import java.util.Calendar;
import java.util.Date;
public class Util{
public final static long DAY = 24 * 3600 * 1000;
public final static int YEAR_MASK = (1 << Calendar.YEAR);
public final static int MONTH_MASK = (1 << Calendar.MONTH);
public final static int DAY_MASK = (1 << Calendar.DAY_OF_MONTH);
public final static int HOUR_MASK = (1 << Calendar.HOUR);
public final static int HOUR_OF_DAY_MASK = (1 << Calendar.HOUR_OF_DAY);
public final static int MINUTE_MASK = (1 << Calendar.MINUTE);
public final static int SECOND_MASK = (1 << Calendar.SECOND);
public final static int MILLISECOND_MASK = (1 << Calendar.MILLISECOND);
public final static int AM_PM_MASK = (1 << Calendar.AM_PM);
/**
* Gets formatted time
*
* @param time time in ms since 01/01/70
* @param symbols if true, inserts symbols
* @param fields Calendar.MONTH
,
* Calendar.DAY
,
* Calendar.YEAR
,
* Calendar.HOUR
,
* Calendar.HOUR_OF_DAY
,
* Calendar.MINUTE
,
* Calendar.SECOND
,
* Calendar.MILLISECOND
,
* Calendar.AM_PM
*
* @returns formatted time
*/
public static String formatTime(long time, boolean symbols, int fields)
{
StringBuffer sb = new StringBuffer();
Calendar calendar = Calendar.getInstance();
String year;
int hour;
calendar.setTime(new Date(time));
if ((fields & MONTH_MASK) != 0)
{
sb.append(twoDigit(calendar.get(Calendar.MONTH)+1));
}
if ((fields & DAY_MASK) != 0)
{
if (symbols) sb.append("/");
sb.append(twoDigit(calendar.get(Calendar.DAY_OF_MONTH)));
}
if ((fields & YEAR_MASK) != 0)
{
if (symbols) sb.append("/");
//get last two digits of year
year = Integer.toString(calendar.get(Calendar.YEAR));
sb.append(year.substring(year.length()-2));
}
if ((fields & HOUR_MASK) != 0 || (fields & HOUR_OF_DAY_MASK) != 0)
{
if ((fields & HOUR_MASK) != 0)
hour = calendar.get(Calendar.HOUR);
else if ((fields & HOUR_OF_DAY_MASK) != 0)
hour = calendar.get(Calendar.HOUR_OF_DAY);
else
hour = 0;
if (hour == 0) hour = 12;
sb.append(twoDigit(hour));
}
if ((fields & MINUTE_MASK) != 0)
{
if (symbols) sb.append(":");
sb.append(twoDigit(calendar.get(Calendar.MINUTE)));
}
if ((fields & SECOND_MASK) != 0)
{
if (symbols) sb.append(":");
sb.append(twoDigit(calendar.get(Calendar.SECOND)));
}
if ((fields & MILLISECOND_MASK) != 0)
{
if (symbols) sb.append(".");
sb.append(threeDigit(calendar.get(Calendar.MILLISECOND)));
}
if ((fields & AM_PM_MASK) != 0)
{
sb.append(calendar.get(Calendar.AM_PM) == Calendar.AM ? "A":"P");
}
return sb.toString();
}
private static String twoDigit(int value) {
if (value < 10) {
return "0" + value;
} else {
//get last two digits
String str = Integer.toString(value);
return str.substring(str.length() - 2);
}
}
private static String threeDigit(int value) {
if (value < 10) {
return "00" + value;
} else if (value < 100) {
return "0" + value;
} else {
return "" + value;
}
}
}