繁体   English   中英

用今天的日期检查日期

[英]Check date with todays 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";
}

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

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

有关更多信息,请参阅这篇文章DateUtils Java

这有帮助吗?

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 + "]");
}

tl;博士

LocalDate
.parse( "2021-01-23" )
.isBefore(
    LocalDate.now(
        ZoneId.of( "Africa/Tunis" ) 
    )
)

… 或者:

try 
{
    org.threeten.extra.LocalDateRange range =         
        LocalDateRange.of( 
            LocalDate.of( "2021-01-23" ) ,
            LocalDate.of( "2021-02-21" )
        )
    ;
    if( range.isAfter( 
        LocalDate.now( ZoneId.of( "Africa/Tunis" ) )
    ) { … }
    else { … handle today being within or after the range. }
} catch ( java.time.DateTimeException e ) {
    // Handle error where end is before start.
}

细节

其他答案忽略了时区的关键问题。

其他答案使用过时的类。

避免旧的日期时间类

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

java.time

LocalDate

对于仅日期值,没有时间和时区,使用LocalDate class。

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

时区

请注意,虽然LocalDate存储时区,但确定诸如“今天”之类的日期需要时区。 对于任何给定的时刻,日期可能因世界各地的时区而异。 例如,巴黎的新一天比蒙特利尔更早。 巴黎午夜过后的片刻,在蒙特利尔仍然是“昨天”。

如果您只有一个与 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 ) ) ;

LocalDateRange

如果在这样的时间范围内广泛工作,请考虑将ThreeTen-Extra库添加到您的项目中。 该库扩展了 java.time 框架,并且是可能添加到 java.time 的试验场。

ThreeTen-Extra 包括一个LocalDateRange class 以及方便的方法,例如abutscontainsenclosesoverlaps等。


关于java.time

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

现在处于维护模式Joda-Time项目建议迁移到java.time类。

要了解更多信息,请参阅Oracle 教程 并在 Stack Overflow 上搜索许多示例和解释。 规范是JSR 310

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

从哪里获得 java.time 课程?

Android 已经为此配备了专用的 class。 检查DateUtils.isToday(long when)

使用纯 Java:

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);
    }

使用Joda Time这可以简化为:

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

检查日期是否是今天的日期,或者不仅检查日期不包含在其中的时间,因此将时间设为 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 ")
    } 

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

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

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

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));
    }

}

我假设您使用整数来表示您的年、月和日? 如果要保持一致,请使用 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";
                        }

尝试这个:

public static boolean isToday(Date date)
{
    return org.apache.commons.lang3.time.DateUtils.isSameDay(Calendar.getInstance().getTime(),date);
}
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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM