使用java日历类获取一周的开始和结束日期 [英] Getting the start and the end date of a week using java calendar class

查看:1013
本文介绍了使用java日历类获取一周的开始和结束日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想获得给定日期的一周的最后一周和第一周。
例如,如果日期是2011年10月12日,那么我需要2011年10月10日(作为一周的开始日期)和2011年10月16日(作为一周的结束日期)的日期
有谁知道如何使用日历类(java.util.Calendar)
得到这两个日期非常感谢!

I want to get the last and the first week of a week for a given date. e.g if the date is 12th October 2011 then I need the dates 10th October 2011 (as the starting date of the week) and 16th october 2011 (as the end date of the week) Does anyone know how to get these 2 dates using the calender class (java.util.Calendar) thanks a lot!

推荐答案

代码如何使用 Calendar 对象进行操作。我还应该提一下 joda时间库,因为它可以帮助你很多日期/日历问题。

Some code how to do it with the Calendar object. I should also mention joda time library as it can help you many of Date/Calendar problems.

public static void main(String[] args) {

    // set the date
    Calendar cal = Calendar.getInstance();
    cal.set(2011, 10 - 1, 12);

    // "calculate" the start date of the week
    Calendar first = (Calendar) cal.clone();
    first.add(Calendar.DAY_OF_WEEK, 
              first.getFirstDayOfWeek() - first.get(Calendar.DAY_OF_WEEK));

    // and add six days to the end date
    Calendar last = (Calendar) first.clone();
    last.add(Calendar.DAY_OF_YEAR, 6);

    // print the result
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    System.out.println(df.format(first.getTime()) + " -> " + 
                       df.format(last.getTime()));
}

这篇关于使用java日历类获取一周的开始和结束日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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