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

后端 未结 7 917
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 12:03

    First you have to tell Java what your system LOCALE looks like.

    Check Java System.
    String locale = System.getProperty("user.language")

    And then format the date accordinly (SimpleDateFormat)
    SimpleDateFormat(String pattern, Locale locale)

    Refer to the practical Java code for a working example...

    String systemLocale = System.getProperty("user.language");
    String s;
    Locale locale; 
    
    locale = new Locale(systemLocale );
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
    System.out.println(s);
    // system locale is PT outputs 16/Jul/2011
    
    locale = new Locale("us");
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
    System.out.println(s);
    // outputs Jul 16, 2011
    
    locale = new Locale("fr");
    s = DateFormat.getDateInstance(DateFormat.MEDIUM, locale).format(new Date());
    System.out.println(s);
    // outputs 16 juil. 2011  
    
    0 讨论(0)
提交回复
热议问题