Joda time gives parse Exception for BST timezone but not for GMT

504 Views Asked by At

I'm trying to compare current date with an input date, received in this format "EEE MMM dd HH:mm:ss zzz yyyy"

This piece of code works when my input string is Wed Apr 01 09:00:00 GMT 2020 but doesn't work if its Wed Apr 01 09:00:00 BST 2020 .

        DateTime currentTime =DateTime.now().withZone(DateTimeZone.forID("Europe/London"));
        DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss zzz yyyy");
        DateTime inputDateTime = fmt.parseDateTime("Wed Apr 01 09:00:00 BST 2020");


        if (inputDateTime.isBefore(currentTime))
            Log.d(TAG, "if ");
        else
            Log.d(TAG, "else ");

Any idea on what am I doing wrong? Also, feel free to suggest if there's a better way to do it (can't use new Java date and time library, since we support android API 19+ )

3

There are 3 best solutions below

2
On

I'm not sure if this meets your requirements for the Andriod API 19+, but here is something for the date formatting with SimpleDateFormatter

    String pattern = "EEEEE MMMMM yyyy HH:mm:ss";
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
    String date = simpleDateFormat.format(new Date());
    System.out.println(date);

Hope this solves your problem!

2
On

Docs has mentioned that Time zone names cannot be parsed in joda DateTimeFormat because time zone abbreviations are ambiguous and the parser can't know which time zone it is exactly

Zone names: Time zone names ('z') cannot be parsed.

For example

  • BST can be British Summer Time or Bangladesh Standard Time or Bougainville Standard Time

  • PST can be Pacific Standard Time or Pakistan Standard Time

  • CST could be Central Standard Time (USA), China Standard Time, or Cuba Standard Time
  • EST could be Eastern Standard Time (USA), or Eastern Standard Time (Australia).

And the best way to is to replace BST with appropriate iso timezone code here (for example Europe/Isle_of_Man), and then simple use "EEE MMM dd HH:mm:ss ZZZ yyyy" DateTimeFormat

DateTimeFormatter fmt = DateTimeFormat.forPattern("EEE MMM dd HH:mm:ss ZZZ yyyy");
DateTime inputDateTime = fmt.parseDateTime("Wed Apr 01 09:00:00 Europe/Isle_of_Man 2020");

System.out.println(inputDateTime);  //2020-04-01T09:00:00.000+01:00
0
On

If you use ThreeTen Android Backport instead of Joda-Time, and you should, then it parses fine:

import org.threeten.bp.ZonedDateTime;
import org.threeten.bp.format.DateTimeFormatter;
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy");
ZonedDateTime inputDateTime = ZonedDateTime.parse("Wed Apr 01 09:00:00 BST 2020", fmt);
System.out.println(inputDateTime);

Output

2020-04-01T09:00+01:00[Europe/Isle_of_Man]