2012-02-27 68 views
150

我有一個Java日期對象存儲爲Java的日期類型。我想從Java Date中獲得Year,Month,Day等,以便與Java中的Gregorian Calendar日期進行比較。這可能嗎?

我也有公曆日曆創建日期。公曆日期沒有參數,因此是當今日期(和時間?)的實例。

使用java日期,我希望能夠從java日期類型中獲取年,月,日,小時,分鐘和秒,並比較gregoriancalendar日期。

我看到,此刻Java日期被存儲爲一個很長的時間,唯一可用的方法似乎只是將長整型作爲格式化日期字符串來編寫。有沒有辦法訪問年,月,日等?

我看到getYear(),getMonth()等方法對於Date類已被棄用。我想知道使用Java Date實例的最佳做法是什麼,我的日期爲GregorianCalendar

我的最終目標是做一個日期計算,以便我可以檢查Java日期是否在今天的日期和時間的許多小時,分鐘等內。

我仍然是Java的新手,並對此感到有點困惑。

+0

嘿不管你使用不使用'日期。getYear()'。它有問題(我不知道).'Date.getYear()'一次解析我的日期30/06/2017,它返回我的一年117。看看它降落在哪裏,兩千年背部。但是,當我只打印日期對象,輸出很好。但不是'Date.getYear();'。 – Seenivasan 2017-06-30 10:26:23

+0

僅供參考:您正在使用現在已有的麻煩舊日期時間類,由現代java.time類取代。 – 2017-10-25 15:12:16

回答

393

使用類似:

Date date; // your date 
Calendar cal = Calendar.getInstance(); 
cal.setTime(date); 
int year = cal.get(Calendar.YEAR); 
int month = cal.get(Calendar.MONTH); 
int day = cal.get(Calendar.DAY_OF_MONTH); 
// etc. 

當心,月從0開始,而不是1

編輯:由於Java 8,最好使用java.time.LocalDate而非java.util.Calendar。請參閱this answer瞭解如何操作。

+0

非常感謝!這正是我想要實現的。我正在處理從0到11個月的月份。如果我想檢查Java日期是否在今天的48小時內,最好是從我的公曆日期實例中減去48小時? – daveb 2012-02-27 23:51:05

+4

您可以使用'cal.add(Calendar.DAY_OF_MONTH,-48)'在日曆對象上執行日算法。您可以使用'cal.compareTo(anotherCal)'比較兩個日曆對象。 – 2012-02-27 23:55:56

+1

輝煌,歡呼Florent!以上是否意味着Calender會在使用日曆get方法時返回更新的年,日,秒,分和秒? Dave – daveb 2012-02-28 00:02:10

9

或者你可以做這樣的事情。它將解釋「Date」類如何工作。

String currentDateString = "02/27/2012 17:00:00"; 
    SimpleDateFormat sd = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss"); 
    Date currentDate = sd.parse(currentDateString); 

    String yourDateString = "02/28/2012 15:00:00"; 
    SimpleDateFormat yourDateFormat = new SimpleDateFormat(
      "MM/dd/yyyy HH:mm:ss"); 

    Date yourDate = yourDateFormat.parse(yourDateString); 

    if (yourDate.after(currentDate)) { 
     System.out.println("After"); 
    } else if(yourDate.equals(currentDate){ 
     System.out.println("Same"); 
    }else{ 
        System.out.println("Before"); 
      } 
+0

嗨JavaCity,謝謝你。這非常有用。此刻,我試圖迴避從日期字符串解析。但是,當我將應用程序的用戶設置爲年,日和月時,我將需要稍後進行解析。我打算建立一個字符串來解析SimpleDateFormat。以上內容對於實際操作非常有用。我的Java日期是從一天前的實例化中創建的日期和時間。我現在正在尋找與今天實例化的gregoriancalendar日期進行比較。真誠的感謝 – daveb 2012-02-27 23:57:50

+7

請修正代碼......小寫'mm'表示分鐘,大寫'MM'表示月份。 – YoYo 2016-05-17 02:40:37

4
Date date = new Date(); 

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEEE"); 

    System.out.println("DAY "+simpleDateFormat.format(date).toUpperCase()); 

    simpleDateFormat = new SimpleDateFormat("MMMM"); 
    System.out.println("MONTH "+simpleDateFormat.format(date).toUpperCase()); 

    simpleDateFormat = new SimpleDateFormat("YYYY"); 
    System.out.println("YEAR "+simpleDateFormat.format(date).toUpperCase()); 
3
private boolean isSameDay(Date date1, Date date2) { 
    Calendar calendar1 = Calendar.getInstance(); 
    calendar1.setTime(date1); 
    Calendar calendar2 = Calendar.getInstance(); 
    calendar2.setTime(date2); 
    boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR); 
    boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH); 
    boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH); 
    return (sameDay && sameMonth && sameYear); 
} 
30

