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

后端 未结 7 931
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: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;
        }
    

提交回复
热议问题