How to format date and time in Android?

前端 未结 24 1654
面向向阳花
面向向阳花 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:22

    The other answers are generally correct. I should like to contribute the modern answer. The classes Date, DateFormat and SimpleDateFormat used in most of the other answers, are long outdated and have caused trouble for many programmers over many years. Today we have so much better in java.time, AKA JSR-310, the modern Java date & time API. Can you use this on Android yet? Most certainly! The modern classes have been backported to Android in the ThreeTenABP project. See this question: How to use ThreeTenABP in Android Project for all the details.

    This snippet should get you started:

        int year = 2017, month = 9, day = 28, hour = 22, minute = 45;
        LocalDateTime dateTime = LocalDateTime.of(year, month, day, hour, minute);
        DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM);
        System.out.println(dateTime.format(formatter));
    

    When I set my computer’s preferred language to US English or UK English, this prints:

    Sep 28, 2017 10:45:00 PM
    

    When instead I set it to Danish, I get:

    28-09-2017 22:45:00
    

    So it does follow the configuration. I am unsure exactly to what detail it follows your device’s date and time settings, though, and this may vary from phone to phone.

提交回复
热议问题