javadatetimejava-8date-conversionparseexception

Date Function is trimming seconds where seconds is 00


OffsetDateTime odtB = OffsetDateTime.parse("2019-02-02T13:55:00Z");
odtB.toString()

prints 2019-02-02T13:55 as output. As because of this my conversion function is throwing error!!

SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM\''YY HH:mm aa");
String parsedDate = odtB.format(otdB);

How to stop OffsetDateTime or anyOther Java DateTime class from trimming seconds off when seconds are 00??


Solution

  • In java8, you do not need SimpleDateFormat any more, it's troublesome.

    I suggest to use ISO_OFFSET_DATE_TIME:

    The ISO date-time formatter that formats or parses a date-time with an offset, such as '2011-12-03T10:15:30+01:00'.

    Example:

    import java.util.*;
    import java.time.*;
    import java.time.format.*;
    
    public class HelloWorld{
    
         public static void main(String []args){
            OffsetDateTime odtB = OffsetDateTime.parse("2019-02-02T13:55:00Z");
            DateTimeFormatter f = DateTimeFormatter.ISO_OFFSET_DATE_TIME;
            System.out.print(f.format(odtB)); // 2019-02-02T13:55:00Z
         }
    }