Formatting a calendar date

前端 未结 5 500
不思量自难忘°
不思量自难忘° 2021-02-02 07:06

I just want the date to show up like so:

Saturday, May 26, 2012 at 10:42 PM

Here\'s my code so far:

Calendar calendar = Calendar.get         


        
5条回答
  •  迷失自我
    2021-02-02 07:12

    This is actually a fairly subtle problem to get right, and I've not seen another answer here on SO that addresses both:

    • The Calendar's time zone (which means that it might be showing a different date than local)
    • The device's Locale (which affects the "right" way to format dates)

    The previous answers to this question ignore locale, and other answers that involve conversion to a Date ignore the time zone. So here's a more complete, general solution:

    Calendar cal = Calendar.getInstance(); // the value to be formatted
    java.text.DateFormat formatter = java.text.DateFormat.getDateInstance(
            java.text.DateFormat.LONG); // one of SHORT, MEDIUM, LONG, FULL, or DEFAULT
    formatter.setTimeZone(cal.getTimeZone());
    String formatted = formatter.format(cal.getTime());
    

    Note that you need to use java.text.DateFormat here, not Android's own (confusingly-named) android.text.format.DateFormat.

提交回复
热议问题