Scala random date between two dates - java

I am trying to write a method which takes two java.util.Date's as parameters and returns a random java.util.Date between these two in Scala. However, I get the same dummy result each time. What is wrong with my code?
Note:
randomDateBetween(new Date(2017, 1, 1), new Date(2018, 1, 1)) returns Tue Jun 12 09:36:00 EET 3917 like all the time
Code:
def randomDateBetween( firstDate : Date, secondDate : Date) : Date =
{
val ratio = new Random().nextInt(100);
val difference = (secondDate.getTime - firstDate.getTime)
val surplusMillis = (difference * (ratio / 100.0)).asInstanceOf[Long]
val cal = Calendar.getInstance()
cal.setTimeInMillis(surplusMillis + firstDate.getTime)
return cal.getTime()
}
I fixed it guys, thank you anyway. Cause of the error was java.util.Date being deprecated. I changed my method call like this and it worked perfectly fine:
val date1 = Calendar.getInstance
val date2 = Calendar.getInstance
date1.set(2017, 1, 1)
date2.set(2018, 1, 1)
randomDateBetween(date1.getTime, date2.getTime)

You need to seed the Random object like so:
Random.setSeed(System.currentTimeMillis())
val ratio = new Random().nextInt(100)

(Java syntax here, rather than Scala)
ThreadLocalRandom
The Answer by sheunis is correct but outdated.
Another outdated option is Math.random.
randomNum = minimum + ( int )( Math.random() * maximum );
The modern approach since Java 7 is ThreadLocalRandom. See this Answer.
long random = ThreadLocalRandom.current().nextLong( minimum , maximum + 1 );
Both of these alternatives to Random are initialized with an internally generated seed that may not otherwise be modified.
Avoid legacy date-time classes.
Also you are using troublesome old date-time classes Date and Calendar that are now legacy, supplanted by java.time classes.
Using java.time
For date-only values without time-of-day and without time zone, use LocalDate class.
LocalDate start = LocalDate.of( 2017 , Month.JANUARY , 1 ) ;
LocalDate stop = LocalDate.of( 2018 , Month.JANUARY , 1 ) ;
Count days between, to determine random number of days.
long maxDays = ChronoUnit.DAYS.between( start , stop ) ;
So we want to add a random number of days, as little as zero and as much as maxDays.
long days = ThreadLocalRandom.current().nextLong( 0 , maxDays + 1 );
LocalDate ld = start.plusDays( days ) ;

Date randomDate= new Date(ThreadLocalRandom.current().nextLong(fromDate.getTime(), toDate.getTime()+1));
I don't know much about scala. I have tested it in java, I think this solution is applicable for scala as well. Please modify the code if needed.

Related

Java calculate time by adding specific number of hours, but consider only working hours and non weekend days

