Home > database >  How to convert datetime from GMT format to yyyy-MM-dd HH:mm:ss?
How to convert datetime from GMT format to yyyy-MM-dd HH:mm:ss?

Time:10-12

How can I convert the following datetime format to yyyy-MM-dd HH:mm:ss?

Tue, 11 Oct 2022 15:59:46 GMT

I already tried this but it doesn't work, it brings the wrong time

Date d = new Date("Tue, 11 Oct 2022 15:59:46 GMT");
SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String f = sdf1.format(d);
System.out.println(f);

It's bringing the wrong time when you print:

2022-10-11 12:59:46

CodePudding user response:

The solution is to set the setTimeZone zone in the SimpleDateFormat. So I can do the conversion later with format.

sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));

full code

Date d = new Date("Tue, 11 Oct 2022 15:59:46 GMT");
SimpleDateFormat sdf1= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
sdf1.setTimeZone(TimeZone.getTimeZone("GMT"));
String f = sdf1.format(d);
System.out.println(f);

CodePudding user response:

tl;dr

ZonedDateTime
.parse( 
    "Tue, 11 Oct 2022 15:59:46 GMT" , 
    DateTimeFormatter.RFC_1123_DATE_TIME 
)
.format (
    DateTimeFormatter.ISO_LOCAL_DATE_TIME
)
.remove( "T" , " " )

java.time

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310.

Parsing text

Your text is in the format defined by an obsolete standard, RFC 1123 / RFC 822.

The java.time.DateTimeFormatter class carries a constant pre-defining a formatter for that: RFC_1123_DATE_TIME.

ZonedDateTime zdt = ZonedDateTime.parse( input , DateTimeFormatter.RFC_1123_DATE_TIME ) ;

Generating text

The format you desire is close to that of a format defined in the modern standard ISO 8601: YYYY-MM-DDTHH:MM:SS.

The DateTimeFormatter class also carries a predefined formatter for the ISO 8601 standard: ISO_LOCAL_DATE_TIME.

Just remove the T to get your desired format.

String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).remove( "T" , " " ) ;
  • Related