static方法总是同时返回

Sud*_*pta 1 java static-methods date

我想在我的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());
}
Run Code Online (Sandbox Code Playgroud)

如何在不创建Util类实例的情况下以特定格式获取更新时间.可能吗.

Rog*_*sjö 6

由于重复使用相同的Date对象,因此总是得到相同的时间.解析类时会创建Date对象.要获取每次使用的当前时间:

private static SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");

public static String getCurrentDate() {
    Date date = new Date();
    return timeFormatter.format(date);
}
Run Code Online (Sandbox Code Playgroud)

甚至

public static String getCurrentDate() {
    Date date = new Date();
    SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
    return timeFormatter.format(date);
}
Run Code Online (Sandbox Code Playgroud)

因为SimpleDateFormat不是线程安全的.

由于您只想要当前时间,因此甚至无需创建新日期.

public static String getCurrentDate() {
    SimpleDateFormat timeFormatter= new SimpleDateFormat("hh:mm:ss a");
    return timeFormatter.format(System.currentTimeMillis());
}
Run Code Online (Sandbox Code Playgroud)

如果您只想要输出而不能解析,则可以使用

public static String getCurrentDate() {
    return String.format("%1$tr", System.currentTimeMillis());
}
Run Code Online (Sandbox Code Playgroud)