I'm receiving a String
which is a spelled out day of the week, e.g. Monday. Now I want to get the constant integer representation of that day, which is used in java.util.Calendar
.
Do I really have to do if(day.equalsIgnoreCase("Monday")){...}else if(...){...}
on my own? Is there some neat method? If I dig up the SimpleDateFormat
and mix that with the Calendar
I produce nearly as many lines as typing the ugly if-else-to-infitity statetment.
Use DateTime. DayOfWeek property to display the current day of week. DayOfWeek wk = DateTime.
Use the DateTime. DayOfWeek or DateTimeOffset. DayOfWeek property to retrieve a DayOfWeek value that indicates the day of the week. If necessary, cast (in C#) or convert (in Visual Basic) the DayOfWeek value to an integer.
Use the strftime() method of a datetime module to get the day's name in English in Python. It uses some standard directives to represent a datetime in a string format. The %A directive returns the full name of the weekday. Like, Monday, Tuesday.
You can use SimpleDateFormat
it can also parse the day for a specific Locale
public class Main {
private static int parseDayOfWeek(String day, Locale locale)
throws ParseException {
SimpleDateFormat dayFormat = new SimpleDateFormat("E", locale);
Date date = dayFormat.parse(day);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
return dayOfWeek;
}
public static void main(String[] args) throws ParseException {
int dayOfWeek = parseDayOfWeek("Sunday", Locale.US);
System.out.println(dayOfWeek);
dayOfWeek = parseDayOfWeek("Tue", Locale.US);
System.out.println(dayOfWeek);
dayOfWeek = parseDayOfWeek("Sonntag", Locale.GERMANY);
System.out.println(dayOfWeek);
}
}
For anyone interested in Java 8 solution, this can be achieved with something similar to this:
import static java.util.Locale.forLanguageTag;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.time.DayOfWeek;
import org.junit.Test;
public class sarasa {
@Test
public void test() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("EEEE", forLanguageTag("es"));
TemporalAccessor accessor = formatter.parse("martes"); // Spanish for Tuesday.
System.out.println(DayOfWeek.from(accessor));
}
}
Output for this is:
TUESDAY
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