How can I set date and time formatting in Java that respects the user's OS settings

后端 未结 7 916
Happy的楠姐
Happy的楠姐 2020-11-28 11:25

I am running my Java app on a Windows 7 machine where my regional settings are set up to format dates as YYYY-mm-dd and time as HH:mm:ss (e.g. \"2011-06-20 07:50:28\"). But

相关标签:
7条回答
  • 2020-11-28 11:48

    Perhaps I'm misunderstanding what you're getting at here but you need to use the Locale.

     DateFormat df = DateFormat.getDateInstance(DateFormat.LONG, Locale.FRANCE);
    

    By using Locale you can control what format for what region you're using.

    0 讨论(0)
  • 2020-11-28 11:55

    You can't do this in pure Java. There is no way Sun/Oracle could make this system independent.

    A quick browse of the .NET libraries gives this page - to quote:

    The user might choose to override some of the values associated with the current culture of Windows through the regional and language options portion of Control Panel. For example, the user might choose to display the date in a different format or to use a currency other than the default for the culture. If the CultureInfo.UseUserOverride property is set to true, the properties of the CultureInfo.DateTimeFormat object, the CultureInfo.NumberFormat object, and the CultureInfo.TextInfo object are also retrieved from the user settings.

    I would suggest that you do this in a way that is system dependent upon Windows if you need this functionality (e.g. access the Windows registry as @laz suggested).

    0 讨论(0)
  • 2020-11-28 11:55

    I looks like you will need to access the Windows registry for this. See this question for various solutions to that read/write to Windows Registry using Java.

    Once you choose one of the many methods of accessing the registry you will need to get the correct key from the registry for the format. This document indicates the key to use is HKEY_USERS\.Default\Control Panel\International.

    When using GNOME in Linux, you can use the gconftool command similar to the reg command for Windows as mentioned in the prior links about the Windows registry. I see the key /apps/panel/applets/clock_screen0/prefs/custom_format in my configuration, though it is blank since I am using the default:

    gconftool -g /apps/panel/applets/clock_screen0/prefs/custom_format
    

    I'm not sure if that is the value you'd want to use for your purposes or not.

    On Mac OS, I'm not sure what you would do.

    0 讨论(0)
  • 2020-11-28 11:59

    Oracle JDK 8 fully supports formatting using user-customized OS regional settings.

    Just set system property java.locale.providers=HOST

    According to https://docs.oracle.com/javase/8/docs/technotes/guides/intl/enhancements.8.html:

    HOST represents the current user's customization of the underlying operating system's settings. It works only with the user's default locale, and the customizable settings may vary depending on the OS, but primarily Date, Time, Number, and Currency formats are supported.

    The actual implementation of this formatter is available in the class sun.util.locale.provider.HostLocaleProviderAdapterImpl. If using system property is not acceptable (say, your don't want to affect the whole application), it's possible to use that provider class directly. The class is internal API, but can be reached using reflection:

    private static DateFormat getSystemDateFormat() throws ReflectiveOperationException {
            Class<?> clazz = Class.forName("sun.util.locale.provider.HostLocaleProviderAdapterImpl");
            Method method = clazz.getMethod("getDateFormatProvider");
            DateFormatProvider dateFormatProvider = (DateFormatProvider)method.invoke(null);
            DateFormat dateFormat = dateFormatProvider.getDateInstance(DateFormat.MEDIUM, Locale.getDefault(Locale.Category.FORMAT));
            return dateFormat;
        }
    
    0 讨论(0)
  • 2020-11-28 11:59
    java -Djava.locale.providers=HOST,CLDR,COMPAT YourProgram
    

    Date and time formats are part of Java’s locale data. Java can get its locale data from up to four sources. Which ones it uses is controlled by the java.locale.providers system property. Default up to Java 8 was JRE,SPI. From Java 9 it’s CLDR,COMPAT. None of these will get you the date and time data from the operating system, but you can get them by supplying the HOST locale provider, for example as in the command line above. When running your program with this property definition, you may for example have:

        DateTimeFormatter systemFormatter
                = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.FULL);
        ZonedDateTime now = ZonedDateTime.now(ZoneId.of("Africa/Bangui"));
        String formattedDateTime = now.format(systemFormatter);
        System.out.println(formattedDateTime);
    

    This will print the current date and time in the format defined by the underlying operating system. To the extend that the operating system supports it you can vary the length of the output by using format styles FULL, LONG, MEDIUM and SHORT.

    For most purposes you will want to have a DateTimeFormatter knowing the format as in the above code. In the rare case where you want to know a format pattern string that is possible too:

        String osFormat = DateTimeFormatterBuilder.getLocalizedDateTimePattern(
                FormatStyle.SHORT, FormatStyle.LONG, IsoChronology.INSTANCE, Locale.getDefault());
    

    The first argument to getLocalizedDateTimePattern is the date format style. The second is the time style.

    0 讨论(0)
  • 2020-11-28 12:01

    I found this Java utility class by JetBrains that retrieves all the custom locale settings from the OS (both from Windows and Mac) and does the correct formatting for you:

    https://github.com/JetBrains/intellij-community/blob/master/platform/util/src/com/intellij/util/text/DateFormatUtil.java

    It's under the Apache 2.0 license so you can probably use it in your project.

    0 讨论(0)
提交回复
热议问题