Java LocalDate 如何使用

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

Java LocalDate How to utilize

问题

输入列表:

  1. 起始日期 例如) 2020-10-01
  2. 终止日期 例如) 2020-10-30
  3. 列表 [星期几] 例如) [周日, 周一....]
  4. 列表 [周数] 例如) [1, 4, 5]

我想知道如何在两个日期之间获取特定的星期几。
谢谢。

英文:

input list

  1. from date ex) 2020-10-01
  2. to date ex) 2020-10-30
  3. List [day of week] ex) [sun,mon....]
  4. List [week] ex) [1,4,5]

I would like to know how to get a specific day of the week between the two dates.
Thank.

答案1

得分: 1

> from date ex) 2020-10-01 to date ex) 2020-10-30

您提供的输入字符串已经是 ISO8601 日期格式因此可以在不显式提供 `DateTimeFormatter` 的情况下进行解析如果要以自定义格式例如 `yyyy-MM-dd`)获取输出字符串则需要使用 `DateTimeFormatter` 格式化日期对象

```java
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        String inputStrDate = "2020-10-01";
        LocalDate date = LocalDate.parse(inputStrDate);

        String outputStrDate = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(outputStrDate);
    }
}

输出:

2020-10-01

但是,如果您的输入是其他格式,则需要使用 DateTimeFormatter 将其解析为日期对象。

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class Main {
    public static void main(String[] args) {
        // 输入字符串的格式化程序
        DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern("dd-MM-yyyy");

        String inputStrDate = "10-01-2020";
        LocalDate date = LocalDate.parse(inputStrDate, inputFormat);

        // 输出字符串的格式化程序
        DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        String outputStrDate = date.format(outputFormat);
        System.out.println(outputStrDate);
    }
}

输出:

2020-10-01

了解更多有关日期时间 API 的信息,可参阅 Trail: Date Time


<details>
<summary>英文:</summary>

&gt; from date ex) 2020-10-01 to date ex) 2020-10-30

Your input string is already in the ISO8601 format for date and therefore it can be parsed without providing a `DateTimeFormatter` explicitly. In order to get the output string in a custom format (e.g. `yyyy-MM-dd`), you need to format the date object using `DateTimeFormatter`.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
    	public static void main(String[] args) {
    		String inputStrDate = &quot;2020-10-01&quot;;
    		LocalDate date = LocalDate.parse(inputStrDate);
    
    		String outputStrDate = date.format(DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&quot;));
    		System.out.println(outputStrDate);
    	}
    }
**Output:**

    2020-10-01

However, if your input is some other format, you will need to use `DateTimeFormatter` in order to parse it to a date object.

    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    
    public class Main {
    	public static void main(String[] args) {
    		// Formatter for input string
    		DateTimeFormatter inputFormat = DateTimeFormatter.ofPattern(&quot;dd-MM-yyyy&quot;);
    
    		String inputStrDate = &quot;10-01-2020&quot;;
    		LocalDate date = LocalDate.parse(inputStrDate, inputFormat);
    
    		// Formatter for output string
    		DateTimeFormatter outputFormat = DateTimeFormatter.ofPattern(&quot;yyyy-MM-dd&quot;);
    
    		String outputStrDate = date.format(outputFormat);
    		System.out.println(outputStrDate);
    	}
    }

**Output:**

    2020-10-01

Learn more about date-time API from **[Trail: Date Time](https://docs.oracle.com/javase/tutorial/datetime/index.html)**.



</details>



# 答案2
**得分**: 1

```java
for (LocalDate d = fromDate; !d.isAfter(toDate); d = d.plusDays(1)) { // Loop from start to end date
    for (Integer wf : weekOfMonth) {
        for (Integer df : dayOfWeek) {
            offDay = d.with(fieldWeek, wf)
                       .with(fieldDay, df);

            if (d.getMonth() == offDay.getMonth() && !offDays.contains(offDay)) {
                offDays.add(offDay);
            }
        }
    }
}

抱歉我之前问了错误的问题。
非常感谢。

我已经完成了,但我还是研究了你的代码。

英文:
for(LocalDate d = fromDate; !d.isAfter(toDate); d = d.plusDays(1)) { // 일정 시작 ~ 끝 loop
        for (Integer wf : weekOfMonth) {
            for (Integer df : dayOfWeek) {
                offDay = d.with(fieldWeek, wf)
                        .with(fieldDay, df);

                
                if (d.getMonth() == offDay.getMonth() &amp;&amp; !offDays.contains(offDay)) {
                    offDays.add(offDay);
                }
            }
        }
    }