For example I have sentTime as an input (25 May 2021 02:00:00 PM) and I need to add reviewTime (10 hours) and calculate releasingTime (considering only working hours(9am-5pm) and non weekend days)
25 May 2021 02:00:00 PM + 10 hours would be 26 May 2021 04:00:00 PM
java.time
I do not know of any easy way to do this. The java.time classes have all the parts needed, but you would have to build up some code to do the calculations.
Be aware that you must account for time zone. On some dates, you will encounter anomalies such as days being 23 or 25 hours long, the clock skipping ahead or dropping behind. One example of such anomalies is Daylight Saving Time (DST), but that is not the only cause. Politicians around the world have shown a penchant for redefining the time-keeping of their jurisdictions for varied reasons.
Here is a brief example to get you started, if you choose to go this route.
Besides the java.time classes built into Java, this code also leverages the ThreeTen-Extra library which adds functionality to java.time. We need that library for two classes here:
A TemporalAdjuster for finding the next working day (skipping Saturday-Sunday). See tutorial on temporal adjusters. Tip: You may want to consider implementing a TemporalAdjuster on your own as part of a real solution — but I'm not sure, just an idea I have not thought through.
Interval class to track a pair of moments as seen in UTC (an offset of zero hours-minutes-seconds). Not required here, but might be useful in further work.
Duration work = Duration.ofHours( 10 );
LocalTime shiftStart = LocalTime.of( 9 , 0 );
LocalTime shiftEnd = LocalTime.of( 17 , 0 );
ZoneId z = ZoneId.of( "America/Chicago" );
ZonedDateTime startOfWork = ZonedDateTime.of( 2021 , 5 , 25 , 14 , 0 , 0 , 0 , z );
// Calculate how much time left in the day to work.
ZonedDateTime endOfDayOne = startOfWork.with( shiftEnd );
Duration untilEndOfDayOne = Duration.between( startOfWork , endOfDayOne );
Duration remainingWork = work.minus( untilEndOfDayOne );
// Determine next work-day.
// Add ThreeTen-Extra library to your project to access the `TemporalAdjuster` for `nextWorkingDay()`.
LocalDate nextWorkDay = endOfDayOne.toLocalDate().with( org.threeten.extra.Temporals.nextWorkingDay() );
ZonedDateTime startOfNextWorkingDay = ZonedDateTime.of( nextWorkDay , shiftStart , z );
ZonedDateTime endOfWork = startOfNextWorkingDay.plus( remainingWork );
org.threeten.extra.Interval workInterval =
org.threeten.extra.Interval.of(
startOfWork.toInstant() ,
endOfWork.toInstant()
);
Dump to console. By default, java.time generates text in standard ISO 8601 formats.
System.out.println( "startOfWork = " + startOfWork );
System.out.println( "work = " + work );
System.out.println( "endOfWork = " + endOfWork );
System.out.println( "workInterval = " + workInterval );
When run.
startOfWork = 2021-05-25T14:00-05:00[America/Chicago]
work = PT10H
endOfWork = 2021-05-26T16:00-05:00[America/Chicago]
workInterval = 2021-05-25T19:00:00Z/2021-05-26T21:00:00Z
Project management software
Project Management software is built to do this very job: Calculate elapsed time for various tasks restricted by working hours and working days. One possible solution is trying to leverage such a library for your purposes.
Assuming sentTime is of type java.util.Date, you can may be use the following code that utilizes Java 8's java.time.LocalDateTime
int reviewTime = 10;
List<DayOfWeek> weekends = Arrays.asList(DayOfWeek.SATURDAY, DayOfWeek.SUNDAY);
LocalDateTime start = sentTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
final int workingHoursStart = 9;
final int workingHoursEnd = 17;
int hoursReviewed = 0;
while(reviewTime > hoursReviewed){
DayOfWeek dayOfWeek = start.getDayOfWeek();
if(weekends.contains(dayOfWeek) || start.getHour() < workingHoursStart || start.getHour() > workingHoursEnd){
start = start.plusHours(1);
continue;
}
start = start.plusHours(1);
hoursReviewed++;
}
Your resultant releasingTime time would be in the start object after the loop finishes iterating.

How to know if a date is in previous x minutes?

