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
You can do it with a
for
loop declared withand 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 withDateTimeFormatter.ofPattern("EEE - d", Locale.ENGLISH)
.Output:
Note: all the dates of this month, starting from today, are of two digits and therefore it doesn't matter whether you use
d
ordd
for day-of-month. However, if your requirement is to print the day-of-month always in two digits (e.g.01
instead of1
), usedd
in theDateTimeFormatter
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.