How to get start and end date of a year?

前端 未结 15 1800
清酒与你
清酒与你 2021-02-05 02:57

I have to use the Java Date class for this problem (it interfaces with something out of my control).

How do I get the start and end date of a year and then

15条回答
  •  南笙
    南笙 (楼主)
    2021-02-05 03:24

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2014);
    cal.set(Calendar.DAY_OF_YEAR, 1);    
    Date start = cal.getTime();
    
    //set date to last day of 2014
    cal.set(Calendar.YEAR, 2014);
    cal.set(Calendar.MONTH, 11); // 11 = december
    cal.set(Calendar.DAY_OF_MONTH, 31); // new years eve
    
    Date end = cal.getTime();
    
    //Iterate through the two dates 
    GregorianCalendar gcal = new GregorianCalendar();
    gcal.setTime(start);
    while (gcal.getTime().before(end)) {
        gcal.add(Calendar.DAY_OF_YEAR, 1);
        //Do Something ...
    }
    

提交回复
热议问题