Reputation: 31
I have a String of western date.I want is to have it in Japanese format.
String date = "2015-06-01";
I want is to have it in Japanese format. Please help me!
output = 平成27年6月1日
Upvotes: 1
Views: 1605
Reputation: 1
LocalDate localDate = LocalDate.now();
DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyyy/MM/dd").withChronology(IsoChronology.INSTANCE)
.withLocale(Locale.ENGLISH);
DateTimeFormatter japanDateFormat = DateTimeFormatter.ofPattern("yyyy年MM月dd日")
.withChronology(IsoChronology.INSTANCE)
.withLocale(Locale.JAPAN);
}
System.out.println(localDate.format(dateFormat));
System.out.println(localDate.format(japanDateFormat));
Output is:
2022/06/15
2022年06月15日
Upvotes: 0
Reputation: 86296
As a minor supplement to the answer by Meno Hochschild, if you want to use java.time for this, you may do it in this way:
DateTimeFormatter japaneseEraDtf = DateTimeFormatter.ofPattern("GGGGy年M月d日")
.withChronology(JapaneseChronology.INSTANCE)
.withLocale(Locale.JAPAN);
String date = "2015-06-01";
LocalDate gregorianDate = LocalDate.parse(date);
JapaneseDate japaneseDate = JapaneseDate.from(gregorianDate);
System.out.println(japaneseDate.format(japaneseEraDtf));
Output is:
平成27年6月1日
I think it was what you asked for.
If I have understood correctly, java.time does not format the first year of an era in the way usually expected by Japanese, which Meno Hochschild’s Time4A library does, so all things being equal you will prefer his answer.
I have stolen the formatter from this answer by buræquete.
Upvotes: 1
Reputation: 44061
You can use my lib Time4A which is also available for lower Android API levels and then use its JapaneseCalendar:
String input = "2015-06-01";
PlainDate gregorian = Iso8601Format.EXTENDED_DATE.parse(input);
ChronoFormatter<JapaneseCalendar> f = // immutable, so you can make it static
ChronoFormatter.ofStyle(DisplayMode.MEDIUM, Locale.JAPANESE, JapaneseCalendar.axis());
String output = f.print(gregorian.transform(JapaneseCalendar.axis()));
System.out.println(output); // 平成27年6月1日
I have also done an experiment with the java.time
-package which is available since API level 26, but could not quickly find a way to produce the format you want:
DateTimeFormatter dtf =
DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)
.withLocale(Locale.JAPAN)
.withChronology(JapaneseChronology.INSTANCE);
JapaneseDate japaneseDate = JapaneseDate.from(LocalDate.parse(input));
System.out.println(dtf.format(japaneseDate)); // H27.06.01
The numbers are correct but it does not use Japanese symbols and letters, despite of the fact that I specified the Japan locale. Maybe a workaround using the builder and a hand-made pattern will help further. Note that my experiment was executed in a Java-8-environment. Maybe Android or newer Java versions are different?!
Upvotes: 1