简体   繁体   English

比较Java中的日期 - 只有年,月和日

[英]Comparing dates in Java - only years, months and days

I'm trying to compare to dates object. 我想与date对象进行比较。 Only one problem is that I want to compare just days, month and years. 只有一个问题是我想比较几天,几个月和几年。

/* toString output
mydate 2013-08-23
current date: Thu Aug 23 14:15:34 CEST 2013

If I compare just days ( 23-08-2013 ) dates are equal, if I'm using .after() .before() methods dates are diffrent. 如果我比较几天(23-08-2013)日期是相等的,如果我使用.after()。之前()方法日期是不同的。

Is there is Java method that compares only days, month, years in easy way or do I have to compare each value ? 是否有简单比较日,月,年的Java方法或者我必须比较每个值?

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();
cal1.setTime(date1);
cal2.setTime(date2);
boolean sameDay = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
              cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR);

This will work perfectly......... 这将完美地工作.........

If you don't want to use external libraries and there is no problem using Calendar you could try something like this: 如果您不想使用外部库并且使用Calendar没有问题,您可以尝试这样的事情:

Calendar calendar1= Calendar.getInstance();
Calendar calendar2= Calendar.getInstance();

Date date1 = ...;
Date date2= ...;

calendar1.setTime(date1);
calendar1.set(Calendar.HOUR_OF_DAY, 0);
calendar1.set(Calendar.MINUTE, 0);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.MILLISECOND, 0);

calendar2.setTime(date2);
calendar2.set(Calendar.HOUR_OF_DAY, 0);
calendar2.set(Calendar.MINUTE, 0);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.MILLISECOND, 0);

calendar1.after(calendar2);
calendar1.before(calendar2);

Not so simple but is something... 不是那么简单但是......

Unfortunately, date support in the core Java API is very weak. 不幸的是,核心Java API中的日期支持非常弱。 You could use Calendar to strip time/timezone information from your date. 您可以使用Calendar从日期中删除时间/时区信息。 You'd probably want to write a separate method to do that. 你可能想要写一个单独的方法来做到这一点。 You could also use the Joda API for date/time support, as it's much better than Java's. 你也可以使用Joda API来支持日期/时间,因为它比Java更好。

Joda-Time is much better and highly recommended. Joda-Time更好,强烈推荐。 But if you have to use Java api, you can do- 但是如果你必须使用Java api,你可以 -

Calendar c1 = Calendar.getInstance();
Calendar c2 = Calendar.getInstance();

c1.setTime(someDate);
c2.setTime(someOtherDate);

int yearDiff = c1.get(Calendar.YEAR) - c2.get(Calendar.YEAR);
int monthDiff = c1.get(Calendar.MONTH) - c2.get(Calendar.MONTH);
int dayDiff = c1.get(Calendar.DAY_OF_MONTH) - c2.get(Calendar.DAY_OF_MONTH);

Say to compare only year, you can do- 比如只比较一年,你可以做 -

if(c1.get(Calendar.YEAR) > c2.get(Calendar.YEAR)){
    // code
}

etc. 等等

Date date = new Date();
String str="2013-08-23";
Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str);

Calendar cal = Calendar.getInstance();
cal.setTime(date);
Calendar cal1 = Calendar.getInstance();
cal1.setTime(date1);

if(cal.get(Calendar.YEAR) == cal1.get(Calendar.YEAR)){
System.out.println("Years are equal");
}
else{
System.out.println("Years not equal");
}

if(cal.get(Calendar.MONTH) == cal1.get(Calendar.MONTH)){
System.out.println("Months are equal");
}
else{
System.out.println("Months not equal");
}

No there is nothing in the JDK. JDK中没有任何内容。 You could use some external library as Apache Commons Lang . 你可以使用一些外部库作为Apache Commons Lang There is a method DateUtils.isSameDay(Date, Date) which would do what you are looking for. 有一种方法DateUtils.isSameDay(Date, Date)您的需求。

Better would be to avoid to use the Date of Java and use for instance JodaTime . 更好的方法是避免使用Java的Date并使用例如JodaTime

tl;dr TL;博士

I want to compare just days, month and years. 我想比较几天,几个月和几年。

mydate 2013-08-23 mydate 2013-08-23

current date: Thu Aug 23 14:15:34 CEST 2013 当前日期:8月23日星期四14:15:34 CEST 2013

If you want to capture the current date dynamically. 如果要动态捕获当前日期。

LocalDate.now(                   // Capture the current date…
    ZoneId.of( "Europe/Paris" )  // …as seen by the wall-clock time used by the people of a particular region (a time zone).
)
.isEqual(
    LocalDate.parse( "2013-08-23" ) 
)

Or, for a specific moment. 或者,在特定时刻。

ZonedDateTime.of(  // Thu Aug 23 14:15:34 CEST 2013
    2013 , 8 , 23 , 14 , 15 , 34 , 0 , ZoneId.of( "Europe/Paris" )     
)
.toLocalDate()     // Extract the date only, leaving behind the time-of-day and the time zone.
.isEqual(
    LocalDate.parse( "2013-08-23" ) 
)

LocalDate

The bundled java.util.Date and .Calendar classes are notoriously troublesome. 捆绑的java.util.Date和.Calendar类是众所周知的麻烦。 Avoid them. 避免他们。 As other answers suggested, use a decent date-time libary. 正如其他答案所建议的那样,使用一个体面的日期时间库。 That means either: 这意味着:

You need to extract a date-only value from your date-time, to ignore the time-of-day. 您需要从日期时间中提取仅日期值,以忽略时间。 Both Joda-Time and java.time have such a class, coincidentally named LocalDate . Joda-Time和java.time都有这样一个类,巧合地命名为LocalDate

java.time java.time

The java.time framework built into Java 8 and later supplants the old java.util.Date/.Calendar classes. Java 8及更高版本中内置的java.time框架取代了旧的java.util.Date/.Calendar类。 The new classes are inspired by the highly successful Joda-Time framework, intended as its successor, similar in concept but re-architected. 新课程的灵感来自非常成功的Joda-Time框架,旨在作为其继承者,在概念上类似但重新设计。 Defined by JSR 310 . JSR 310定义。 Extended by the ThreeTen-Extra project. ThreeTen-Extra项目扩展。 See the Tutorial . 请参阅教程

ZoneId zoneId = ZoneId.of( "Europe/Paris" );

ZonedDateTime x = ZonedDateTime.of( 2014, 1, 2, 3, 4, 5, 6, zoneId );
ZonedDateTime y = ZonedDateTime.now( zoneId );

Extract and compare the date-only portion of the date-time by calling toLocalDate . 通过调用toLocalDate提取并比较日期时间的仅日期部分。

Boolean isSameDate = x.toLocalDate().isEqual( y.toLocalDate() );

Joda-Time 乔达时间

DateTimeZone timeZoneParis = DateTimeZone.forID( "Europe/Paris" );

DateTime x = new DateTime( 2014, 1, 2, 3, 4, 5, 6, timeZoneParis );
DateTime y = new DateTime( 2014, 6, 5, 4, 3, 2, 1, timeZoneParis );

boolean isXAfterY = x.isAfter( y );

To test equality of the date portion, convert the DateTime objects to a LocalDate which describes only a date without any time-of-day or time zone (other than a time zone used to decide the date). 要测试日期部分的相等性,请将DateTime对象转换为LocalDate ,它仅描述没有任何时间或时区的日期(用于确定日期的时区除外)。

boolean isSameDate = x.toLocalDate().isEqual( y.toLocalDate() );

If you want to examine the constituent elements, Joda-Time offers methods such as dayOfMonth , hourOfDay, and more. 如果你想检查组成元素,Joda-Time提供了诸如dayOfMonth ,hourOfDay等方法。

How about this way 这样怎么样

    String str="2013-08-23";
    Date date=new SimpleDateFormat("yyyy-MM-dd").parse(str);
    Calendar cal=Calendar.getInstance();
    cal.setTime(date);
    Calendar calNow=Calendar.getInstance();

    if(cal.get(Calendar.YEAR)>calNow.get(Calendar.YEAR)){
        // do something
    }if(cal.get(Calendar.MONTH)>calNow.get(Calendar.MONTH)){
        // do something
    }if(cal.get(Calendar.DATE)>calNow.get(Calendar.DATE)){
       // do something
    }

You can try this 你可以试试这个

    Date d1= ...
    Date d2= ...
    long dayInMillis = 24 * 3600 * 1000; 
    boolean dateEqual = d1.getTime() / dayInMillis == d2.getTime() / dayInMillis;  

The solution to this problem is surprisingly simple. 这个问题的解决方案非常简单。 You'll need to begin by parsing your date time strings into Date instants in the Java API (you can use a SimpleDateFormat object to help you do this). 您需要首先将日期时间字符串解析为Java API中的Date时刻(您可以使用SimpleDateFormat对象来帮助您执行此操作)。

If you have two instants in time represented as Dates: 如果您有两个时间表示为日期:

  1. Get the representation of both as long integers 获取两个整数的表示
  2. Because all Dates are represented internally in UTC, adjust both to the local time zone by adding or substracting the offsets from GMT +/- DST 因为所有日期都在UTC内部表示,所以通过添加或减去GMT +/- DST的偏移量来调整本地时区
  3. Convert both to an integer count of days (which will include the granularity for comparing years and months) 将两者都转换为整数天数(包括比较年份和月份的粒度)
  4. Compare them by their natural order; 比较它们的自然顺序; if the integers are equal, the day, month, and year are equal irrespective of local time (assuming, of course, that both Date instants were in the same time zone). 如果整数相等,则无论当地时间如何,日,月和年都是相等的(当然,假设两个日期时刻都在同一时区)。

Presto! 普雷斯托!

A method for adjusting a Date object to local time and returning it as a decimal count of days in the POSIX Epoch follows: 将Date对象调整为本地时间并将其作为POSIX Epoch中的十进制天数返回的方法如下:

public static double toLocalDayNumber(Date d, GregorianCalendar gc) {

        gc.setTime(d);

        long utcDateAsMillisFromEpoch = gc.getTimeInMillis();
        long localDateAsMillisFromEpoch = utcDateAsMillisFromEpoch +
                gc.get(GregorianCalendar.ZONE_OFFSET) +
                gc.get(GregorianCalendar.DST_OFFSET);

        return (((double) localDateAsMillisFromEpoch) / (86400.0 * 1000.0);
}

This method takes a Date object d , and a Java API Calendar object gc that has been constructed with the local TimeZone of interest. 此方法采用Date对象d和使用感兴趣的本地TimeZone构造的Java API Calendar对象gc

By using Date only 仅使用Date

        SimpleDateFormat cDate1 = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date now1 = new Date();
        String ccDate1 = cDate1.format(now1);
        System.out.println("Date1=="+ccDate1);


        SimpleDateFormat cDate2 = new SimpleDateFormat("yyyy-MM-dd HH-mm-sss");
        Date now2 = new Date();
        String ccDate2 = cDate2.format(now2);
        System.out.println("Date2=="+ccDate2);

        if(ccDate1.equals(ccDate2))//Get full feature of date
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

        if(ccDate1.split(" ")[0].equals(ccDate2.split(" ")[0]))//Comparing  Full Date
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

        if(ccDate1.split(" ")[0].split("-")[0].equals(ccDate2.split(" ")[0].split("-")[0]))//Comparing YEAR
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

        if(ccDate1.split(" ")[0].split("-")[1].equals(ccDate2.split(" ")[0].split("-")[1]))//Comparing MONTH
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

        if(ccDate1.split(" ")[0].split("-")[2].equals(ccDate2.split(" ")[0].split("-")[2]))//Comparing DAY
            System.out.println("Equal");
        else
            System.out.println("Not Equal");

An example using Java Calendar to compare only the date parts between 2 calendar objects without having to clear() all other calendar fields (MINUTE, MILLISECOND, etc), which gets set when Calendar.getInstance() is called. 使用Java Calendar仅比较2个日历对象之间的日期部分而不必清除()所有其他日历字段(MINUTE,MILLISECOND等)的示例,这些日历字段在调用Calendar.getInstance()时设置。

I know this thread is old, and this is not a new solution but might be of help to some people. 我知道这个帖子已经过时了,这不是一个新的解决方案,但可能对某些人有所帮助。

Calendar cal1 = Calendar.getInstance();
Calendar cal2 = Calendar.getInstance();

cal1.set(2018, Calendar.JANUARY, 1);
cal2.set(2018, Calendar.JANUARY, 1);

System.out.println(_doesCalendar1DateMatchCalendar2Date(cal1,cal2)); // in this case returns true

private boolean _doesCalendar1DateMatchCalendar2Date(Calendar cal1, Calendar cal2) {
            boolean sameDate = cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) 
                    && cal1.get(Calendar.MONTH) == cal2.get(Calendar.MONTH)
                    && cal1.get(Calendar.DATE) == cal2.get(Calendar.DATE);
            return sameDate;
        }

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

相关问题 获得两个日期之间的差异 - 没有几个月 - 没有几天 - Get difference between two dates in years - without months - without days java.sql.Date 可以强制只插入年、月、日到 Oracle 日期列吗 - Can java.sql.Date be forced to insert only years, months, days to an Oracle Date column 日期之间的天/月(仅年/月) - Days/Months between to Dates(only Year/Month) Java 7中两个日期的月份和月份之间的差异 - Difference between 2 dates in months and days in Java 7 用于查找年,月和日中2个日期对象之间差异的Java方法 - Java method to find difference between 2 date objects in years, months and days 将日期与月份作为字符串进行比较 - Comparing dates with months as strings 如何使用Joda-Time计算两个日期之间的年,月和天数 - How to calculate No of Years, Months and days between two dates using Joda-Time 在 Android 中获取年、月和日中两个选定日期之间的正确差异 - Get correct difference between two selected dates in years, months and days in Android Java 7获得2个日期之间的天数,并正确计算leap年 - Java 7 get number of days between 2 dates with correct calculation for leap years 将天数(int)转换为Java中的天,月和年(包括leap年) - Converting number of days(int) into days,months and years in java (including leap year)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM