Search code examples
androidcalendardate-format

Get day name from full calender date format


How to get name day name like (Wednesday - Thursday) from this date format "Wed Jan 30 00:00:00 GMT+02:00 2019"


Solution

  • java.time

    It seems that what you’ve got is an instance of the java.util.Date class. That’s a poorly designed class that is long outdated, so first thing is to see if you can avoid that and have an instance of a class from java.time, the modern Java date and time API, instead.

    However, if you got the Date from a legacy API that you cannot change or don’t want to change just now, first thing is to convert it to a modern Instant and then perform further conversions from there. The following snippet uses ThreeTenABP, more on that below.

        Date yourOldfashionedDate = getFromLegacyApi();
    
        Instant modernInstant = DateTimeUtils.toInstant(yourOldfashionedDate);
        String dayName = modernInstant.atZone(ZoneId.systemDefault())
                .getDayOfWeek()
                .getDisplayName(TextStyle.FULL, Locale.ENGLISH);
    
        System.out.println("Day name is " + dayName);
    

    Output given the date from your question:

    Day name is Wednesday

    If what you got was a String (probably a string returned from Date.toString at some point), you need to parse it first:

        DateTimeFormatter dateFormatter
                = DateTimeFormatter.ofPattern("EEE MMM dd HH:mm:ss zzz yyyy", Locale.ROOT);
    
        String dateString = "Wed Jan 30 00:00:00 GMT+02:00 2019";
        ZonedDateTime dateTime = ZonedDateTime.parse(dateString, dateFormatter);
        String dayName = dateTime.getDayOfWeek()
                .getDisplayName(TextStyle.FULL, Locale.ENGLISH);
    

    You see that the last bit is exactly like before.

    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. Only in this case use yourOldfashionedDate.toInstant() instead of DateTimeUtils.toInstant(yourOldfashionedDate).
    • 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