从日期对象获取日期

时间:2009-10-06 12:33:20

标签: java datetime calendar

我想看看someDate是否有任何一天。我检查一下吗?

Calendar cal = Calendar.getInstance();
cal.setTime(someDate); // someDate is a Date
int day = cal.get(Calendar.DAY_OF_MONTH);
if(day == 0){
  // code //
} 

4 个答案:

答案 0 :(得分:4)

我不确定你的意思是“有任何一天” - 所有的日期都会 天......: - )

除此之外,您可能需要以下内容:

Calendar cal = Calendar.getInstance();
cal.setTime(someDate); // someDate is a Date
int day = cal.get(Calendar.DAY_OF_WEEK);
if(day == Calendar.SUNDAY){
  // code //
}

最大的变化是你想获得DAY_OF_WEEK字段;你的例子所做的是获得一个月内的一天(例如9月15日将返回“15”)。其次,与Calendar.SUNDAY(或等效物)相比更清晰,更不易出错,直接与例如0,即使代码是等效的。

答案 1 :(得分:0)

每个日期对象都有一天。该月的某一天永远不会是0,它将在1-31的范围内。这意味着您的检查将始终失败。

答案 2 :(得分:0)

如果我理解正确,您需要Calendar.DAY_OF_WEEK

答案 3 :(得分:0)

answer by Andrzej Doyle是正确的。


只是为了它,这是相同类型的代码,但使用Joda-Time 2.3库和Java 7。

java.util.Calendar不同,Joda-Time明智地使用基于1的计数。因此,一周的日期编号为1到7.此外,Joda-Time使用标准(ISO 8601)方法,其中星期一是一周的第一天(1)。

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
// import org.joda.time.*;
// import org.joda.time.format.*;

// Specify time zone rather than rely on default.
// Time Zone list… http://joda-time.sourceforge.net/timezones.html  (not quite up-to-date, read page for details)
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Paris" );

DateTime now = new DateTime( timeZone );
if( now.dayOfWeek().get() == DateTimeConstants.MONDAY ) {
    System.out.println( "Today is a Monday." );
} else {
    System.out.println( "Nope, today is some other day of week." );
}