I have an ISO String date like this one: 2019-12-17 15:14:29.198Z
I would like to know if this date is in the previous 15 minutes from now.
Is-it possible to do that with SimpleDateFormat ?
val dateIso = SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.FRENCH).parse(isoString)
java.time.Instant
Use Instant class to represent a moment in UTC.
To parse, replace SPACE with a T per the ISO 8601 standard.
Instant instant = Instant.parse( "2019-12-17 15:14:29.198Z".replace( " " , "T" ) ;
Determine the current moment in UTC.
Instant now = Instant.now() ;
Determine 15 minutes ago. Call plus…/minus… methods for date-time math.
Instant then = now.minusMinutes( 15 ) ;
Apply your test. Here we use the Half-Open approach where the beginning is inclusive while the ending is exclusive.
boolean isRecent =
( ! instant.isBefore( then ) ) // "Not before" means "Is equal to or later".
&&
instant.isBefore( now )
;
For older Android, add the ThreeTenABP library that wraps the ThreeTen-Backport library. Android 26+ bundles java.time classes.
If you are doing much of this work, add the ThreeTen-Extra library to your project (may not be appropriate for Android, not sure). This gives you the Interval class and it’s handy comparison methods such as contains.
Interval.of( then , now ).contains( instant )
If you already know the reference date everytime you access the program, you can use java.util.Calendar.
boolean isBefore;
long timeToCheck = 15*60*1000; //15 minutes.
Calendar calendar = Calendar.getInstance(), calendar2 = Calendar.getInstance();
calendar.set(Calendar.DATE, yourDay);
calendar.set(Calendar.HOUR_OF_DAY, yourHour);
calendar.set(Calendar.MINUTE, yourMinute);
calendar.set(Calendar.SECOND, yourSecond);
if (calendar.before(calendar2)){
long timeInMillis = calendar2.getTimeInMillis() - calendar.getTimeInMillis();
if ( timeInMillis >= timeToCheck ) isBefore = true;
else isBefore = false;
}
Is this you want:
int xMinutes = 10 * 60 * 1000;
long dateIsoinMillis = dateIso.getTime();
long xMinsAgo = System.currentTimeMillis() - xMinutes;
if (dateIsoinMillis < xMinsAgo) {
System.out.println("searchTimestamp is older than 10 minutes");
}

Test a date within a day intervall range

I have a date and a number and want to check if this date and this number occurs in a list of other dates within:
+-20 date intervall with the same number
so for example 1, 1.1.2013 and 1,3.1.2013 should reuturn false.
I tried to implement the method something like that:
private List<EventDate> dayIntervall(List<EventDate> eventList) throws Exception {
List<EventDate> resultList = new ArrayList<EventDate>();
for (int i = 0; i < eventList.size(); i++) {
String string = eventList.get(i).getDate();
Date equalDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string);
for (int j = 0; j < eventList.size(); j++) {
String string1 = eventList.get(i).getDate();
Date otherDate = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN).parse(string1);
if (check number of i with number of j && check Date) {
//do magic
}
}
}
return resultList;
}
The construction of the iteration method is not that hard. What is hard for me is the date intervall checking part. I tried it like that:
boolean isWithinRange(Date testDate, Date days) {
return !(testDate.before(days) || testDate.after(days));
}
However that does not work because days are not takes as days. Any suggestions on how to fix that?
I really appreciate your answer!
You question is difficult to follow. But given its title, perhaps this will help…
Span Of Time In Joda-Time
The Joda-Time library provides a trio of classes to represent a span of time: Interval, Period, and Duration.
Interval
An Interval object has specific endpoints that lie on the timeline of the Universe. A handy contains method tells if a DateTime object occurs within those endpoints. The beginning endpoint in inclusive while the last endpoint is exclusive.
Time Zones
Note that time zones are important, for handling Daylight Saving Time and other anomalies, and for handling start-of-day. Keep in mind that while a java.util.Date seems like it has a time zone but does not, a DateTime truly does know its own time zone.
Sample Code
Some code off the top of my head (untested)…
DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime dateTime = new DateTime( yourDateGoesHere, timeZone );
Interval interval = new Interval( dateTime.minusDays( 20 ), dateTime.plusDays( 20 ) );
boolean didEventOccurDuringInterval = interval.contains( someOtherDateTime );
Whole Days
If you want whole days, call the withTimeAtStartOfDay method to get first moment of the day. In this case, you probably need to add 21 rather than 20 days for the ending point. As I said above, the end point is exclusive. So if you want whole days, you need the first moment after the time period you care about. You need the moment after the stroke of midnight. If this does not make sense, see my answers to other questions here and here.
Note that Joda-Time includes some "midnight"-related methods and classes. Those are no longer recommended by the Joda team. The "withTimeAtStartOfDay" method takes their place.
DateTime start = dateTime.minusDays( 20 ).withTimeAtStartOfDay();
DateTime stop = dateTime.plusDays( 21 ).withTimeAtStartOfDay(); // 21, not 20, for whole days.
Interval interval = new Interval( start, stop );
You should avoid java.util.Date if at all possible. Using the backport of ThreeTen (the long awaited replacement date/time API coming in JDK8), you can get the number of days between two dates like so:
int daysBetween(LocalDate start, LocalDate end) {
return Math.abs(start.periodUntil(end).getDays());
}
Does that help?
You can get the number of dates in between the 2 dates and compare with your days parameter. Using Joda-Time API it is relatively an easy task: How do I calculate the difference between two dates?.
Code:
SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy", Locale.GERMAN);
Date startDate = format.parse("1.1.2013");
Date endDate = format.parse("3.1.2013");
Days d = Days.daysBetween(new DateTime(startDate), new DateTime(endDate));
System.out.println(d.getDays());
Gives,
2
This is possible using Calendar class as well:
Calendar cal = Calendar.getInstance();
cal.setTime(startDate);
System.out.println(cal.fieldDifference(endDate, Calendar.DAY_OF_YEAR));
Gives,
2
This 2 can now be compared to your actual value (20).

