Localized date format in Java

前端 未结 6 1182
夕颜
夕颜 2020-12-11 21:08

I have a timestamp in millis and want to format it indicating day, month, year and the hour with minutes precission.

I know I can specify the format like this:

相关标签:
6条回答
  • 2020-12-11 21:19

    Is using joda time (http://joda-time.sourceforge.net/) out of the question? If not, then I would wholeheartedly recommend using this wonderful library instead of the cumbersome Java API.

    If not, you could use DateFormat.getDateTimeInstance(int, int, Locale)

    The first int is the style for hour, the other is the style for time, so try using:

    DateFormat f = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.getDefault());
    String formattedDate = f.format(new Date());
    System.out.println("Date: " + formattedDate);
    

    See if this suits you.

    Output for Locale.GERMANY: Date: 25.07.13 10:57

    Output for Locale.US: Date: 7/25/13 10:57 AM

    0 讨论(0)
  • 2020-12-11 21:20

    You can use method getDateTimeInstance, of DateFormat. Here the getDateTimeInstance method takes 3 arguments

    1. the style of Date field
    2. the style of time field
    3. the Locale using which pattern is auto extracted

      DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.US);
      System.out.println(DATE_FORMAT.format(d));
      DATE_FORMAT = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.FRENCH);
      System.out.println(DATE_FORMAT.format(d));
      
    0 讨论(0)
  • 2020-12-11 21:29

    Try some thing like this

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
        String formatted = simpleDateFormat.format(900000);
        System.out.println(simpleDateFormat.parse(formatted));
    
    0 讨论(0)
  • 2020-12-11 21:33

    But it does not show the hour. How can I do it?

    You have to call DateFormat.getDateTimeInstance(int, int, Locale)

    DateFormat.getDateInstance(int, Locale) => Gets the date formatter with the given formatting style for the given locale.

    While

    DateFormat.getDateTimeInstance(int, int, Locale) => Gets the date/time formatter with the given formatting styles for the given locale.

    0 讨论(0)
  • 2020-12-11 21:41

    You can use something like this:

    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy HH:mm", Locale.getDefault());
    String formatted = sdf .format(900000);
    System.out.println(simpleDateFormat.parse(formatted));
    
    0 讨论(0)
  • 2020-12-11 21:41

    Using Joda-Time you could detect the system setting and use different time format:

    String format;
    
    if (DateFormat.is24HourFormat(context)) {
      format = "MM/dd/yy, hh:mm";
    }
    else {
      format = "MM/dd/yy, h:mm aa";
    }
    
    DateTimeFormatter formatter = DateTimeFormat.forPattern(format);
    formatter.print(new DateTime());
    
    0 讨论(0)
提交回复
热议问题