如何在Java中将字符串转换为工作日?

huangapple go评论88阅读模式
英文:

how convert string to a weekday in java?

问题

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String[] inputDays = new String[] { "wed", "mon", "thu" };
        String[] strDays = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
        Map<String, Integer> dayIndexMap = new HashMap<>();
        dayIndexMap.put("sun", 0);
        dayIndexMap.put("mon", 1);
        dayIndexMap.put("tue", 2);
        dayIndexMap.put("wed", 3);
        dayIndexMap.put("thu", 4);
        dayIndexMap.put("fri", 5);
        dayIndexMap.put("sat", 6);

        SimpleDateFormat sdf = new SimpleDateFormat("EE");
        Calendar calendar = Calendar.getInstance();

        for (String inputDay : inputDays) {
            int currentDayIndex = dayIndexMap.get(inputDay);
            int desiredDayIndex = (currentDayIndex + 6) % 7; // Subtract 1 day

            calendar.setTime(new Date());
            int todayIndex = calendar.get(Calendar.DAY_OF_WEEK) - 1;
            int daysToAdd = (todayIndex - desiredDayIndex + 7) % 7;

            calendar.add(Calendar.DAY_OF_YEAR, -daysToAdd);
            Date desiredDate = calendar.getTime();

            String outputDay = sdf.format(desiredDate).toLowerCase();
            System.out.println("Input : " + inputDay + " | Output : " + outputDay);
        }
    }
}

Please make sure to include the necessary imports and libraries before running the code.

英文:

I have a string values like "wed","mon","thu" ... I want to substract 1 day from this values. the expected output will be "tue", "sun","wed". how to achieve this in java 8?

I am able to do it for current week. But not getting it if I pass a string.

Calendar now = Calendar.getInstance();
System.out.println(&quot;Current date : &quot; + (now.get(Calendar.MONTH) + 1) + &quot;-&quot;
+ now.get(Calendar.DATE) + &quot;-&quot; + now.get(Calendar.YEAR));
String[] strDays = new String[] { &quot;Sunday&quot;, &quot;Monday&quot;, &quot;Tuesday&quot;, &quot;Wednesday&quot;, &quot;Thusday&quot;,
&quot;Friday&quot;, &quot;Saturday&quot; };
System.out.println(&quot;Current day is : &quot; + strDays[now.get(Calendar.DAY_OF_WEEK) - 1]);

Input : "wed","mon","thu"
Output Needed : "tue", "sun","wed"

答案1

得分: 2

如何在Java中将字符串转换为星期几?

使用格式化程序:

    static DateTimeFormatter dowFormatter = new DateTimeFormatterBuilder()
            .parseCaseInsensitive()
            .appendPattern("EEE")
            .toFormatter(Locale.ENGLISH);

解析为一周的某一天:

    String dowString = "wed";
    DayOfWeek dow = DayOfWeek.from(dowFormatter.parse(dowString));
    System.out.println(dow);

这将输出:

    > WEDNESDAY

`DayOfWeek` 枚举表示一周的 7 天。一旦在代码中将星期几作为这样的对象获取到,获取前一天就很简单(知道如何操作时):

    DayOfWeek currentDow = dow.minus(1);
    System.out.println("当前天是:" + currentDow);

> 当前天是:TUESDAY

它适用于一周的所有天;当我们到达一周的开始(在这个枚举声明中是星期一)时,减法操作将回到一周的末尾(星期日)。

如果需要,您可以使用顶部的格式化程序将枚举实例重新格式化为字符串进行显示:

    String currentDowString = dowFormatter.format(currentDow);
    System.out.println("当前天是:" + currentDowString);

> 当前天是:Tue

在您自己的代码中,没有理由硬编码每天的名称。Java 已经知道许多语言中的名称和常用缩写。

在这种情况下,也没有理由使用 `Calendar` 类,无论是在这种情况还是其他情况下。它并不真正适合您的用例。它设计得很糟糕,现在已经过时了。相反,对于所有与日期和时间相关的工作,请使用现代的 Java 日期和时间 API,其中包括 `DayOfWeek`,即 java.time。

**链接**

- [Oracle 教程:日期时间](https://docs.oracle.com/javase/tutorial/datetime/) 解释了如何使用 java.time。
- [`DayOfWeek` 的文档](https://docs.oracle.com/javase/10/docs/api/java/time/DayOfWeek.html)
英文:

> how convert string to a weekday in java?

Use a formatter:

static DateTimeFormatter dowFormatter = new DateTimeFormatterBuilder()
.parseCaseInsensitive()
.appendPattern(&quot;EEE&quot;)
.toFormatter(Locale.ENGLISH);

To parse into a day of week;

	String dowString = &quot;wed&quot;;
DayOfWeek dow = DayOfWeek.from(dowFormatter.parse(dowString));
System.out.println(dow);

This outputs:

> WEDNESDAY

The DayOfWeek enum represents the 7 days of the week. Once you’ve got the day of week as such an object in your code, getting the previous day is trivial (when you know how):

	DayOfWeek currentDow = dow.minus(1);
System.out.println(&quot;Current day is : &quot; + currentDow);

> Current day is : TUESDAY

It does work for all days of the week; when we hit the beginning of the week (Monday in this enum declaration), the subtraction goes back to the end of the week (Sunday).

If you want, you may format the enum instance back to a string for display using the formatter from the top:

	String currentDowString = dowFormatter.format(currentDow);
System.out.println(&quot;Current day is : &quot; + currentDowString);

> Current day is : Tue

There is no reason for hardcoding the names of the days in your own code. Java already knows the names and the common abbreviations in many languages.

There is also no reason why you should want to use the Calendar class, neither in this nor in other cases. It doesn’t really fit your use case. And it was always poorly designed and is now long outdated. Instead use java.time, the modern Java date and time API to which DayOfWeek belongs, for all you date and time work.

Links

huangapple
  • 本文由 发表于 2020年3月16日 01:36:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/60695776.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定