Ranjith Reddy
Ranjith Reddy

Reputation: 183

Convert date with nanoseconds in java

I have a date in this format "2017-05-17 00:31:16.227", I need to convert it to "17-MAY-17 12.31.16.227000000 AM".

String convertTimestamp(Timestamp date) {

    String newstring = null;
    try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss.SSSSSSSSS");
        java.util.Date date1 = dateFormat.parse(date.toString());
        DateFormat sdf = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aa");
        newstring = sdf.format(date1);

    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("new string" + newstring);

    return newstring;
}

but I am getting the value like this **"17-MAY-17 12.31.16.000000227 AM"

Upvotes: 2

Views: 6843

Answers (1)

Basil Bourque
Basil Bourque

Reputation: 338316

You are using the troublesome old legacy date-time classes that are now supplanted by the java.time classes. These legacy classes are limited to milliseconds which means three decimal places in the fraction of a second. So the legacy classes cannot handle the nine digits you desire.

The nine digits of decimal fraction you want means a resolution of nanoseconds rather than milliseconds. Fortunately, the java.time classes have a resolution of nanoseconds.

Parse your input as a LocalDateTime object as it lacks any indication of time zone or offset-from-UTC. Replace the SPACE in middle with a "T" to comply with standard ISO 8601 format.

String input = "2017-05-17 00:31:16.227".replace( " " , "T" ) ;
LocalDateTime ldt = LocalDateTime.parse( input );

You should be able to force the trailing zeros you desire in the decimal fraction in a string representing the value of this LocalDateTime object. Use either a DateTimeFormatter or a DateTimeFormatterBuilder.

Upvotes: 2

Related Questions