Date and time formatting depending on locale

2019-01-22 18:13发布

问题:

I'm new to both Java and Android development so this might be a stupid question, but I've been searching for days now and can't find a solution:

I try to output a java.util.Date depending on the user's locale.

Searching on StackOverflow lead me to this:

java.util.Date date = new Date();
String dateString = DateFormat.getDateFormat(getApplicationContext()).format(date);

This outputs:

20/02/2011

On my french localized phone. Almost fine.

How can I also output the hours, minutes and seconds parts of the Date, using the user's locale ? I've been looking in the android documentation but couldn't find anything.

Many thanks.

回答1:

Use android.text.format.DateFormat.getTimeFormat()

ref: http://developer.android.com/reference/android/text/format/DateFormat.html



回答2:

tl;dr

ZonedDateTime.now( ZoneId.of( "Asia/Kolkata" ) )
             .format( DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( Locale.FRENCH ) )

java.time

The code in the Question uses troublesome old date-time classes, now legacy, supplanted by the java.time classes built into Java 8 and later.

Locale and time zone have nothing to do with each other. Locale determines the human language and cultural norms used when generating a String to represent a date-time value. The time zone determines the wall-clock time of a particular region used to represent a moment on the timeline.

The Instant class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Instant instant = Instant.now();

2016-10-12T07:21:00.264Z

Apply a time zone to get a ZonedDateTime. I arbitrarily choose to show this moment using India time zone. Same moment, same point on the timeline.

ZoneId z = ZoneId.of( "Asia/Kolkata" );
ZonedDateTime zdt = instant.atZone( z );

2016-10-12T12:51:00.264+05:30[Asia/Kolkata]

Generate a String using the locale of Québec Canada. Let java.time automatically localize the string.

Locale l = Locale.CANADA_FRENCH;
DateTimeFormatter f = DateTimeFormatter.ofLocalizedDateTime ( FormatStyle.FULL ).withLocale ( l );
String output = zdt.format ( f );  // Indian time zone with Québécois presentation/translation.

mercredi 12 octobre 2016 12 h 51 IST


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to java.time.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

  • Java SE 8 and SE 9 and later
    • Built-in.
    • Part of the standard Java API with a bundled implementation.
    • Java 9 adds some minor features and fixes.
  • Java SE 6 and SE 7
    • Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
    • The ThreeTenABP project adapts ThreeTen-Backport (mentioned above) for Android specifically.
    • See How to use….

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.



回答3:

java.text.DateFormat has all the functions you could possibly need:

DateFormat.getDateInstance()

DateFormat.getTimeInstance()

But the one you need is:

DateFormat.getDateTimeInstance() You can also specify the length of the date / time part and the locale. The end result would be:

DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.SHORT, Locale.FRENCH).format(Date);

Source: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html



回答4:

DateFormat.getTimeInstance() gets the time formatter with the default formatting style for the default locale. You can also pass a style and a Locale.



回答5:

public static String formatDate(Date date, boolean withTime)
{
    String result = "";
    DateFormat dateFormat;

    if (date != null)
    {
        try
        {
            String format = Settings.System.getString(context.getContentResolver(), Settings.System.DATE_FORMAT);
            if (TextUtils.isEmpty(format))
            {
                dateFormat = android.text.format.DateFormat.getDateFormat(context);
            }
            else
            {
                dateFormat = new SimpleDateFormat(format);
            }
            result = dateFormat.format(date);

            if (withTime)
            {
                dateFormat = android.text.format.DateFormat.getTimeFormat(context);
                result += " " + dateFormat.format(date);
            }
        }
        catch (Exception e)
        {
        }
    }

    return result;
}


回答6:

If you want the hours seconds and milli seconds of current locale then use Calendar.getInstance().getTime() will give you time of current locale