rakesh venkatraman
rakesh venkatraman

Reputation: 25

iso date and time not giving in the required format

  1. what format should i use to get required output

  2. for input "2016-04-01T16:23:19.8995" o/p=2016-04-01T16:23:19.900 therefore .8995 rounded off to .900 in the output

    3.similarly for input "2016-04-01T16:23:19.9995" expected output is 2016-04-01T16:23:20.000 not getting expected output


public class Date {

public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat(
            "yyyy-MM-dd'T'HH:mm:ss.SSSS");
    System.out.println(sdf.parse("2016-04-01T16:23:19.9995"));

}

}

Upvotes: 1

Views: 86

Answers (2)

Anmol Gupta
Anmol Gupta

Reputation: 2957

In Java 8, you can use java.time.LocalDateTime.

LocalDateTime time = LocalDateTime.parse("2016-04-01T16:23:19.9995");
System.out.println(time); //gives 2016-04-01T16:23:19.999500 as output

LocalDateTime should give you at-least the desired format. And as Peter answered, S is milliseconds no matter how many S you use.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533442

S means millisecond no matter how many S you use.

If you want this behaviour, I suggest you

  • parse that portion yourself or
  • use JSR 310 which can handle nanoseconds in timestamps.

Using the DateTime library in Java 8.

String dateTime = "2016-04-01T16:23:19.8995";
LocalDateTime localDateTime = LocalDateTime.parse(dateTime);
System.out.println(localDateTime);

prints

2016-04-01T16:23:19.899500

if you want to round it you can do.

LocalDateTime inMillis = localDateTime.plusNanos(500_000).truncatedTo(ChronoUnit.MILLIS);
System.out.println(inMillis);

prints

2016-04-01T16:23:19.900

Upvotes: 1

Related Questions