2012-02-21 341 views
17

我必須使用Java Date類來解決這個問題(它與我的控制之外的東西接口)。如何獲取一年的開始和結束日期?

如何獲取一年的開始日期和結束日期,然後遍歷每個日期?

+2

日期被刪除。改用日曆。 – 2012-02-21 18:23:05

+6

那麼,'Calendar'不是一個選項? @Stas:這不是真的。一堆棄用的方法不會使整個類不被使用。 – BalusC 2012-02-21 18:23:18

+0

@BalusC:「在JDK 1.1之前,Date類有兩個額外的功能,它允許將日期解釋爲年,月,日,小時,分和秒值,還允許格式化和解析日期字符串。不幸的是,這些函數的API不適用於國際化,從JDK 1.1開始,Calendar類應該用於在日期和時間字段之間進行轉換,DateFormat類應該用於格式化和解析日期字符串。已棄用。「 – 2012-02-21 18:26:53

回答

32
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 ... 
} 
+0

啊,我沒有意識到你可以在日曆和日期之間進行轉換! – 2012-02-23 14:35:34

+2

你不要在它們之間轉換;日期代表即時時間,而日曆會告訴您該時刻在特定系統中的表現。 – PaulJWilliams 2013-02-15 10:26:46

+6

此代碼可以通過諸如'cal.set(Calendar.MONTH,Calendar.DECEMBER)的常量來改進;' – tos 2013-11-27 09:49:52

4
// suppose that I have the following variable as input 
    int year=2011; 
    Calendar calendarStart=Calendar.getInstance(); 
    calendarStart.set(Calendar.YEAR,year); 
    calendarStart.set(Calendar.MONTH,0); 
    calendarStart.set(Calendar.DAY_OF_MONTH,1); 
    // returning the first date 
    Date startDate=calendarStart.getTime(); 

    Calendar calendarEnd=Calendar.getInstance(); 
    calendarEnd.set(Calendar.YEAR,year); 
    calendarEnd.set(Calendar.MONTH,11); 
    calendarEnd.set(Calendar.DAY_OF_MONTH,31); 

    // returning the last date 
    Date endDate=calendarEnd.getTime(); 

要重複,你應該使用日曆對象並增加DAY_OF_MONTH變量

希望它可以幫助

+0

你可以用今年的日子來代替。 – 2012-02-21 18:37:14

+0

@ srini.venigalla:true – VirtualTroll 2012-02-21 18:39:45

+0

啊,我沒意識到你可以在日曆和日期之間進行轉換! – 2012-02-23 14:35:48

1

我假設你有Date類的實例,你需要找到根據Date類實例計算當前的第一個日期和最後一個日期。你可以使用Calendar類來做到這一點。使用提供的日期類實例構造日曆實例。將MONTH和DAY_OF_MONTH字段分別設置爲0和1,然後使用getTime()方法,該方法將返回表示Date類的第一天的Date類實例。您可以使用相同的技術來查找年末。

Date date = new Date(); 
    System.out.println("date: "+date); 
    Calendar cal = Calendar.getInstance(); 
    cal.setTime(date); 

    System.out.println("cal:"+cal.getTime()); 

    cal.set(Calendar.MONTH, 0); 
    cal.set(Calendar.DAY_OF_MONTH, 1); 

    System.out.println("cal new: "+cal.getTime()); 
0

嚴重,只是谷歌搜索「今年java的第一天,」讓我this link,使用日曆構造一個很好的例子。

不知道你爲什麼要使用日期,除非你受到限制,這是某種家庭作業。

+0

API限制我無法解決,感謝這個想法! – 2012-02-23 14:35:13

+0

鏈接已死: – 2014-07-17 11:53:08

+0

鏈接已更新,感謝您的支持! – Carlos 2014-07-17 22:16:27

5
Calendar cal = new GregorianCalendar(); 
    cal.set(Calendar.DAY_OF_YEAR, 1); 
    System.out.println(cal.getTime().toString()); 
    cal.set(Calendar.DAY_OF_YEAR, 366); // for leap years 
    System.out.println(cal.getTime().toString()); 
+0

這應該是公認的答案 – mithrandir 2014-12-07 16:46:41

+1

這是非閏年的工作嗎?還是應該手動糾正? – Davor 2015-10-28 14:53:10

+0

請記住,有些年份會有365天和其他人將有366. 這種方法不應該使用。 – 2017-06-19 14:28:38

