0

I want to format this date 2021-12-17T06:23:49.000000Z to read as Dec 17,2021. How do I achieve that?

This is what I have tried:

SimpleDateFormat spf=new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSS.'Z'");
Date newDate= null;
try {
    newDate = spf.parse(date);
} catch (ParseException e) {
    e.printStackTrace();
}
spf= new SimpleDateFormat("dd MMM yyyy");
date = spf.format(newDate);
Dada
  • 6,313
  • 7
  • 24
  • 43
kingsley Dike
  • 31
  • 1
  • 4

1 Answers1

6

The biggest mistake you have here is using the old Date and SimpleDateFormat classes. They are legacy, and have been retained mainly for backwards compatibility. The java.time package provides a far more consistent API. Like,

String date = "2021-12-17T06:23:49.000000Z";
OffsetDateTime inst = OffsetDateTime.ofInstant(Instant.parse(date), 
        ZoneId.systemDefault());
System.out.println(DateTimeFormatter.ofPattern("MMM dd, yyyy").format(inst));

Outputs

Dec 17, 2021
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
  • 2
    Or automatically localize: `DateTimeFormatter.ofLocalizedDate( FormatStyle.MEDIUM ).withLocale( Locale.getDefault() )` – Basil Bourque Dec 19 '21 at 03:09