I have this code copied from one of questions from SO:
public static String getCurrentTimeStamp() {
SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date now = new Date();
String strDate = sdfDate.format(now);
return strDate;
}
I want to get only the system time and NOT the date. Then I must change second line of code to:
SimpleDateFormat sdfDate = new SimpleDateFormat(" HH:mm:ss") ;
Then, DATE() must get the current time. Clear upto this point but I can’t understand the format() function used.
I mean cant we simply output variable now instead of strdate?
Is it just because that the return type of function getCurrentTimeStamp() is String?
Please clarify and if there is any other simpler and one line code for getting system time alone, do share.
Well you could return
now.toString()– but that will use the format thatDate.toString()happens to choose, whereas you want a specific format. The point of theSimpleDateFormatobject in this case is to convert aDate(which is a point in time, without reference to any particular calendar or time zone) into aString, applying an appropriate time zone, calendar system, and text format (in your caseHH:mm:ss).You can still simplify your method somewhat though, by removing the local variables (which are each only used once):
Or maybe you’d find it more readable to keep the variable for the date format, but not the date and the return value:
Personally I’d recommend using Joda Time instead, mind you – it’s a much nicer date/time API, and its formatted are thread-safe so you could easily keep a reference to a single formatting object.