我想在我的Util类中创建一个静态方法,它将以日期格式返回当前时间。因此,我尝试了下面的代码,但它总是返回相同的时间。
private static Date date = new Date();
private static SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
public static String getCurrentDate() {
return formatter.format(date.getTime());
}
如何在不创建Util类的实例的情况下获取特定格式的更新时间。有没有可能。
发布于 2012-09-15 05:52:47
因为重用了相同的Date对象,所以总是得到相同的时间。Date对象是在解析类时创建的。要获取每次的当前时间,请使用:
private static SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
public static String getCurrentDate() {
Date date = new Date();
return timeFormatter.format(date);
}
甚至是
public static String getCurrentDate() {
Date date = new Date();
SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
return timeFormatter.format(date);
}
因为SimpleDateFormat不是线程安全的。
由于您只需要当前时间,因此甚至不需要创建新的日期。
public static String getCurrentDate() {
SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
return timeFormatter.format(System.currentTimeMillis());
}
如果您只想要输出而不需要解析能力,那么可以使用
public static String getCurrentDate() {
return String.format("%1$tr", System.currentTimeMillis());
}
https://stackoverflow.com/questions/12434879
复制相似问题