利用Java 8和更高版本,可以將Date對象轉換爲LocalDate對象,然後輕鬆搞定年,月,日。

Date date = new Date(); 
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate(); 
int year = localDate.getYear(); 
int month = localDate.getMonthValue(); 
int day = localDate.getDayOfMonth(); 

注意getMonthValue()從1 int值返回到12

+3

現在是2016年,我相信在Java 8中使用'LocalDate'是節省時間的最佳解決方案,使用'Calendar'和'Date'的另一個解決方案充滿了麻煩。 – 2016-07-06 11:28:08

+0

偉大的答案 - 絕對最好使用* java.time *並避免麻煩的舊日期時間類。此外,請注意本答案如何明智地解決時區問題。對於任何特定時刻,日期因時區而異。 – 2016-07-13 01:27:36

1
@Test 
public void testDate() throws ParseException { 
    long start = System.currentTimeMillis(); 
    long round = 100000l; 
    for (int i = 0; i < round; i++) { 
     StringUtil.getYearMonthDay(new Date()); 
    } 
    long mid = System.currentTimeMillis(); 
    for (int i = 0; i < round; i++) { 
     StringUtil.getYearMonthDay2(new Date()); 
    } 
    long end = System.currentTimeMillis(); 
    System.out.println(mid - start); 
    System.out.println(end - mid); 
} 

public static Date getYearMonthDay(Date date) throws ParseException { 
    SimpleDateFormat f = new SimpleDateFormat("yyyyyMMdd"); 
    String dateStr = f.format(date); 
    return f.parse(dateStr); 
} 

public static Date getYearMonthDay2(Date date) throws ParseException { 
    Calendar c = Calendar.getInstance(); 
    c.setTime(date); 
    c.set(Calendar.SECOND, 0); 
    c.set(Calendar.MINUTE, 0); 
    c.set(Calendar.HOUR_OF_DAY, 0); 
    return c.getTime(); 
} 
public static int compare(Date today, Date future, Date past) { 
    Date today1 = StringUtil.getYearMonthDay2(today); 
    Date future1 = StringUtil.getYearMonthDay2(future); 
    Date past1 = StringUtil.getYearMonthDay2(past); 
    return today.compare // or today.after or today.before 
} 

getYearMonthDay2(日曆溶液)是快十倍。現在你有yyyy MM dd 00 00 00,然後比較使用date.compare

0

仔細安裝從0開始不是1.而且日曆使用像am一樣的pm,所以使用小時和分鐘時要非常小心。

Date your_date; 
 
Calendar cal = Calendar.getInstance(); 
 
cal.setTime(your_date); 
 
int year = cal.get(Calendar.YEAR); 
 
int month = cal.get(Calendar.MINUTE);

+0

更好地使用替代這裏顯示的這些麻煩的舊舊類的現代java.time。請參閱[正確答案](https://stackoverflow.com/a/32363174/642706) – 2017-07-21 18:05:27

+0

謝謝您的回答和建議。這是非常好的。 – 2017-07-22 13:41:02

0

可能更容易

 Date date1 = new Date("31-May-2017"); 
OR 
    java.sql.Date date1 = new java.sql.Date((new Date()).getTime()); 

    SimpleDateFormat formatNowDay = new SimpleDateFormat("dd"); 
    SimpleDateFormat formatNowMonth = new SimpleDateFormat("MM"); 
    SimpleDateFormat formatNowYear = new SimpleDateFormat("YYYY"); 

    String currentDay = formatNowDay.format(date1); 
    String currentMonth = formatNowMonth.format(date1); 
    String currentYear = formatNowYear.format(date1); 
相關問題