Android/Java - Test if date was last month

I am working on an app where I store some information between each use, this data essentially boils down to counting the number of times an event has happened today, this week, this month and in the apps lifetime. I store this data in 4 distinct counters I can load/save using SharedPreferences.
Alongside the data I store the "last run time" of the app as a date, my plan was that during load time I will load in the counters then test the stored date against today's date to determine which counters need to be cleared.
Sounds simple right!
After pulling my hair out for a while and going backward and forwards through the Calendar documentation I think I understand them enough to come up with the following:
Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
Calendar today = Calendar.getInstance();
today.add(Calendar.DATE, -1);
if ( !last.after(today) )
{
today = 0;
}
today.add(Calendar.WEEK_OF_MONTH, -1);
today.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
if ( !last.after(today) )
{
today = 0;
week = 0;
}
today = Calendar.getInstance();
today.add(Calendar.MONTH, -1);
today.set(Calendar.DATE, today.getActualMaximum(Calendar.DATE));
if ( !last.after(today) )
{
today = 0;
week = 0;
month = 0;
}
I think this should be fine, however the issue I have is testing, testing today is easy, however testing the month logic would require either waiting a month, or writing a test case which uses the Calendar API to simulate an old date, however I can't write the test case if my assumptions on how the API works was wrong in the first place!
Therefore, after a large wall of text my question is... does the above block of code look sane, or have I completely mis-understood working with dates in Java?
Thanks!
Edit:
Second pass at the code:
Does this look any more sensible? If I am understanding things correctly I am now attempting to compare the end of the date that was last saved with the very start of today, this week and this month.
Calendar last = Calendar.getInstance();
last.setTimeInMillis(lastDate);
last.set(Calendar.HOUR_OF_DAY, last.getActualMaximum(Calendar.HOUR_OF_DAY));
last.set(Calendar.MINUTE, last.getActualMaximum(Calendar.MINUTE));
last.set(Calendar.SECOND, last.getActualMaximum(Calendar.SECOND));
last.set(Calendar.MILLISECOND, last.getActualMaximum(Calendar.MILLISECOND));
Calendar todayStart = Calendar.getInstance();
todayStart.set(Calendar.HOUR_OF_DAY, todayStart.getActualMinimum(Calendar.HOUR_OF_DAY));
todayStart.set(Calendar.MINUTE, todayStart.getActualMinimum(Calendar.MINUTE));
todayStart.set(Calendar.SECOND, todayStart.getActualMinimum(Calendar.SECOND));
todayStart.set(Calendar.MILLISECOND, todayStart.getActualMinimum(Calendar.MILLISECOND));
// If the last recorded date was before the absolute minimum of today
if ( last.before(todayStart) )
{
todayCount = 0;
}
Calendar thisWeekStart = Calendar.getInstance();
thisWeekStart.set(Calendar.HOUR_OF_DAY, thisWeekStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisWeekStart.set(Calendar.MINUTE, thisWeekStart.getActualMinimum(Calendar.MINUTE));
thisWeekStart.set(Calendar.SECOND, thisWeekStart.getActualMinimum(Calendar.SECOND));
thisWeekStart.set(Calendar.DAY_OF_WEEK, thisWeekStart.getFirstDayOfWeek());
thisWeekStart.set(Calendar.MILLISECOND, thisWeekStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this week then clear
// this week (and today, just to be on the safe side)
if ( last.before(thisWeekStart) )
{
todayCount = 0;
weekCount = 0;
}
Calendar thisMonthStart = Calendar.getInstance();
thisMonthStart.set(Calendar.HOUR_OF_DAY, thisMonthStart.getActualMinimum(Calendar.HOUR_OF_DAY));
thisMonthStart.set(Calendar.MINUTE, thisMonthStart.getActualMinimum(Calendar.MINUTE));
thisMonthStart.set(Calendar.SECOND, thisMonthStart.getActualMinimum(Calendar.SECOND));
thisMonthStart.set(Calendar.DAY_OF_MONTH, thisMonthStart.getActualMinimum(Calendar.MONTH));
thisMonthStart.set(Calendar.MILLISECOND, thisMonthStart.getActualMinimum(Calendar.MILLISECOND));
// If the last date was before the absolute minimum of this month then clear month...
if ( !last.after(thisMonthStart) )
{
todayCount = 0;
weekCount = 0;
monthCount = 0;
}
Other than the readability challenges of using a variable called "today" and setting it to all manner of things that aren't "Today", you're not handling the time.
If it's now 3:20, and something happened at 5:00pm on Jan 31st, we probably want to still count that as happening in January? You should max out the time related fields to the end of the day as well.
For the week thing, that can be a real mess if someone executes in a locale where Sunday is considered the first day of the week. You may want to consider using the system's first day of week, rather than Sunday.
Also it is probably worth noting that this depends explicitly on the use of Calendar.add() to work properly. cal.set(Calendar.MONTH, cal.get(Calendar.MONTH) -1); is NOT the same thing and would be broken.
You should just use Joda-Time. If you do your code becomes:
DateTime oneMonthAgo = new DateTime().minusMonths(1);
DateTime oneWeekAgo = new DateTime().minusWeeks(1);
And so on... It requires no further dependencies than the JDK itself and works on Android. Hope that helps.
Yes, you can use Joda-Time on Android. (From what I've read; I don't use Android)
Yes, you should be using Joda-Time. Far more advanced and useful that the notoriously troublesome java.util.Date and .Calendar classes bundled with Java.
Both your question and the other answers are ignoring the crucial issue of time zone. The time zone defines the meaning of "today" and the beginning/ending of other days.
You should define in plain declarative sentences exactly what you mean by "today", "this week", and "this month". For example, "today"…
Do you mean the last 24 hours?
Do you mean from 00:00:00 and up to but not including 00:00:00 tomorrow, in the UTC/GMT time zone (that is, no time zone offset)?
Do mean from the first moment of today in a given time zone (some offset from UTC) up to but not including the first moment of tomorrow in the same time zone? This may not be 24 hours because of Daylight Saving Time (DST) or other anomalies.
I'm too tired to parse your code. And I shouldn't have to. Before writing such date-time code, you should spell out in plain English what your goal is. Date-time work is surprisingly tricky, so you must be clear on your goals.
Here's some example code in Joda-Time 2.3.
Joda-Time uses the ISO 8601 standard for most defaults. This includes the definition of a week. Monday is first day, numbered 1, and Sunday is last day, numbered 7.
When focusing on a "day" with date-time objects, you may want to start with the first moment of the day. If so, call the withTimeAtStartOfDay method. To get end-of-day, don't. Use the Half-Open approach where you compare up to but not including the first moment of the next day. Explanation is found in other answers on StackOverflow.
Joda-Time offers 3 classes to handle spans of time: Period, Duration, and Interval. Check them all out. When doing comparisons, Joda-Time uses the "Half-Open" approach where the beginning is inclusive and the ending is exclusive. This makes sense when you ponder it. Search StackOverflow for more discussion.
Here's a bit of example code to get you going. I take a set of arbitrary date-time values. Then I define some spans of time as a day, week ago, and month ago. Then I count how many of the values fall into those spans.
String input = "2014-01-02T03:04:05Z";
DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
java.util.List<DateTime> dateTimes = new java.util.ArrayList<DateTime>();
DateTime dateTime1 = new DateTime( input, timeZone ); // Parse the string as being in Zulu time zone (UTC). Then adjust to Montréal time.
dateTimes.add( dateTime1 );
dateTimes.add( dateTime1.plusDays( 3 ) );
dateTimes.add( dateTime1.plusWeeks( 1 ) );
dateTimes.add( dateTime1.plusMonths( 1 ) );
DateTime now = new DateTime( timeZone );
dateTimes.add( now );
dateTimes.add( now.minusDays( 1 ) );
dateTimes.add( now.minusDays( 10 ) );
// Spans of time
Interval today = new Interval( now.withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
Interval pastWeek = new Interval( now.minusWeeks( 1 ).withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
Interval pastMonth = new Interval( now.minusMonths( 1 ).withTimeAtStartOfDay(), now.plusDays( 1 ).withTimeAtStartOfDay() );
int countTotal = dateTimes.size();
int countDay = 0;
int countWeek = 0;
int countMonth = 0;
for ( DateTime dateTime : dateTimes ) {
if ( today.contains( dateTime ) ) {
countDay++;
}
if ( pastWeek.contains( dateTime ) ) {
countWeek++;
}
if ( pastMonth.contains( dateTime ) ) {
countMonth++;
}
}
Dump to console…
System.out.println( "dateTimes: " + dateTimes );
System.out.println( "today: " + today );
System.out.println( "pastWeek: " + pastWeek );
System.out.println( "pastMonth: " + pastMonth );
System.out.println( "countTotal: " + countTotal );
System.out.println( "countDay: " + countDay );
System.out.println( "countWeek: " + countWeek );
System.out.println( "countMonth: " + countMonth );
When run…
dateTimes: [2014-01-01T22:04:05.000-05:00, 2014-01-04T22:04:05.000-05:00, 2014-01-08T22:04:05.000-05:00, 2014-02-01T22:04:05.000-05:00, 2014-03-05T07:40:25.508-05:00, 2014-03-04T07:40:25.508-05:00, 2014-02-23T07:40:25.508-05:00]
today: 2014-03-05T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
pastWeek: 2014-02-26T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
pastMonth: 2014-02-05T00:00:00.000-05:00/2014-03-06T00:00:00.000-05:00
countTotal: 7
countDay: 1
countWeek: 2
countMonth: 3

Java Generate all dates between x and y [duplicate]

This question already has answers here:
how to get a list of dates between two dates in java
(23 answers)
Closed 6 years ago.
I attempted to generate the date range between date x and date y but failed. I have the same method in c# so I tried to modify it as much as I can but failed to get result. Any idea what I could fix?
private ArrayList<Date> GetDateRange(Date start, Date end) {
if(start.before(end)) {
return null;
}
int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;
ArrayList<Date> listTemp = new ArrayList<Date>();
Date tmpDate = start;
do {
listTemp.add(tmpDate);
tmpDate = tmpDate.getTime() + MILLIS_IN_DAY;
} while (tmpDate.before(end) || tmpDate.equals(end));
return listTemp;
}
To be honest I was trying to get all the dates starting from january 1st till the end of year 2012 that is december 31st. If any better way available, please let me know.
Thanks
Joda-Time
Calendar and Date APIs in java are really weird... I strongly suggest to consider jodatime, which is the de-facto library to handle dates.
It is really powerful, as you can see from the quickstart: http://joda-time.sourceforge.net/quickstart.html.
This code solves the problem by using Joda-Time:
import java.util.ArrayList;
import java.util.List;
import org.joda.time.DateTime;
public class DateQuestion {
public static List<DateTime> getDateRange(DateTime start, DateTime end) {
List<DateTime> ret = new ArrayList<DateTime>();
DateTime tmp = start;
while(tmp.isBefore(end) || tmp.equals(end)) {
ret.add(tmp);
tmp = tmp.plusDays(1);
}
return ret;
}
public static void main(String[] args) {
DateTime start = DateTime.parse("2012-1-1");
System.out.println("Start: " + start);
DateTime end = DateTime.parse("2012-12-31");
System.out.println("End: " + end);
List<DateTime> between = getDateRange(start, end);
for (DateTime d : between) {
System.out.println(" " + d);
}
}
}
You could use this function:
public static Date addDay(Date date){
//TODO you may want to check for a null date and handle it.
Calendar cal = Calendar.getInstance();
cal.setTime (date);
cal.add (Calendar.DATE, 1);
return cal.getTime();
}
Found here.
And what is the reason of fail? Why you think that your code is failed?
tl;dr
Year year = Year.of ( 2012 ) ; // Represent an entire year.
year
.atDay( 1 ) // Determine the first day of the year. Returns a `LocalDate` object.
.datesUntil( // Generates a `Stream<LocalDate>`.
year
.plusYears( 1 ) // Returns a new `Year` object, leaving the original unaltered.
.atDay( 1 ) // Returns a `LocalDate`.
) // Returns a `Stream<LocalDate>`.
.forEach( // Like a `for` loop, running through each object in the stream.
System.out :: println // Each `LocalDate` object in stream is passed to a call of `System.out.println`.
)
;
java.time
The other Answers are outmoded as of Java 8.
The old date-time classes bundled with earlier versions of Java have been supplanted with the java.time framework built into Java 8 and later. See Tutorial.
LocalDate (date-only)
If you care only about the date without the time-of-day, use the LocalDate class. The LocalDate class represents a date-only value, without time-of-day and without time zone.
LocalDate start = LocalDate.of( 2016 , 1 , 1 ) ;
LocalDate stop = LocalDate.of( 2016 , 1 , 23 ) ;
To get the current date, specify a time zone. For any given moment, today’s date varies by time zone. For example, a new day dawns earlier in Paris than in Montréal.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
We can use the isEqual, isBefore, and isAfter methods to compare. In date-time work we commonly use the Half-Open approach where the beginning of a span of time is inclusive while the ending is exclusive.
List<LocalDate> localDates = new ArrayList<>();
LocalDate localDate = start;
while ( localDate.isBefore( stop ) ) {
localDates.add( localDate );
// Set up the next loop.
localDate = localDate.plusDays( 1 );
}
LocalDate::datesUntil
You can obtain a stream of LocalDate objects.
Stream< LocalDate > dates = start.datesUntil( stop ) ;
dates.forEach( System.out::println ) ;
LocalDateRange
If doing much of this work, add the ThreeTen-Extra library to your project. This gives you the LocalDateRange class to represent your pair of start and stop LocalDate objects.
Instant (date-time)
If you have old java.util.Date objects, which represent both a date and a time, convert to the Instant class. An Instant is a moment on the timeline in UTC.
Instant startInstant = juDate_Start.toInstant();
Instant stopInstant = juDate_Stop.toInstant();
From those Instant objects, get LocalDate objects by:
Applying the time zone that makes sense for your context to get ZonedDateTime object. This object is the very same moment on the timeline as the Instant but with a specific time zone assigned.
Convert the ZonedDateTime to a LocalDate.
We must apply a time zone as a date only has meaning within the context of a time zone. As we said above, for any given moment the date varies around the world.
Example code.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate start = ZonedDateTime.ofInstant( startInstant , zoneId ).toLocalDate();
LocalDate stop = ZonedDateTime.ofInstant( stopInstant , zoneId ).toLocalDate();
You can use joda-time.
Days.daysBetween(fromDate, toDate);
Found at joda-time homepage.
similar question in stackoverflow with some good answers.
Look at the Calendar API, particularly Calendar.add().

Categories