How can I get current date in Android?

前端 未结 26 2068
[愿得一人]
[愿得一人] 2020-11-27 10:24

I wrote the following code

Date d = new Date();
CharSequence s  = DateFormat.format(\"MMMM d, yyyy \", d.getTime());

But is asking me para

26条回答
  •  执笔经年
    2020-11-27 11:05

    I am providing the modern answer.

    java.time and ThreeTenABP

    To get the current date:

        LocalDate today = LocalDate.now(ZoneId.of("America/Hermosillo"));
    

    This gives you a LocalDate object, which is what you should use for keeping a date in your program. A LocalDate is a date without time of day.

    Only when you need to display the date to a user, format it into a string suitable for the user’s locale:

        DateTimeFormatter userFormatter
                = DateTimeFormatter.ofLocalizedDate(FormatStyle.LONG);
        System.out.println(today.format(userFormatter));
    

    When I ran this snippet today in US English locale, output was:

    July 13, 2019

    If you want it shorter, specify FormatStyle.MEDIUM or even FormatStyle.SHORT. DateTimeFormatter.ofLocalizedDate uses the default formatting locale, so the point is that it will give output suitable for that locale, different for different locales.

    If your user has very special requirements for the output format, use a format pattern string:

        DateTimeFormatter userFormatter = DateTimeFormatter.ofPattern(
                "d-MMM-u", Locale.forLanguageTag("ar-AE"));
    

    13-يول-2019

    I am using and recommending java.time, the modern Java date and time API. DateFormat, SimpleDateFormat, Date and Calendar used in the question and/or many of the other answers, are poorly designed and long outdated. And java.time is so much nicer to work with.

    Question: Can I use java.time on Android?

    Yes, java.time works nicely on older and newer Android devices. It just requires at least Java 6.

    • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
    • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
    • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

    Links

    • Oracle tutorial: Date Time explaining how to use java.time.
    • Java Specification Request (JSR) 310, where java.time was first described.
    • ThreeTen Backport project, the backport of java.time to Java 6 and 7 (ThreeTen for JSR-310).
    • ThreeTenABP, Android edition of ThreeTen Backport
    • Question: How to use ThreeTenABP in Android Project, with a very thorough explanation.

提交回复
热议问题