gpt4 book ai didi

java - 日历 - 每周日期 - Java

转载 作者:行者123 更新时间:2023-11-30 03:23:21 25 4
gpt4 key购买 nike

public static void main(String[] args) {
int week = 1;
int year = 2010;


Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.WEEK_OF_YEAR, week);
calendar.set(Calendar.YEAR, year);


Date date = calendar.getTime();
System.out.println(date);
}

如果我输入周、年,我会根据我们的桌面日历查找确切的开始和结束日期。但上面的代码给出的输出为 2009 年 1 月 27 日,星期日。我知道这是因为按照美国一周的默认第一天是星期日,但我需要根据桌面日历 2010 年 1 月 1 日,星期五 作为一周的开始日期

我的要求:如果我的输入是:

  • 周为“1”,
  • 月份为“5”,
  • 年份为“2015”

我需要:

   1st May, 2015 --> as first day of the week
2nd May, 2015 --> as last day of the week

如果我的输入是:

  • 周为“1”,
  • 月份为“6”,
  • 年份为“2015”

我需要:

   1st June, 2015 --> as first day of the week
6th June, 2015 --> as last day of the week

有人可以帮助我吗?

最佳答案

不要使用 CALENDAR.Week,而是使用 Calendar.DAY_OF_YEAR。我刚刚测试了它,它对我有用:

public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
calendar.clear();
calendar.set(Calendar.YEAR, 2010);
calendar.set(Calendar.DAY_OF_YEAR, 1);
System.out.println(calendar.getTime());
calendar.set(Calendar.DAY_OF_YEAR, 7);
System.out.println(calendar.getTime());
}

如果您希望它在任意一周内工作,只需做一些数学计算即可确定您想要一年中的哪一天。

编辑:如果您还想输入月份,可以使用Calendar.DAY_OF_MONTH。

关于java - 日历 - 每周日期 - Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30805716/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com