简体   繁体   中英

Java date format get all dates between two date values

I am writting a java application and I just started with java Date . What I am trying to do is to read a json that contains two date stamps that look like this: 2015-05-20T17:24Z[UTC] . After I read the two dates I want to take only the objects that have time stamp between the two dates I have just read. Can anyone help me on how to work with this format?

public static List<Date> getDaysBetweenDates(Date startdate, Date enddate)
{
    List<Date> dates = new ArrayList<Date>();
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(startdate);

    while (calendar.getTime().before(enddate))
    {
        Date result = calendar.getTime();
        dates.add(result);
        calendar.add(Calendar.DATE, 1);
    }
    return dates;
   }

Function above will list all the valid date objects between two dates

Java 8

Start by converting the String value to something which is comparable...

String text = "2015-05-20T17:24Z[UTC]";
ZonedDateTime from = ZonedDateTime.parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME);

Now, (obviously), you need a to date as well, but the conversion is the same process. When you need to, convert the value you want to compare to a ZonedDateTime object (as above) and use it's functionality to determine if it's within the specified range...

ZonedDateTime from = ...;
ZonedDateTime to = ...;
ZonedDateTime date = ...;

if (date.isAfter(from) && date.isBefore(to)) {

}

Now, this is exclusive, if you want the from and to dates to be inclusive, you'll need to add a isEqual check for both the from and to dates (but it only needs to match one, obviously)

Now, you should be able to use something similar with using Joda-Time

To parse the date use SimpleDateFormat :

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd'T'hh:mm'Z'[ZZZ]" );
Date date = sdf.parse( "2015-05-20T17:24Z[UTC]" );

Then either loop over the objects you want to filter and check object.date.compareTo(startDate) >= 0 and object.date.compareTo(endDate) <= 0 etc.

Alternatively use a sorted map with the objects' date as key.

Create your from/to ZonedDateTime's as MadProgrammer said:

ZonedDateTime from = ZonedDateTime.parse(text, DateTimeFormatter.ISO_ZONED_DATE_TIME);

Then create Joda DateTime 's for from/to:-

DateTimeZone zone = DateTimeZone.forID(zdt.getZone().getId());
DateTime from = new DateTime(zdt.toInstant().toEpochMilli());

Then use Joda's Interval.contains() to check if each Instant falls within the interval - keeping in mind that contains() excludes the end date.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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