检索当前星期的星期一的日期 [英] Retrieve current week's Monday's date

查看:107
本文介绍了检索当前星期的星期一的日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个实用程序,将在星期一至星期五之间的任何一天运行。它将更新内容管理工具中的一些数量的文件。与该文件相关联的最后修改日期应为该周的星期日日期。我写了以下程序来检索当前星期的星期一的日期。但我仍然不确定这是否适用于所有场景。有没有人有更好的解决方案?

We have a utility that will run any day between Monday - Friday. It will update some number of files inside a Content Management Tool. The last modified date associated with that file should be, that week's monday's date. I wrote the following program to retrieve current week's monday's date. But I am still not sure whether this would work for all scenarios. Has anyone got a better solution ?

Calendar c = Calendar.getInstance();
c.setTime(new Date());
System.out.println(c.get(Calendar.DAY_OF_MONTH));
System.out.println(c.get(Calendar.DAY_OF_WEEK));
int mondayNo = c.get(Calendar.DAY_OF_MONTH)-c.get(Calendar.DAY_OF_WEEK)+2;
c.set(Calendar.DAY_OF_MONTH,mondayNo);
System.out.println("Date "+c.getTime());


推荐答案

我强烈建议使用 Joda Time (对于所有的日期/时间工作,而不仅仅是这个):

I would strongly recommend using Joda Time instead (for all your date/time work, not just this):

// TODO: Consider time zones, calendars etc
LocalDate now = new LocalDate();
LocalDate monday = now.withDayOfWeek(DateTimeConstants.MONDAY);
System.out.println(monday);

请注意,由于您在这里使用了星期一在Joda时间的一周中,这将总是返回较早的一天(或同一天)。如果您选择星期三(例如),那么它会从星期一或星期二提前到星期三。如果您需要下周三或上周三,您可以随时添加或减少一周。

Note that as you've used Monday here, which is the first day of the week in Joda Time, this will always return an earlier day (or the same day). If you chosen Wednesday (for example), then it would advance to Wednesday from Monday or Tuesday. You can always add or subtract a week if you need "the next Wednesday" or "the previous Wednesday".

编辑:如果您真的想要使用java.util.Date/Calendar,可以使用:

If you really want to use java.util.Date/Calendar, you can use:

Calendar c = Calendar.getInstance();
c.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Date " + c.getTime());

您可以使用 Calendar.setFirstDayOfWeek ,以指示一周是周一至周日,还是周日 - 周六;我相信设置一周中的某一天将保持在当前周内,但可以测试。

You can use Calendar.setFirstDayOfWeek to indicate whether a week is Monday-Sunday or Sunday-Saturday; I believe setting the day of the week will stay within the current week - but test it.

这篇关于检索当前星期的星期一的日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