i tried to get a string with the name of the actual weekday this way:
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (c.get(Calendar.MONDAY) == dayOfWeek) weekDay = "monday";
else if (c.get(Calendar.TUESDAY) == dayOfWeek) weekDay = "tuesday";
else if (c.get(Calendar.WEDNESDAY) == dayOfWeek) weekDay = "wednesday";
else if (c.get(Calendar.THURSDAY) == dayOfWeek) weekDay = "thursday";
else if (c.get(Calendar.FRIDAY) == dayOfWeek) weekDay = "friday";
else if (c.get(Calendar.SATURDAY) == dayOfWeek) weekDay = "saturday";
else if (c.get(Calendar.SUNDAY) == dayOfWeek) weekDay = "sunday";
but weekDay
stays always null and i actually have no idea why because the debugger says that dayOfWeek
is 5 so i should be equal to c.get(Calendar.THURSDAY)
get(Calendar. DAY_OF_WEEK); Just the same as in Java, nothing particular to Android. You can check that from Calender.
Example 1: Get Current date and time in default formatnow() method. For default format, it is simply converted from a LocalDateTime object to a string using a toString() method.
To get the day of the week, use Calendar. DAY_OF_WEEK.
As simple as this
sCalendar = Calendar.getInstance();
String dayLongName = sCalendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.getDefault());
I accomplished this by doing the following:
String weekDay;
SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE", Locale.getDefault());
Calendar calendar = Calendar.getInstance();
weekDay = dayFormat.format(calendar.getTime());
You will want to review the SimpleDateFormat to learn more. I think this is the cleanest approach in that you do not need a switch or if statement if your only need is to get the string value.
You are supposed to compare dayOfWeek directly with Calendar.MONDAY etc. See code below
Also, I have put brackets around if else. Do not rely on indentation for code flow, explicitly put brackets even if your if-else has only one statement.
public static void main(String[] args) {
String weekDay = "";
Calendar c = Calendar.getInstance();
int dayOfWeek = c.get(Calendar.DAY_OF_WEEK);
if (Calendar.MONDAY == dayOfWeek) {
weekDay = "monday";
} else if (Calendar.TUESDAY == dayOfWeek) {
weekDay = "tuesday";
} else if (Calendar.WEDNESDAY == dayOfWeek) {
weekDay = "wednesday";
} else if (Calendar.THURSDAY == dayOfWeek) {
weekDay = "thursday";
} else if (Calendar.FRIDAY == dayOfWeek) {
weekDay = "friday";
} else if (Calendar.SATURDAY == dayOfWeek) {
weekDay = "saturday";
} else if (Calendar.SUNDAY == dayOfWeek) {
weekDay = "sunday";
}
System.out.println(weekDay);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With