Pergunta

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.

Foi útil?

Solução

I mean cant we simply output variable now instead of strdate.

Well you could return now.toString() - but that will use the format that Date.toString() happens to choose, whereas you want a specific format. The point of the SimpleDateFormat object in this case is to convert a Date (which is a point in time, without reference to any particular calendar or time zone) into a String, applying an appropriate time zone, calendar system, and text format (in your case HH:mm:ss).

You can still simplify your method somewhat though, by removing the local variables (which are each only used once):

public static String getCurrentTimeStamp() {
    return new SimpleDateFormat("HH:mm:ss").format(new Date());
}

Or maybe you'd find it more readable to keep the variable for the date format, but not the date and the return value:

public static String getCurrentTimeStamp() {
    DateFormat format = new SimpleDateFormat("HH:mm:ss");
    return format.format(new Date());
}

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.

Outras dicas

public static String getCurrentTimeStampwithTimeOnly() {
    return new SimpleDateFormat("HH:mm:ss").format(new Date());
}

Helps you to do this.

you can call this line any time

Date now = new Date(); 

The now variable will contain the current timestamp The format function just generates a String from this timestamp

also take a look at the Calendar class ( Calendar.getInstance())

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top