Not able to parse date

Viewed 49

I am stuck trying to parse this date string, can any one please help, getting the below error while parsing

Exception in thread "main" java.text.ParseException: Unparseable date: "2022-09-22T11:22:39GMT-06:00" at java.base/java.text.DateFormat.parse(DateFormat.java:396) at Main.main(Main.java:16)

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.OffsetDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;
import java.text.ParseException;

public class Main {
   public static void main(String[] args) throws ParseException {
   String dateString = "2022-09-22T11:22:39GMT-06:00";
   System.out.println("Hello World!");
   SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd     hh:mm:ss a");
   simpleDateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
   simpleDateFormat.parse(dateString);
  }
}

Can any one help this parse, not able to parse this string

2 Answers

tl;dr

Use java.time. Never use the legacy date-time classes SimpleDateFormat, Date, Calendar, etc.

OffsetDateTime
.parse( "2022-09-22T11:22:39GMT-06:00".replace( "GMT" , "" ) ) 
.withOffsetSameInstant( ZoneOffset.UTC ) 
.format(
    DateTimeFormatter
    .ofLocalizedDateTime( … )
    .withLocale( … )
)

ISO 8601

The ideal solution would include educating the publisher of your date about the ISO 8601 standard for communicating date-time values as text.

Your input text nearly complies with ISO 8601. The GMT part is redundant as we know -06:00 means “six hours behind UTC/GMT”.

To comply with ISO 8601, delete that GMT text.

String inputIso8601 = input.replace( "GMT" , "" ) ;

java.time

You are using terrible date-time classes that were years ago supplanted by the modern java.time classes defined in JSR 310. Oracle Corp provides a tutorial on java.time at no cost.

OffsetDateTime

Your input represents a date and time as seen with a particular offset from UTC. So parse as a OffsetDateTime object.

OffsetDateTime odt = OffsetDateTime.parse( inputIso8601 ) ;

Adjust to UTC

Apparently you want to adjust that to be the same moment but as seen with an offset of zero hours-minutes-seconds from UTC.

We have a constant for zero offset: ZoneOffset.UTC.

OffsetDateTime odtInUtc = odt.withOffsetSameInstant( ZoneOffset.UTC ) ;

Generate text

Next you want to generate some text to represent the value of our odtInUtc object. You can do that in either of two ways. I recommend the first.

Both of these have been covered many times already on Stack Overflow. Search to learn more.

If you set the GMT in the setTimeZone command why do you need the GMT in the dateString?

Instead of: SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss a");

Try this: SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");

Related