取回本周的星期一的日期 [英] Retrieve current week's Monday's date

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

问题描述

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

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时间(代表所有的日期/时间工作,而不仅仅是这样):

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 Time的一周中,这将永远返回一个较早的一天(或同一天)。如果你选择星期三(例如),那么它将从星期一或星期二提前到星期三。如果您需要下周三或上周三,您可以随时添加或减少一周。

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天全站免登陆