Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get locale specific date/time format in Java

I have use case in java where we want get the locale specific date. I am using DateFormat.getDateInstance

final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM,
                Locale.forLanguageTag(locale)));

This translates the dates but ja-JP this translates the date "17 January 2019" to "2019/01/17" but I need something like "2019年1月17日". For all other locales this correctly translates the date.

Please let know if there is other method to get this.

like image 424
Jhutan Debnath Avatar asked Jan 17 '19 07:01

Jhutan Debnath


People also ask

How do you check if a date is in a particular format in Java?

DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); formatter. setLenient(false); try { Date date= formatter. parse("02/03/2010"); } catch (ParseException e) { //If input date is in different format or invalid. } formatter.

How will you format a date based on a locale after you have obtained a DateFormat object?

To format a date for the current Locale, use one of the static factory methods: myString = DateFormat. getDateInstance(). format(myDate);

How do you check if the date is in YYYY MM DD format in Java?

SimpleDateFormat – yyyy-M-d For legacy Java application, we use SimpleDateFormat and . setLenient(false) to validate a date format.


2 Answers

This worked for me:

public static void main(String[] args) throws IOException {
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.FULL, Locale.JAPAN);
    Date today = new Date();
    System.out.printf("%s%n", dateFormat.format(today));
}

and MEDIUM acted exactly how you said

UPD: or using newer ZonedDataTime as Michael Gantman suggested:

public static void main(String[] args) throws IOException {
    ZonedDateTime zoned = ZonedDateTime.now();
    DateTimeFormatter pattern = DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL).withLocale(Locale.JAPAN);
    System.out.println(zoned.format(pattern));
}
like image 168
Akceptor Avatar answered Sep 27 '22 21:09

Akceptor


Just to mention: SimpleDateFormat is an old way to format dates which BTW is not thread safe. Since Java 8 there are new packages called java.time and java.time.format and you should use those to work with dates. For your purposes you should use class ZonedDateTime Do something like this:

ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("..."));

to find out correct zone id for Japan use

ZoneId.getAvailableZoneIds()

Later on to format your Date correctly use class DateTimeFormatter

like image 40
Michael Gantman Avatar answered Sep 27 '22 23:09

Michael Gantman