Java 将字符串转换为星期几(不是确切日期)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18232340/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:35:23  来源:igfitidea点击:

Convert string to day of week (not exact date)

javadatecalendarsimpledateformatdayofweek

提问by Franz Kafka

I'm receiving a Stringwhich 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.

我收到了String一个拼写出来的一周中的哪一天,例如星期一。现在我想获得那天的常量整数表示,它在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 SimpleDateFormatand mix that with the CalendarI produce nearly as many lines as typing the ugly if-else-to-infitity statetment.

我真的必须自己做if(day.equalsIgnoreCase("Monday")){...}else if(...){...}吗?有什么巧妙的方法吗?如果我挖掘SimpleDateFormat并混合它,Calendar我会产生几乎与输入丑陋的 if-else-to-infitity 语句一样多的行。

回答by Josh M

You could do something like this:

你可以这样做:

    private static String getDayOfWeek(final Calendar calendar){
    assert calendar != null;
    final String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    return days[calendar.get(Calendar.DAY_OF_WEEK)-1];
}

Although it would probably be a good idea to declare the days of the week so you don't have to keep declaring them each time the method is called.

尽管声明星期几可能是个好主意,因此您不必在每次调用该方法时都继续声明它们。

For the other way around, something like this:

反过来说,是这样的:

    private static int getDayOfWeek(final String day){
    assert day != null;
    final String[] days = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
    for(int i = 0; i < days.length; i++)
        if(days[i].equalsIgnoreCase(day))
            return i+1;
    return -1;
}

回答by Tala

Why not initialize what you want once?

为什么不初始化你想要的一次?

private static final Map<String, Integer> weekDays;
static
{
    weekDays= new HashMap<String, Integer>();
    weekDays.put("Monday", Calendar.MONDAY);
    weekDays.put("Tuesday", Calendar.TUESDAY);
    // etc
}

回答by René Link

You can use SimpleDateFormatit can also parse the day for a specific Locale

您可以使用SimpleDateFormat它也可以解析特定的一天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);
    }

}

回答by Martin

Why not declare a Map:

为什么不声明一个 Map:

Map<String, Integer> daysMap = new HashMap<String, Integer>();

daysMap.add("monday", 0);
daysMap.add("tuesday", 1);
//etc.

Then, when you need to search:

然后,当您需要搜索时:

int dayId = daysMap.get(day.toLowerCase());

This should do what you need. You could even load the data from some file / database, etc.

这应该做你需要的。您甚至可以从某个文件/数据库等加载数据。

回答by Ravi Thapliyal

Consider using a helper method like

考虑使用像这样的辅助方法

public static int getDayOfWeekAsInt(String day) {
    if (day == null) {
        return -1;
    }
    switch (day.toLowerCase()) {
        case "monday":
            return Calendar.MONDAY;
        case "tuesday":
            return Calendar.TUESDAY;
        case "wednesday":
            return Calendar.WEDNESDAY;
        case "thursday":
            return Calendar.THURSDAY;
        case "friday":
            return Calendar.FRIDAY;
        case "saturday":
            return Calendar.SATURDAY;
        case "sunday":
            return Calendar.SUNDAY;
        default: 
            return -1;
    }
}

Please, note that using Strings with switch-caseis only supported Java 7 onwards.

请注意,switch-case仅支持 Java 7 及更高版本的字符串。

回答by Amar

I generally use an enum, though in this case your input has to be in proper case.

我通常使用枚举,但在这种情况下,您的输入必须是正确的。

public enum DayOfWeek {
    Sunday(1),Monday(2),Tuesday(3),Wednesday(4),Thursday(5),Friday(6),Saturday(7);

    private final int value;

    DayOfWeek(int value) {

        this.value = value;
    }

    public int getValue() {

        return value;
    }

    @Override
    public String toString() {

        return value + "";
    }
}

Now, you can get the day of the week as follows:

现在,您可以按如下方式获取星期几:

String sunday = "Sunday";
System.out.println(DayOfWeek.valueOf(sunday));

This would give you following output:

这将为您提供以下输出:

1

回答by tete

java.time

时间

For anyone interested in Java 8 solution, this can be achieved with something similar to this:

对于任何对 Java 8 解决方案感兴趣的人,这可以通过类似于以下内容的方式来实现:

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

回答by Basil Bourque

For non-English day-of-week names, see Answer by tete.

对于非英语的星期几名称,请参阅tete 的回答

tl;dr

tl;博士

 DayOfWeek.valueOf( "Monday".toUppercase() )  // `DayOfWeek` object. Works only for English language.
          .getValue()                         // 1

java.time

时间

If your day-of-week names happen to be the full-length name in English (Monday, Tuesday, etc.), that happens to coincide with the names of the enum objects defined in the DayOfWeekenum.

如果您的星期几名称恰好是英文的全长名称(星期一、星期二等),则恰好与枚举中定义的枚举对象的名称一致DayOfWeek

Convert your inputs to all uppercase, and parse to get a constant object for that day-of-week.

将您的输入转换为全部大写,并解析以获得该星期几的常量对象。

String input = "Monday" ;
String inputUppercase = input.toUppercase() ;  // MONDAY
DayOfWeek dow = DayOfWeek.valueOf( inputUppercase );  // Object, neither a string nor a number.

Now that we have a full-feature object rather than a string, ask for the integer number of that day-of-week where Monday is 1 and Sunday is 7 (standard ISO 8601definition).

既然我们有一个全功能对象而不是一个字符串,那么要求星期一是 1 和星期日是 7(标准ISO 8601定义)的那个星期几的整数。

int dayOfWeekNumber = dow.getValue() ;

Use DayOfWeekobjects rather than strings

使用DayOfWeek对象而不是字符串

I urge you to minimize the use of either the name or number of day-of-week. Instead, use DayOfWeekobjectswhenever possible.

我敦促您尽量减少使用名称或星期几。相反,尽可能使用DayOfWeek对象

By the way, you can localize the day-of-week name automatically.

顺便说一下,您可以自动本地化星期几名称。

String output = DayOfWeek.MONDAY.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

That localization is one-way only through the DayOfWeekclass. To go the other direction in languages other than English, see the Answer by tete.

该本地化仅是通过DayOfWeek该类的一种方式。要使用英语以外的其他语言,请参阅tete答案



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多

回答by Deepak Kumar

If you are using java 8 :

如果您使用的是 Java 8:

import java.time.DayOfWeek;

Then simply use: DayOfWeek.[DAY].getValue()

然后简单地使用:DayOfWeek.[DAY].getValue()

System.out.println(DayOfWeek.MONDAY.getValue());
System.out.println(DayOfWeek.TUESDAY);
System.out.println(DayOfWeek.FRIDAY.getValue());

For older version check this answer: Convert string to day of week (not exact date)

对于旧版本,请检查此答案: 将字符串转换为星期几(不是确切日期)

回答by Dawood ibn Kareem

Use the names built into the DateFormatSymbolsclass as follows. This returns 0 for Sunday, 6 for Saturday, and -2 for any invalid day. Add your own error handling as you see fit.

使用DateFormatSymbols类中内置的名称,如下所示。星期日返回 0,星期六返回 6,任何无效日返回 -2。根据需要添加您自己的错误处理。

private static final List dayNames = Arrays.asList(new DateFormatSymbols().getWeekdays());

public int dayNameToInteger(String dayName) {
    return dayNames.indexOf(dayName) - 1;
}