Indonesian Times in SimpleDateFormat

前端 未结 1 1648
温柔的废话
温柔的废话 2021-01-16 18:40

I have a date with this format:

Tue Mar 03 00:00:00 WIB 2015

How can I format it into:

2015-03-03

What I

1条回答
  •  一向
    一向 (楼主)
    2021-01-16 19:23

    First to note: The classname LocalDate looks like Joda-Time but you have to use SimpleDateFormat because Joda-Time cannot parse timezone names or abbreviations.

    Second: Your parsing pattern is wrong and uses YYYY instead of yyyy (Y is year of week-date, not the normal calendar year). Using Y can cause wrong date output.

    Third: It is necessary to specify the locale as English because you have English Labels in your input (especially if your default locale is not an English - otherwise you get an exception).

    Fourth: The pattern letter z is correct and will process timezone names like "WIB". Again: It is important to specify the locale here. The use of "Z" as in another answer given normally denotes a timezone offset but is allowed for parsing timezone names according to the Javadoc. So I recommend "z" for clarity (as you have done).

    SimpleDateFormat formatIncoming =
        new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy", Locale.ENGLISH);
    SimpleDateFormat formatOutgoing = new SimpleDateFormat("yyyy-MM-dd");
    TimeZone tz = TimeZone.getTimeZone("Asia/Jakarta");
    System.out.println(tz.getDisplayName(false, TimeZone.SHORT, Locale.ENGLISH)); // WIB
    
    formatOutgoing.setTimeZone(tz);
    String s = formatOutgoing.format(formatIncoming.parse("Tue Mar 03 00:00:00 WIB 2015"));
    
    System.out.println("Date in Indonesia: " + s); // 2015-03-03
    

    0 讨论(0)
提交回复
热议问题