tags:

views:

2904

answers:

3

The below code gives me current time. but it does not tell anything about millisecond

public static String getCurrentTimeStamp() {
      SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
      Date now = new Date();
      String strDate = sdfDate.format(now);
      return strDate;
}

I get date in the format 2009-09-22 16:47:08 (YYYY-MM-DD HH:MI:Sec)

But I want to retrieve current time in the format 2009-09-22 16:47:08.128 ((YYYY-MM-DD HH:MI:Sec.Ms)

where 128 tells the millisecond.

SimpleTextFormat will work fine. Here the lowest unit of time is second. but I want millisecond also.

+11  A: 

You only have to add the millisecond field in your date format string:

new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

The API doc of SimpleDateFormat describes the format string in detail.

Michael Borgwardt
+9  A: 
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
JayJay
A: 

Here you go:

 GregorianCalendar now = new GregorianCalendar();//gets the current date and time
 int year = now.get(Calendar.YEAR);
 int month = now.get(Calendar.MONTH);
 int day = now.get(Calendar.DATE) + 1; //add one because January is integer 0
 int hour = now.get(Calendar.HOUR_OF_DAY);
 int minute = now.get(Calendar.MINUTE);
 int second = now.get(Calendar.SECOND);

 String output = year + "-" + month + "-" + day+ " " + hour + ":" + minute + ":" + second;
Jay
This is not an answer to the question, and there's a bug in it: your + 1 should be added to month, not to day.
Jesper
Suppose the date and time is 1 Oct 2009, 9:04 AM. Your code would output: "2009-9-2 9:4:0".
Jesper
aside from the bug, thank you, some how I screwed that up, I stand by that this will format a date output as requested by the poster.
Jay
Really? Did you test it? You don't prepend zeroes if the date, month, hour, minute or second is only one digit, so a time like 9:04 AM will show up as "9:4:0" instead of "09:04:00". Besides that, the poster asked how to show milliseconds, which your answer doesn't show.
Jesper