javaandroidcalendardayofweekdayofmonth

How to display day names and number from current date in android


Hi I am implementing a feature called calendar. Now From current month name and current year from this how to display day names and day number .

Code:

cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
            Date startDate = cal.getTime();
            cal.add(Calendar.DATE, 6);
            Date endDate = cal.getTime();

            Log.d(TAG, "Start Date = " + startDate);
            Log.d(TAG, "End Date = " + endDate);

Example: Dec 2020

Expected output :

Wed -9
Thu -10
Fri -11
Sat- 12
Sun- 13

Can any one help me How to achieve my goal


Solution

  • You can do it with a for loop declared with

    1. Initial value as today
    2. Terminating value as the end of the month
    3. Increment value of one day

    and inside the body of the loop, print the 3-letter weekday name (i.e. EEE) and the day-of-month (i.e. d) of the date formatted with DateTimeFormatter.ofPattern("EEE - d", Locale.ENGLISH).

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.time.temporal.TemporalAdjusters;
    import java.util.Locale;
    
    class Main {
        public static void main(String[] args) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEE - d", Locale.ENGLISH);
            LocalDate today = LocalDate.now();
            for (LocalDate date = today; !date.isAfter(today.with(TemporalAdjusters.lastDayOfMonth())); date = date
                    .plusDays(1)) {
                System.out.println(date.format(formatter));
            }
        }
    }
    

    Output:

    Fri - 11
    Sat - 12
    Sun - 13
    ...
    ...
    ...
    Wed - 30
    Thu - 31
    

    Note: all the dates of this month, starting from today, are of two digits and therefore it doesn't matter whether you use d or dd for day-of-month. However, if your requirement is to print the day-of-month always in two digits (e.g. 01 instead of 1), use dd in the DateTimeFormatter pattern.


    Some useful notes:

    The date-time API of java.util and their formatting API, SimpleDateFormat are outdated and error-prone. It is recommended to stop using them completely and switch to the modern date-time API. Learn more about the modern date-time API at Trail: Date Time.

    For any reason, if you have to stick to Java 6 or Java 7, you can use ThreeTen-Backport which backports most of the java.time functionality to Java 6 & 7.

    If you are working for an Android project and your Android API level is still not compliant with Java-8, check Java 8+ APIs available through desugaring and How to use ThreeTenABP in Android Project.