Sorry for asking the wrong question.
And thank you very much.

I've already made it, but I've studied your code.

答案3

得分: 0

java.time

我也建议您使用java.time这是现代的Java日期和时间API用于处理日期我的建议是

	LocalDate fromDate = LocalDate.of(2020, Month.OCTOBER, 1);
	LocalDate toDate = LocalDate.of(2020, Month.OCTOBER, 30);
	List<DayOfWeek> daysOfWeek = List.of(DayOfWeek.SUNDAY, DayOfWeek.MONDAY);
	List<Integer> weeks = List.of(1, 4, 5);
	
	if (! YearMonth.from(fromDate).equals(YearMonth.from(toDate))) {
		throw new IllegalStateException("Covering more than one month is not yet supported");
	}
	
	WeekFields wf = WeekFields.SUNDAY_START;
	for (int week : weeks) {
		for (DayOfWeek dow : daysOfWeek) {
			LocalDate date = fromDate.with(wf.weekOfMonth(), week)
					.with(wf.dayOfWeek(), dow.get(wf.dayOfWeek()));
			// Is date inside interval?
			if (! (date.isBefore(fromDate)  || date.isAfter(toDate))) {
				System.out.println(date);
			}
		}
	}

输出

>     2020-10-18
>     2020-10-19
>     2020-10-25
>     2020-10-26

打印的日期是美国方式定义的十月第4和第5周的星期日和星期一其中星期从星期日开始因为您在示例列表中首先提到了星期日),第1周是10月1日的一周第1周的星期日和星期一没有打印出来因为它们在10月1日之前也就是在九月份

请考虑您需要哪种周计数方案您可以使用`WeekFields.ISO``WeekFields.of(Locale.getDefault())`等方式

我首先查找周然后查找星期几因为对我来说这是自然的方式我需要使用`WeekFields`对象进行两次调整以确保选择的周计数方案得到遵守

如果您需要跨越一个以上的日历月份请遍历各个月份并为每个月份执行相同的操作还要检查结果日期是否在该月份内以忽略在月份边界附近的重复日期
英文:

java.time

I too recommend that you use java.time, the modern Java date and time API, for your date work. My shot is:

	LocalDate fromDate = LocalDate.of(2020, Month.OCTOBER, 1);
LocalDate toDate = LocalDate.of(2020, Month.OCTOBER, 30);
List&lt;DayOfWeek&gt; daysOfWeek = List.of(DayOfWeek.SUNDAY, DayOfWeek.MONDAY);
List&lt;Integer&gt; weeks = List.of(1, 4, 5);
if (! YearMonth.from(fromDate).equals(YearMonth.from(toDate))) {
throw new IllegalStateException(&quot;Covering more than one month is not yet supported&quot;);
}
WeekFields wf = WeekFields.SUNDAY_START;
for (int week : weeks) {
for (DayOfWeek dow : daysOfWeek) {
LocalDate date = fromDate.with(wf.weekOfMonth(), week)
.with(wf.dayOfWeek(), dow.get(wf.dayOfWeek()));
// Is date inside interval?
if (! (date.isBefore(fromDate)  || date.isAfter(toDate))) {
System.out.println(date);
}
}
}

Output:

> 2020-10-18
> 2020-10-19
> 2020-10-25
> 2020-10-26

The dates printed are Sunday and Monday of weeks 4 and 5 of October defining weeks in the American way where the week begins on Sunday (since you mentioned Sunday first in your example list) and week 1 is the week of October 1. Sunday and Monday of week 1 are not printed because they fall before October 1, that is, in September.

Consider which week scheme you require. You may use for example WeekFields.ISO or WeekFields.of(Locale.getDefault()).

I am finding the week first, then the day of week, because to me this is the natural way. I need to use the WeekFields object for both adjustments to make sure that the chosen week scheme is respected.

If you need to cover more than one calendar month, iterate over the months and do the same for each. Also check that the result date falls within the month so duplicates near month borders are ignored.

huangapple
  • 本文由 发表于 2020年9月18日 12:45:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/63949460.html
匿名

发表评论

匿名网友

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

确定