查看今天的日期

时间:2011-06-30 15:51:07

标签: java android date

我写了一些代码来检查两个日期,开始日期和结束日期。如果结束日期在开始日期之前,则会提示结束日期在开始日期之前。

我还想添加一个检查,看看开始日期是否在今天之前(今天是用户使用应用程序的那天)我该怎么做? (下面的日期检查代码,如果有任何影响的话,所有这些都是为Android编写的)

if (startYear > endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startMonth > endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
} else if (startDay > endDay && startMonth >= endMonth && startYear >= endYear) {
    fill = fill + 1;
    message = message + "End Date is Before Start Date" + "\n";
}

12 个答案:

答案 0 :(得分:107)

不要那么复杂。使用这种简单的方法。导入DateUtils java类并调用以下返回布尔值的方法。

DateUtils.isSameDay(date1,date2);
DateUtils.isSameDay(calender1,calender2);
DateUtils.isToday(date1);

有关详情,请参阅此文DateUtils Java

答案 1 :(得分:41)

这有帮助吗?

Calendar c = Calendar.getInstance();

// set the calendar to start of today
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);

// and get that as a Date
Date today = c.getTime();

// or as a timestamp in milliseconds
long todayInMillis = c.getTimeInMillis();

// user-specified date which you are testing
// let's say the components come from a form or something
int year = 2011;
int month = 5;
int dayOfMonth = 20;

// reuse the calendar to set user specified date
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);

// and get that as a Date
Date dateSpecified = c.getTime();

// test your condition
if (dateSpecified.before(today)) {
  System.err.println("Date specified [" + dateSpecified + "] is before today [" + today + "]");
} else {
  System.err.println("Date specified [" + dateSpecified + "] is NOT before today [" + today + "]");
}

答案 2 :(得分:7)

Android已经有了专门的课程。查看DateUtils.isToday(long when)

答案 3 :(得分:5)

使用Joda Time这可以简化为:

DateMidnight startDate = new DateMidnight(startYear, startMonth, startDay);
if (startDate.isBeforeNow())
{
    // startDate is before now
    // do something...
}

答案 4 :(得分:5)

其他答案忽略了time zone的关键问题。

其他答案使用过时的类。

避免旧的日期时间类

与最早版本的Java捆绑在一起的旧日期时间类设计糟糕,令人困惑且麻烦。避免使用java.util.Date/.Calendar和相关的类。

java.time

LocalDate

对于仅限日期的值,没有时间和没有时区,请使用LocalDate类。

LocalDate start = LocalDate.of( 2016 , 1 , 1 );
LocalDate stop = start.plusWeeks( 1 );

时区

请注意,虽然LocalDate存储时区,但确定日期(例如“今天”)需要时区。对于任何特定时刻,日期可能因时区而异。例如,巴黎的新日早些时候比蒙特利尔早。巴黎午夜过后的一刻仍然在蒙特利尔的“昨天”。

如果您只拥有offset-from-UTC,请使用ZoneOffset。如果您有完整时区(大陆/地区),请使用ZoneId。如果您想要UTC,请使用方便的常量ZoneOffset.UTC

ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );

使用isEqualisBeforeisAfter方法进行比较很简单。

boolean invalidInterval = stop.isBefore( start );

我们可以查看今天是否包含在此日期范围内。在我这里显示的逻辑中,我使用半开放式方法,其中开头是包含,而结尾是独占。这种方法在日期工作中很常见。因此,例如,一周从周一开始,但不包括下周一。

// Is today equal or after start (not before) AND today is before stop.
boolean intervalContainsToday = ( ! today.isBefore( start ) ) && today.isBefore( stop ) ) ;

Interval

如果需要花费大量时间,请考虑将ThreeTen-Extra库添加到项目中。该库扩展了java.time框架,并且是可能添加到java.time的试验场。

ThreeTen-Extra包含Interval课程,其中包含abutscontainsenclosesoverlaps等便捷方法。

关于 java.time

java.time框架内置于Java 8及更高版本中。这些类取代了麻烦的旧legacy日期时间类,例如java.util.DateCalendar和& SimpleDateFormat

现在位于Joda-Timemaintenance mode项目建议迁移到java.time类。

要了解详情,请参阅Oracle Tutorial。并搜索Stack Overflow以获取许多示例和解释。规范是JSR 310

您可以直接与数据库交换 java.time 对象。使用符合JDBC driver或更高版本的JDBC 4.2。不需要字符串,不需要java.sql.*类。

