检索上周一和周五的日期的最佳方法是什么

检索上周一和周五的日期的最佳方法是什么

本文介绍了检索上周一和周五的日期的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到上周星期一和星期五的日期。为了做到这一点,我得到的日期本周一星期,减去7天。这给我上星期的日期。

I need to get the dates for Monday and Friday last week. To do this, i am getting the date of Monday this week and subtracting 7 days. This gives me the date for Monday last week.

要得到星期五的日期,我必须添加4.这让我困惑,因为某种原因,第一天这个星期是星期天,而不是在英国的星期一。

To get the date for Friday i have to add 4. This confused me a bit because for some reason the first day of the week is Sunday as opposed to Monday here in the UK.

无论如何,这里是我如何得到日期。

Anyway, here is how i am getting the dates.

            // Get the dates for last MON & FRI
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);

        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        cal.add(Calendar.DAY_OF_WEEK, -7);

        cal.set(Calendar.HOUR_OF_DAY,0);
        cal.set(Calendar.MINUTE,0);
        cal.set(Calendar.SECOND,0);
        cal.set(Calendar.MILLISECOND,0);

        // Get the date on Friday
        cal.add(Calendar.DAY_OF_WEEK, 4);

        cal.set(Calendar.HOUR_OF_DAY,23);
        cal.set(Calendar.MINUTE,59);
        cal.set(Calendar.SECOND,59);
        cal.set(Calendar.MILLISECOND,0);

上面的工作,但我有兴趣,如果有什么错误的逻辑。也就是说它将在2月,闰年等工作。

The above works but i am interested if there is anything wrong with the logic. I.e. will it work for Februarys, leap years etc.

随时提出更好的解决方案/方法。

Feel free to suggest a better solution/approach.

感谢

推荐答案

为这样的问题提供了非常好的方法。

Joda-Time offers really nice methods for problems like that.

上星期和星期五的日期看起来像这样使用Joda时间:

Getting the dates for Monday and Friday last week would look something like this using Joda Time:

DateTime today = DateTime.now();
DateTime sameDayLastWeek = today.minusWeeks(1);
DateTime mondayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.MONDAY);
DateTime fridayLastWeek = sameDayLastWeek.withDayOfWeek(DateTimeConstants.FRIDAY);

您可以创建 DateTime c $ c> java.util.Date 对象,反之亦然,因此很容易与Java日期一起使用。

You can create DateTime objects from java.util.Date objects and vice versa so it is easy to use with Java dates.

使用上面的日期代码

DateTime today = new DateTime("2012-09-30");

结果为2012-09-17为星期一,2012-09-21为星期五,将日期设置为

results in "2012-09-17" for Monday and "2012-09-21" for Friday, setting the date to

DateTime tomorrow = new DateTime("2012-10-01");

结果为2012-09-24为星期一,2012-09-28为星期五。

results in "2012-09-24" for Monday and "2012-09-28" for Friday.

这篇关于检索上周一和周五的日期的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 16:37