Java Simple Date formatter displaying wrong value

Viewed 73

Having issue displaying nano seconds using SimpleDateFormat.

SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss:SSSSSSS");     
Date dt = sdf.parse("03.08.2020 05:35:19:7600000"); 
System.out.println("Date  :" + sdf.format(dt) );

Output is: Date :03.08.2020 07:41:59:0000000.

Can you please help make the output show nano seconds as: 7600000? Thanks!

2 Answers

I suggest you switch from the outdated and error-prone legacy date-time API to the modern date-time API.

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        DateTimeFormatter format = DateTimeFormatter.ofPattern("dd.MM.yyyy HH:mm:ss:SSSSSSS");
        LocalDateTime ldt = LocalDateTime.parse("03.08.2020 05:35:19:7600000", format);
        System.out.println(ldt);
    }
}

Output:

2020-08-03T05:35:19.760

You can also try the following and then parse the required date :

sdf.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta");
Related