将字符串转换为星期几(不是确切的日期) [英] Convert string to day of week (not exact date)
问题描述
我收到一个 String
,它是一周中的拼写,例如星期一。现在,我想获取当天的常量整数表示形式,该表示形式用于 java.util.Calendar
。
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
.
我真的必须在我的 if(day.equalsIgnoreCase( Monday)){...}上做if(...){...}
拥有?有一些整洁的方法吗?如果我挖出 SimpleDateFormat
并将其与 Calendar
混合,则产生的行数几乎与键入难看的if-
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.
推荐答案
您可以使用 SimpleDateFormat
它也可以解析特定语言环境
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);
}
}
这篇关于将字符串转换为星期几(不是确切的日期)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!