2
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??

xingbin
  • 27,410
  • 9
  • 53
  • 103
KNDheeraj
  • 834
  • 8
  • 23
  • What are you really trying to obtain? A string like `02-Feb'19 01:55 PM`? And what error are you getting? – Ole V.V. Feb 05 '19 at 13:20

3 Answers3

3

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
     }
}
xingbin
  • 27,410
  • 9
  • 53
  • 103
1

If you use java.time.LocalDateTime (which you should since Java 8), you can use different DateTimeFormatters, which you can configure (give them a pattern) to not trimming trailing zeros. See the following example using your date String with a slightly adjusted pattern:

LocalDateTime ldt = LocalDateTime.parse("2019-02-02T13:55:00Z", DateTimeFormatter.ISO_DATE_TIME);
System.out.println(ldt.format(DateTimeFormatter.ofPattern("dd-MMM\''YY HH:mm:ss")));

This prints 02-Feb'19 13:55:00, which hopefully is what you want.

deHaar
  • 17,687
  • 10
  • 38
  • 51
1

SimpleDateFormat is from an old and obsolete way of working with Dates. It is also not Thread-safe and has a lot of other problems. In other words don't use it. You need to use DateTimeFormatter Please read the javadoc (link provided). It gives detailed explanation how to use it. However the cause of your problem is that in your format mask you are missing placeholder for seconds, thus when your String has seconds it doesn't conform with your format. Change the format to dd-MMM-YY HH:mm:ss aa emphases on "ss" - the missing seconds placeholder and it will work

Michael Gantman
  • 7,315
  • 2
  • 19
  • 36