I want to make a static method in my Util class which will return the current time in a date formate. So i have tried the below code but it returns always same time.
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());
}
How can i get update time in my specific format without creating an instance of Util class. Is it possible.
You always get the same time since you reuse the same Date object. The Date object is created when the class is resolved. To get the current time each time use:
Or even
as SimpleDateFormat is not thread safe.
As you just want the current time there is even no need to create a new Date.
If you just want the output and not ability to parse you could use