0

The time I have is -> September 15 2020 11:10:25

I am using this code to format it in Japanese

 timeFormatStr = "YYYY MMMMMMMMMM DD HH:mm:ss z"; 
 SimpleDateFormat sd = new SimpleDateFormat(timeFormatStr, locale);
 timeStr = sdf.format(new Date(time));

The timeStr looks like this (does not look right).

2020 9月 259 23:10:25 UTC

Any idea what the format string should be? I checked that the locale is - ja_JP.eucjp

Thanks

Tas
  • 115
  • 3
  • 12
  • [This](https://stackoverflow.com/questions/63911330/how-to-convert-a-sequence-of-characters-into-a-date-format-to-store-in-the-datab/63911886#63911886) might be helpful – Spectric Sep 16 '20 at 02:10
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `ZonedDateTime` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Sep 16 '20 at 05:26
  • Not knowing Japanese, could you tell us your expected result and point out precisely in what way the string that you got doesn’t look right? Thank you. – Ole V.V. Sep 16 '20 at 05:27

1 Answers1

2

YYYY MMMMMMMMMM DD HH:mm:ss z is not how the Japanese format their dates and times. You should use DateTimeFormatter, and call ofLocalizedDateTime and withLocale. This will produce a formatter that produces strings in a native Japanese format.

String formatted = DateTimeFormatter
        .ofLocalizedDateTime(FormatStyle.FULL) // choose a style here
        .withLocale(Locale.JAPANESE)
        .format(new Date(time).toInstant().atZone(ZoneOffset.UTC)); // choose a timezone here
System.out.println(formatted); // 1970年1月1日木曜日 0時00分00秒 Z

You shouldn't really be using Dates anymore. You should instead give the DateTimeFormatter a ZonedDateTime directly.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • With this code, the time string is -> 16 9月 2020 11:02:05 I wanted the time in YYYY MMMMMMM DD format. – Tas Sep 16 '20 at 16:17
  • @Tas but that’s not how the Japanese format their dates. They go yyyy年MM月dd日. [My code will produce an output like the one shown in the comment.](https://ideone.com/WJYkbj) – Sweeper Sep 17 '20 at 01:26
  • @Tas I’m sorry, it still isn’t clear to me. Could you give us **an example** of how you believe that YYYY MMMMMMM DD should look like? Asking because I understand that you are neither satisfied with how it looks in your question nor in this answer, but I don’t yet understand what’s wrong with either of them. – Ole V.V. Sep 17 '20 at 05:03