Indonesian Times in SimpleDateFormat

2020-05-03 11:45发布

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 currently tried:

val today_date = new LocalDate()
val formatIncoming = new java.text.SimpleDateFormat("EEE MMM dd HH:mm:ss z YYYY")
val formatOutgoing = new java.text.SimpleDateFormat("yyyy-MM-dd")
formatOutgoing.format(formatIncoming.parse(data.cheque_date.toString))
//output
2014-12-30

Any solution?

1条回答
神经病院院长
2楼-- · 2020-05-03 12: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
查看更多
登录 后发表回答