从哪里获取java.time类?

答案 5 :(得分:5)

public static boolean isToday(Date date){
    Calendar today = Calendar.getInstance();
    Calendar specifiedDate  = Calendar.getInstance();
    specifiedDate.setTime(date);

    return today.get(Calendar.DAY_OF_MONTH) == specifiedDate.get(Calendar.DAY_OF_MONTH)
            &&  today.get(Calendar.MONTH) == specifiedDate.get(Calendar.MONTH)
            &&  today.get(Calendar.YEAR) == specifiedDate.get(Calendar.YEAR);
}

答案 6 :(得分:4)

检查日期是否是今天的日期,或者不检查日期,而不是时间,因此请将时间00:00:00并使用下面的代码

    Calendar c = Calendar.getInstance();

    // set the calendar to start of today
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);

    Date today = c.getTime();

    // or as a timestamp in milliseconds
    long todayInMillis = c.getTimeInMillis();


    int dayOfMonth = 24;
    int month = 4;
    int year =2013;

    // reuse the calendar to set user specified date
    c.set(Calendar.YEAR, year);
    c.set(Calendar.MONTH, month - 1);
    c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
    c.set(Calendar.HOUR_OF_DAY, 0);
    c.set(Calendar.MINUTE, 0);
    c.set(Calendar.SECOND, 0);
    c.set(Calendar.MILLISECOND, 0);
    // and get that as a Date
    Date dateSpecified = c.getTime();

    // test your condition
    if (dateSpecified.before(today)) {

        Log.v(" date is previou")
    } else if (dateSpecified.equal(today)) {

        Log.v(" date is today ")
    } 
             else if (dateSpecified.after(today)) {

        Log.v(" date is future date ")
    } 

希望它会有所帮助....

答案 7 :(得分:2)

    boolean isBeforeToday(Date d) {
        Date today = new Date();
        today.setHours(0);
        today.setMinutes(0);
        today.setSeconds(0);
        return d.before(today);
    }

答案 8 :(得分:1)

我假设您使用整数代表您的年,月和日?如果要保持一致,请使用Date方法。

Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay; 
currentYear = cal.get(Calendar.YEAR); 
currentMonth = cal.get(Calendar.MONTH); 
currentDay = cal.get(Calendar.DAY_OF_WEEK);

     if(startYear < currentYear)
                {
                    message = message + "Start Date is Before Today" + "\n";
                }
            else if(startMonth < currentMonth && startYear <= currentYear)
                    {
                        message = message + "Start Date is Before Today" + "\n";
                    }
            else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
                        {
                            message = message + "Start Date is Before Today" + "\n";
                        }

答案 9 :(得分:1)

执行此操作的另一种方法:

public class TimeUtils {

    /**
     * @param timestamp
     * @return
     */
    public static boolean isToday(long timestamp) {
        Calendar now = Calendar.getInstance();
        Calendar timeToCheck = Calendar.getInstance();
        timeToCheck.setTimeInMillis(timestamp);
        return (now.get(Calendar.YEAR) == timeToCheck.get(Calendar.YEAR)
                && now.get(Calendar.DAY_OF_YEAR) == timeToCheck.get(Calendar.DAY_OF_YEAR));
    }

}

答案 10 :(得分:0)

试试这个:

public static boolean isToday(Date date)
{
    return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}

答案 11 :(得分:0)

public static boolean itIsToday(long date){
    boolean result = false;
    try{
        Calendar calendarData = Calendar.getInstance();
        calendarData.setTimeInMillis(date);
        calendarData.set(Calendar.HOUR_OF_DAY, 0);
        calendarData.set(Calendar.MINUTE, 0);
        calendarData.set(Calendar.SECOND, 0);
        calendarData.set(Calendar.MILLISECOND, 0);

        Calendar calendarToday = Calendar.getInstance();
        calendarToday.setTimeInMillis(System.currentTimeMillis());
        calendarToday.set(Calendar.HOUR_OF_DAY, 0);
        calendarToday.set(Calendar.MINUTE, 0);
        calendarToday.set(Calendar.SECOND, 0);
        calendarToday.set(Calendar.MILLISECOND, 0);

        if(calendarToday.getTimeInMillis() == calendarData.getTimeInMillis()) {
            result = true;
        }
    }catch (Exception exception){
        Log.e(TAG, exception);
    }
    return result;
}