0

您可以使用具有DateUtils類的apache commons-lang項目。

它們提供了一個迭代器,你可以給Date對象。

但我強烈建議使用Calendar類作爲其他答案的建議。

-1
Calendar cal = Calendar.getInstance();//getting the instance of the Calendar using the factory method 
we have a get() method to get the specified field of the calendar i.e year 

int year=cal.get(Calendar.YEAR);//for example we get 2013 here 

cal.set(year, 0, 1); setting the date using the set method that all parameters like year ,month and day 
Here we have given the month as 0 i.e Jan as the month start 0 - 11 and day as 1 as the days starts from 1 to30. 

Date firstdate=cal.getTime();//here we will get the first day of the year 

cal.set(year,11,31);//same way as the above we set the end date of the year 

Date lastdate=cal.getTime();//here we will get the first day of the year 

System.out.print("the firstdate and lastdatehere\n"); 
+1

可能你解釋你的代碼,請嗎?目前沒有什麼幫助。 – kleinfreund 2013-02-07 12:06:28

-1
GregorianCalendar gcal = new GregorianCalendar(); 
gcal.setTime(start); 
while (gcal.getTime().before(end)) { 
    gcal.add(Calendar.DAY_OF_YEAR, 1); 
    //Do Something ... 
} 

GregorianCalendar的創作在這裏是沒有意義的。實際上,通過Calendar.java源代碼顯示Calendar.getInstance()已經提供了一個GregorianCalendar實例。

問候, 薩科

0

更新:的喬達時庫現在處於維護模式,其團隊建議遷移到java.time類。看到正確的java.time Answer by Przemek

時區

其他答案忽略了時區的關鍵問題。

喬達時間

避免做日期時間工作,出了名的麻煩java.util.Date類。而是使用Joda-Time或java.time。根據需要轉換爲j.u.Date對象以實現互操作性。

DateTimeZone zone = DateTimeZone.forID("America/Montreal") ; 
int year = 2015 ; 
DateTime firstOfYear = new DateTime(year , DateTimeConstants.JANUARY , 1 , 0 , 0 , zone) ; 
DateTime firstOfNextYear = firstOfYear.plusYears(1) ; 
DateTime firstMomentOfLastDayOfYear = firstOfNextYear.minusDays(1) ; 

轉換爲java.util.Date

根據需要轉換爲j.u.Date。

java.util.Date d = firstOfYear.toDate() ; 
24

java.time

使用java.time庫內置到Java 8和更高版本。具體爲LocalDateTemporalAdjusters類。

import java.time.LocalDate 
import static java.time.temporal.TemporalAdjusters.firstDayOfYear 
import static java.time.temporal.TemporalAdjusters.lastDayOfYear 

LocalDate now = LocalDate.now(); // 2015-11-23 
LocalDate firstDay = now.with(firstDayOfYear()); // 2015-01-01 
LocalDate lastDay = now.with(lastDayOfYear()); // 2015-12-31 

如果您需要添加的時間信息,您可以如果你正在尋找一個1行的表達式中使用任何可用的LocalDateLocalDateTime轉換像

lastDay.atStartOfDay(); // 2015-12-31T00:00 
+0

好的答案。我建議總是將想要的/預期的時區傳遞給' LOCALDATE的。現在(ZoneId)'而不是隱式地依賴於JVM的當前默認時區,該時區在運行時可以隨時改變。 'LocalDate.now(ZoneId.of(「America/Montreal」))'同樣,總是將'ZoneId'傳遞給'atStartOfDay'方法,而不是隱式地依賴於JVM默認值。 'lastDay.atStartOfDay(ZoneID.of(「America/Montreal」))' – 2017-05-07 01:22:33

1

,我通常使用這樣的:

new SimpleDateFormat("yyyy-MM-dd").parse(String.valueOf(new java.util.Date().getYear())+"-01-01") 
0

對Srini的答案進行了改進。
使用Calendar.getActualMaximum確定一年中的最後一個日期。

Calendar cal = Calendar.getInstance(); 

calDate.set(Calendar.DAY_OF_YEAR, 1); 
Date yearStartDate = calDate.getTime(); 

calDate.set(Calendar.DAY_OF_YEAR, calDate.getActualMaximum(Calendar.DAY_OF_YEAR)); 
Date yearEndDate = calDate.getTime(); 
相關問題