How to format date and time in Android?

前端 未结 24 1604
面向向阳花
面向向阳花 2020-11-22 00:51

How to format correctly according to the device configuration date and time when having a year, month, day, hour and minute?

24条回答
  •  温柔的废话
    2020-11-22 01:29

    Avoid j.u.Date

    The Java.util.Date and .Calendar and SimpleDateFormat in Java (and Android) are notoriously troublesome. Avoid them. They are so bad that Sun/Oracle gave up on them, supplanting them with the new java.time package in Java 8 (not in Android as of 2014). The new java.time was inspired by the Joda-Time library.

    Joda-Time

    Joda-Time does work in Android.

    Search StackOverflow for "Joda" to find many examples and much discussion.

    A tidbit of source code using Joda-Time 2.4.

    Standard format.

    String output = DateTime.now().toString(); 
    // Current date-time in user's default time zone with a String representation formatted to the ISO 8601 standard.
    

    Localized format.

    String output = DateTimeFormat.forStyle( "FF" ).print( DateTime.now() ); 
    // Full (long) format localized for this user's language and culture.
    

提交回复
热议问题