Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get time with hour, minute, second, millisecond, microsecond

Tags:

java

date

I have this code:

SimpleDateFormat sDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

I know that this code return hour, minute, second in the time. How i can get also the millisecond and microsecond??

like image 468
lolo Avatar asked Dec 07 '22 17:12

lolo


2 Answers

You won't have microseconds, because a Date stores the number of milliseconds since Jan. 1 1970. For the milliseconds, use S, as documented in the javadoc.

like image 102
JB Nizet Avatar answered Dec 09 '22 06:12

JB Nizet


The only way to get micro-seconds is to parse the string yourself. Note: Date should be used to store micro-seconds, but you can use a long. (which you can also use for milli-seconds or nano-seconds)

private static final String YEARS_TO_MINUTES = "yyyy-MM-dd HH:mm";
private static final SimpleDateFormat YEARS_TO_MINUTES_SDF = new SimpleDateFormat(YEARS_TO_MINUTES);

public static long parseMicroSeconds(String text) throws ParseException {
    long timeMS;
    synchronized (YEARS_TO_MINUTES_SDF) {
        timeMS = YEARS_TO_MINUTES_SDF.parse(text.substring(0, YEARS_TO_MINUTES.length())).getTime();
    }
    long microSecs = 0;
    if (text.length() > YEARS_TO_MINUTES.length() + 1) {
        double secs = Double.parseDouble(text.substring(YEARS_TO_MINUTES.length() + 1));
        microSecs = (long) (secs * 1e6 + 0.5);
    }
    return timeMS * 1000 + microSecs;
}

public static String formatMicroSeconds(long timeMicroSeconds) {
    String dateTime;
    synchronized (YEARS_TO_MINUTES_SDF) {
        dateTime = YEARS_TO_MINUTES_SDF.format(new Date(timeMicroSeconds / 1000));
    }
    long secs = timeMicroSeconds % 60000000;
    return dateTime + String.format(":%09.6f", secs / 1e6);
}


public static void main(String... args) throws ParseException {
    String dateTime = "2011-01-17 19:27:59.999650";
    long timeUS = parseMicroSeconds(dateTime);
    for (int i = 0; i < 5; i++)
        System.out.println(formatMicroSeconds(timeUS += 175));
}

prints

2011-01-17 19:27:59.999825
2011-01-17 19:28:00.000000
2011-01-17 19:28:00.000175
2011-01-17 19:28:00.000350
2011-01-17 19:28:00.000525

You can do similarly if you need nano-timings.

like image 21
Peter Lawrey Avatar answered Dec 09 '22 05:12

Peter Lawrey