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().
Related
I have a LocalDateTime object I want to get the last date of the month. So if the localDateTime points to today's date of 29th October. I want to convert it to 31st October Is there a clean and easy way to do it?
My Thoughts:
One way would be to get the month and then make a switch statement. But that would be the long and tedious approach. Not sure if there is an inbuilt method to do the same
Use YearMonth.atEndOfMonth
LocalDate date = LocalDate.now();
YearMonth month = YearMonth.from(date);
LocalDate end = month.atEndOfMonth();
import java.time.LocalDateTime;
import java.time.temporal.TemporalAdjusters;
public class Main {
public static void main(String args[]) {
LocalDateTime a = LocalDateTime.of(2021, 10, 29, 0, 0);
LocalDateTime b = a.with(TemporalAdjusters.lastDayOfMonth());
System.out.println(a);
System.out.println(b);
}
}
You asked:
How do I add the endTime of day to the localDateTime. I see an option called LocalTime.MAX but it adds trailing .99999
Do not use LocalDateTime if you are tracking moments, specific points on the timeline. That class lacks the context of a time zone or offset-from-UTC. For moments, use Instant, OffsetDateTime, or ZonedDateTime.
Represent an entire month with YearMonth.
You should not try to nail down the last moment of the month. That last moment is infinitely divisible. Generally, the best way to define a span of time is the Half-Open approach rather than Fully-Closed. In Half-Open, the beginning is inclusive while the ending is exclusive.
So a day starts with first moment of the day and runs up to, but does not include, the first moment of the next day. A month starts with the first moment of the first day of the month and runs up to, but does not include, the first moment of the first of the next month.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
YearMonth currentMonth = YearMonth.now( z ) ;
YearMonth followingMonth = currentMonth.plusMonths( 1 ) ;
ZonedDateTime start = currentMonth.atDay( 1 ).atStartOfDay( z ) ;
ZonedDateTime end = followingMonth.atDay( 1 ).atStartOfDay( z ) ;
To represent that span of time, add the ThreeTen-Extra library to your project. Use the Interval class with its handy comparison methods such as abuts, overlaps, and contains.
org.threeten.extra.Interval interval = Interval.of( start.toInstant() , end.toInstant() ) ;
//[Sat 2018-12-29 13:30:00 UTC]
final long startTs = 1546090200000L
//[Wed 2019-01-02 09:12:00 UTC]
final long endTs = 1546420320000L
Is there a way using LocalDateTime I can print all the days between these two times?
Ideal output would be:
2018-12-29
2018-12-30
2018-12-31
2019-01-01
2019-01-02
You can use LocalDateTime, for example:
LocalDateTime startLDT = LocalDateTime.ofInstant(Instant.ofEpochMilli(startTs), ZoneId.systemDefault());
LocalDateTime endLDT = LocalDateTime.ofInstant(Instant.ofEpochMilli(endTs), ZoneId.systemDefault());
while (startLDT.isBefore(endLDT)) {
System.out.println(startLDT.format(DateTimeFormatter.ISO_LOCAL_DATE));
startLDT = startLDT.plusDays(1);
}
This loop takes milliseconds and creates instances of LocalDateTime. Then at each iteration if earlier date is before later - it's printed in format yyyy-MM-dd and incremented by day.
tl;dr
First, consider the built-in solution shown in Answer by Ole V.V.
Add the ThreeTen-Extra library to your project, for the LocalDateRange class.
LocalDateRange
.of(
Instant
.ofEpochMilli( 1_546_090_200_000L )
.atZone(
ZoneId.of( "America/Toronto" )
)
.toLocalDate() ,
Instant
.ofEpochMilli( 1_546_420_320_000L )
.atZone(
ZoneId.of( "America/Toronto" )
)
.toLocalDate()
)
.stream()
.forEach(
System.out::println
)
;
2018-12-29
2018-12-30
2018-12-31
2019-01-01
org.threeten.extra.LocalDateRange
The excellent Answer by Ole V.V. is correct, and is likely to meet your needs.
But if you find yourself working often with these date ranges, then you might want to learn about the LocalDateRange class found in the ThreeTen-Extra library. This library adds functionality to the java.time classes built into Java.
As discussed in that other Answer, start by parsing your count of milliseconds since first moment of 1970 in UTC into moments represented as Instant objects.
//[Sat 2018-12-29 13:30:00 UTC]
final long startInput = 1_546_090_200_000L ;
//[Wed 2019-01-02 09:12:00 UTC]
final long stopInput = 1_546_420_320_000L ;
Instant startInstant = Instant.ofEpochMilli( startInput ) ;
Instant stopInstant = Instant.ofEpochMilli( stopInput ) ;
startInstant.toString() = 2018-12-29T13:30:00Z
stopInstant.toString() = 2019-01-02T09:12:00Z
Adjust those into the time zone by which you want to perceive the calendar. Remember, for any given moment, the date varies around the globe by time zone. A moment may be “tomorrow” in Tokyo Japan while simultaneously being “yesterday” in Toronto Canada.
ZoneId z = ZoneId.of( "Asia/Tokyo" ) ;
ZonedDateTime zdtStart = startInstant.atZone( z ) ; // Produce a `ZonedDateTime` object from the `Instant` by applying a `ZoneId`.
zdtStart.toString() = 2018-12-29T22:30+09:00[Asia/Tokyo]
zdtStop.toString() = 2019-01-02T18:12+09:00[Asia/Tokyo]
Extract the date-only portion, without the time-of-day and without the time zone, as LocalDate object.
LocalDate start = zdtStart.toLocalDate() ;
start.toString() = 2018-12-29
stop.toString() = 2019-01-02
Pass both the start and stop LocalDate objects to make a org.threeten.extra.LocalDateRange.
LocalDateRange dateRange = LocalDateRange.of( start , stop ) ;
dateRange.toString() = 2018-12-29/2019-01-02
This LocalDateRange class has many methods for comparisons including contains, encloses, abuts, and overlaps. But for our purpose here, we want to see all the dates in-between. This class can make a stream of LocalDate objects.
Stream < LocalDate > stream = dateRange.stream() ;
From here, use the same .forEach method call to loop as seen in that other Answer.
2018-12-29
2018-12-30
2018-12-31
2019-01-01
Half-open span-of-time
Handling a span-of-time is usually best done using the Half-Open approach where the beginning is inclusive while the ending is exclusive. If you want to use the code above but also want to include the ending date, just add a day: stop = stop.plusDays( 1 ) ;.
LocalDate::datesUntil ➙ stream
Since Java 9 you can use LocalDate.datesUntil() for iterating over a date interval.
//[Sat 2018-12-29 13:30:00 UTC]
final long startTs = 1_546_090_200_000L;
//[Wed 2019-01-02 09:12:00 UTC]
final long endTs = 1_546_420_320_000L;
LocalDate startDate = millisToLocalDate(startTs);
LocalDate endDate = millisToLocalDate(endTs);
startDate.datesUntil( endDate.plusDays(1) ) // Returns a stream.
.forEach( System.out::println ); // Iterates objects in the stream, passing each to `println` method.
Output from this snippet is:
2018-12-29
2018-12-30
2018-12-31
2019-01-01
2019-01-02
I am using the following auxiliary method for converting your counts of milliseconds to LocalDate. I seemed to understand that you wanted to use dates in UTC, so this is what the method does.
private static LocalDate millisToLocalDate(long millisSinceEpoch) {
return Instant.ofEpochMilli(millisSinceEpoch)
.atOffset(ZoneOffset.UTC)
.toLocalDate();
}
datesUntil returns a stream of the dates from start date inclusive to end date exclusive. Since you wanted the end date to be included, we needed to add one day to it before passing it to datesUntil.
Link: Documentation of LocalDate.datesUntil
I'm very new to Java. So please bear with me. I have 4 variables:
mode = prior|later|value;(can have either of these 3 values)
occurrence = 2
day = Wednesday
eta = 14:00
I'm trying to implement a method which will return a list date which is based on following criteria:
case 1 : (mode=prior,occurence=2,day=wednesday,eta=14:00)
should return dates of first 2 wednesdays of the next month from current month.
output = [Wed Aug 01 14:00:00 2018, Wed Aug 08 14:00:00 2018]
case 2 : (mode=later,occurence=2,day=wednesday,eta=14:00)
should return dates of last 2 wednesdays of the next month from current month.
output = [Wed Aug 22 14:00:00 2018, Wed Aug 29 14:00:00 2018]
case 3 : (mode=value,occurence=3,day=wednesday,eta=14:00)
should return date of 3rd wednesday of the next month from current month.
output = [Wed Aug 15 14:00:00 2018, Wed Aug 29 14:00:00 2018]
This is what I've done so far,
public static List<Date> getDates(Calendar c, String mode, int occurrence, int dayNo, String eta) {
List<Date> dates = new ArrayList<Date>();
switch(mode) {
case "value": {
String[] times = eta.split(":");
c.set(Calendar.DAY_OF_WEEK, dayNo);
c.set(Calendar.DAY_OF_WEEK_IN_MONTH, occurrence);
c.set(Calendar.MONTH, Calendar.JULY + 1);
c.set(Calendar.YEAR, 2018);
c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(times[0]));
c.set(Calendar.MINUTE, Integer.parseInt(times[1]));
dates.add(c.getTime());
}
}
return dates;
}
Is there a better way of doing what I've done. Also can somebody please help me with implementing the cases 1 and 2 ?
Avoid legacy date-time classes
You are using terrible old date-time classes that were supplanted years ago by the java.time classes.
In particular, the Calendar class (well, actually, GregorianCalendar) is replaced by ZonedDateTime.
Use types (classes)
Use smart objects rather than dumb strings, where feasible. Using appropriate types makes your code more self-documenting, ensures valid values, provides for type-safety, and lets the compiler catch your typos.
In your case, Java already provides types for most of your data. You can make your own type for the “mode”.
The enum facility in Java is much more powerful and flexible than typically seen in other languages. See Oracle Tutorial to learn more. But the basics are simple, as seen here:
public enum Mode {
PRIOR ,
LATER ,
VALUE
}
For day-of-week, use the DayOfWeek enum, pre-defining seven objects, one for each day of the week. For example, DayOfWeek.WEDNESDAY.
For time-of-day, use LocalTime.
LocalTime lt = LocalTime.of( 14 , 0 ) ;
For the current month, use YearMonth class.
Determining the current year-month means determining the current date. Determining the current date requires a time zone. For any given moment, the date varies around the globe by zone.
ZoneId z = ZoneId.of( "Africa/Tunis" ) ; // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z ) ;
If you have a LocalDate, you can determine the year-month for it.
YearMonth ym = YearMonth.from( myLocalDate ) ;
I suggest having the calling method determine the YearMonth rather than make this method jump through extra hoops. A general design approach in OOP is to separate, or disentangle, responsibilities. This method we are writing should be concerned with its own needs (a year-month value) and should not have to care about how the calling method arrives at its desired year-month whether that be from current date or current month or last month, etc.
Lastly, if your goal is to get a moment in time (a date with a time-of-day), then you must also specify a time zone. A date+time without the context of a time zone (or offset-from-UTC) has no real meaning.
Specify a proper time zone name in the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).
So, putting this all together, your method signature could look like this:
public static List< ZonedDateTime > getDates(
YearMonth ym ,
Mode mode ,
int occurrences ,
DayOfWeek dow ,
LocalTime lt ,
ZoneId z
) { …
Logic
The solution to your first two cases, Mode.PRIOR and Mode.LATER, is the use of the TemporalAdjuster interface. Specifically, the implementations found in TemporalAdjusters class can determine the “nth” weekday-of-month such as first Wednesday. Even more specifically:
firstInMonth( DayOfWeek dayOfWeek )
lastInMonth( DayOfWeek dayOfWeek )
The main idea here is to start with the first (or last) day-of-week in the month. Then work our way down (up) through the month, week-by-week, adding (subtracting) a week at a time. Repeat for our limit of integer occurrences.
We can do a switch on our Mode enum, as discussed here. Minor point: I would prefer to use Mode.PRIOR syntax rather than just PRIOR, for clarity. However, an obscure technicality in Java forbids that syntax in a switch. So, case PRIOR: not case Mode.PRIOR:, as shown further down in sample code.
We collect our resulting ZonedDateTime objects in a List named moments.
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
Let’s look at the logic for each of our three modes.
Mode.PRIOR
Get the first day-of-week of the month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
Work our way down through the month, adding a week at a time.
We might exceed the bounds of the month, going into the following month. So check the YearMonth to see if it is the same as when when started.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Mode.LATER
This case uses the same logic as above, except we start at the bottom of the month and work our way up. Get the last day-of-week of month, then subtract a week at a time.
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Because we are going backwards through time, our collection of moments is in reverse chronological order. So, we need to sort to present these in chronological order.
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
Mode.VALUE
The last case is the simplest: Get the nth day-of-week in the month. That is simply a one-liner.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
Do the usual, make a ZonedDateTime.
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
Verify the month, as the documentation seems to be saying that exceeding the limits of the month takes us into the next month. In such a case, our logic omits the date from our list. So we will be returning moments as an empty list. This means the calling method should check for the list having elements, as it may be empty.
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
Let’s see all the code put together.
// Simulate arguments passed.
LocalTime lt = LocalTime.of( 14 , 0 );
ZoneId z = ZoneId.of( "Africa/Tunis" ); // Or "America/Chicago", etc.
YearMonth ym = YearMonth.now( z );
DayOfWeek dow = DayOfWeek.WEDNESDAY;
Mode mode = Mode.PRIOR ; // Mode.PRIOR, Mode.LATER, Mode.VALUE.
int occurrences = 3; // TODO: Add code to verify this value is in range of 1-5, not zero, not >5.
// Logic
int initialCapacity = 5; // Max five weeks in any month.
List< ZonedDateTime > moments = new ArrayList<>( initialCapacity );
switch ( mode ) {
case PRIOR:
// Start with first day-of-week in month.
LocalDate firstDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.firstInMonth( dow ) );
// Work our way down through the month, adding a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = firstDowOfMonth.plusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
break;
case LATER:
// Start with last day-of-week in month.
LocalDate lastDowOfMonth = ym.atDay( 1 ).with( TemporalAdjusters.lastInMonth( dow ) );
// Work our way up through the month, subtracting a week at a time.
for ( int i = 0 ; i < occurrences ; i++ ) {
LocalDate ld = lastDowOfMonth.minusWeeks( i );
ZonedDateTime zdt = ZonedDateTime.of( ld , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
}
Collections.sort( moments ); // If you want the list to be in chronological order, sort. Otherwise in reverse chronological order for this `Mode.LATER`.
break;
case VALUE:
// Get the nth day-of-week in month.
LocalDate nthDowInMonth = ym.atDay( 1 ).with( TemporalAdjusters.dayOfWeekInMonth( occurrences , dow ) );
ZonedDateTime zdt = ZonedDateTime.of( nthDowInMonth , lt , z );
if ( YearMonth.from( zdt ).equals( ym ) ) { // If in same month…
moments.add( zdt );
}
break;
default: // Defensive programming, testing for unexpected values.
System.out.println( "ERROR - should not be able to reach this point. Unexpected `Mode` enum value." );
break;
}
// return `moments` list from your method.
System.out.println( "moments:\n" + moments );
Note that the specified time-of-day on a particular date in our specified time zone may not be valid. For example, during a cutover in Daylight Saving Time (DST). If so, the ZonedDateTime class adjusts as needed. Be sure to read the documentation to make sure you understand and agree to its adjustment algorithm.
About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?
Java SE 8, Java SE 9, Java SE 10, and later
Built-in.
Part of the standard Java API with a bundled implementation.
Java 9 adds some minor features and fixes.
Java SE 6 and Java SE 7
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
Android
Later versions of Android bundle implementations of the java.time classes.
For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.
So as I understand your question I wrote some code for example. I could not understand the "value" option. Desired output and explanation of method is not obvious for me. If you explain it I could edit the answer.
public class Main {
public static void main(String[] args) {
for (String s : findOccurence("prior", DayOfWeek.WEDNESDAY, 2, "14:00")){
System.out.println(s);
}
}
public static String[] findOccurence(String mode, DayOfWeek day, int occurrence, String eta) {
LocalDate now = LocalDate.now();
LocalDate start = LocalDate.of(now.getYear(), now.getMonth().plus(1), 1);
LocalDate finish = start.plusDays(start.lengthOfMonth());
List<LocalDate> dates = Stream.iterate(start, date -> date.plusDays(1))
.limit(ChronoUnit.DAYS.between(start, finish))
.filter(d -> d.getDayOfWeek() == day)
.collect(Collectors.toList());
String[] formattedEta = eta.split(":");
if (occurrence > dates.size()) {
throw new IndexOutOfBoundsException();
}
if (mode.equalsIgnoreCase("value")) {
}
else if (mode.equalsIgnoreCase("later")) {
dates = Lists.reverse(dates);
}
//later and prior shares common logic
return dates.stream()
.limit(occurrence)
.map(d -> day.toString()
+ " "
+ start.getMonth().name()
+ " "
+ d.getDayOfMonth()
+ " "
+ LocalTime.of(Integer.valueOf(formattedEta[0]), Integer.valueOf(formattedEta[1]), 0)
+ " "
+ start.getYear())
.collect(Collectors.toList())
.toArray(new String[occurrence]);
}
}
Output is :
WEDNESDAY AUGUST 1 14:00 2018
WEDNESDAY AUGUST 8 14:00 2018
I have a date in dd/mm (15/07) format, I need to add a single day to this date, so it becomes 16/07.
How can I do this in the easiest way in java?
You can use Calendar.
String dt = "15-07-2016";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1); // number of days to add
dt = sdf.format(c.getTime());
You can do this:
public String addDay(String date) {
String[] dateSplit = date.split("/");
String day = "" + (Integer.parseInt(dateSplit[0]) + 1);
return day + "/" + dateSplit[1];
}
But this isn't really a nice solution, because this doesn't handle month or year swaps (This you can add by yourself using the % operator)
Or you use the SimpleDateFormat like here: How can I increment a date by one day in Java?
java.time
The Answer by Goel is correct but outmoded.
The java.time framework is built into Java 8 and later. These classes supplant the old troublesome date-time classes such as java.util.Date, .Calendar, & java.text.SimpleDateFormat.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations.
Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP.
MonthDay
The java.time classes include the MonthDay class to represent a month+day without year and without time zone.
String input = "15/07";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern( "dd/MM" );
MonthDay monthDay = MonthDay.parse( input , formatter );
Cannot increment February 28
As commented by Tom, you cannot reliably increment February 28. In most years you would get March 1 but in leap years you get February 29. This is why the YearMonth class lacks any addDays method.
So you need to (a) assume/supply a year, (b) refuse to increment the one day of February 28, or (c) arbitrarily increment to March 1 from February 28 to ignore any possible 29th.
Let's look at the first option, supplying a year.
To get the current year we need the current date. To get the current date, specify a time zone. For any given moment, the date varies around the globe by zone.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
int year = today.getYear();
We can apply that year number to change our YearMonth into a LocalDate. From there the LocalDate::plusDays method increments to the next day. From the resulting instance of LocalDate we extract a YearMonth object.
LocalDate ld = monthYear.atYear( year );
LocalDate nextDay = ld.plusDays( 1 );
YearMonth ymNextDay = MonthDay.from( nextDay );
My API allows library client to pass Date:
method(java.util.Date date)
Working with Joda-Time, from this date I would like to extract the month and iterate over all days this month contains.
Now, the passed date is usually new Date() - meaning current instant. My problem actually is setting the new DateMidnight(jdkDate) instance to be at the start of the month.
Could someone please demonstrates this use case with Joda-Time?
Midnight at the start of the first day of the current month is given by:
// first midnight in this month
DateMidnight first = new DateMidnight().withDayOfMonth(1);
// last midnight in this month
DateMidnight last = first.plusMonths(1).minusDays(1);
If starting from a java.util.Date, a different DateMidnight constructor is used:
// first midnight in java.util.Date's month
DateMidnight first = new DateMidnight( date ).withDayOfMonth(1);
Joda Time java doc - https://www.joda.org/joda-time/apidocs/overview-summary.html
An alternative way (without taking DateMidnight into account) to get the first day of the month would be to use:
DateTime firstDayOfMonth = new DateTime().dayOfMonth().withMinimumValue();
First Moment Of The Day
The answer by ngeek is correct, but fails to put the time to the first moment of the day. To adjust the time, append a call to withTimeAtStartOfDay.
// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so.
org.joda.time.DateTime startOfThisMonth = new org.joda.time.DateTime().dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
org.joda.time.DateTime startofNextMonth = startOfThisMonth.plusMonths( 1 ).dayOfMonth().withMinimumValue().withTimeAtStartOfDay();
System.out.println( "startOfThisMonth: " + startOfThisMonth );
System.out.println( "startofNextMonth: " + startofNextMonth );
When run in Seattle US…
startOfThisMonth: 2013-11-01T00:00:00.000-07:00
startofNextMonth: 2013-12-01T00:00:00.000-08:00
Note the difference in those two lines of console output: -7 vs -8 because of Daylight Saving Time.
Generally one should always specify the time zone rather than rely on default. Omitted here for simplicity. One should add a line like this, and pass the time zone object to the constructors used in example above.
// Time Zone list: http://joda-time.sourceforge.net/timezones.html (Possibly out-dated, read note on that page)
// UTC time zone (no offset) has a constant, so no need to construct: org.joda.time.DateTimeZone.UTC
org.joda.time.DateTimeZone kolkataTimeZone = org.joda.time.DateTimeZone.forID( "Asia/Kolkata" );
java.time
The above is correct but outdated. The Joda-Time library is now supplanted by the java.time framework built into Java 8 and later.
The LocalDate represents a date-only value without time-of-day and without time zone. A time zone is crucial in determine a date. For any given moment the date varies by zone around the globe.
ZoneId zoneId = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( zoneId );
Use one of the TemporalAdjusters to get first of month.
LocalDate firstOfMonth = today.with( TemporalAdjusters.firstDayOfMonth() );
The LocalDate can generate a ZonedDateTime that represents the first moment of the day.
ZonedDateTime firstMomentOfCurrentMonth = firstOfMonth.atStartOfDay( zoneId );
Oh, I did not see that this was about jodatime. Anyway:
Calendar c = Calendar.getInstance();
c.setTime(date);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
int min = c.getActualMinimum(Calendar.DAY_OF_MONTH);
int max = c.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = min; i <= max; i++) {
c.set(Calendar.DAY_OF_MONTH, i);
System.out.println(c.getTime());
}
Or using commons-lang:
Date min = DateUtils.truncate(date, Calendar.MONTH);
Date max = DateUtils.addMonths(min, 1);
for (Date cur = min; cur.before(max); cur = DateUtils.addDays(cur, 1)) {
System.out.println(cur);
}
DateMidnight is now deprecated. Instead you can do:
LocalDate firstOfMonth = new LocalDate(date).withDayOfMonth(1);
LocalDate lastOfMonth = firstOfMonth.plusMonths(1).minusDays(1);
If you know the time zone use new LocalDate(date, timeZone) instead for greater accuracy.
You can also do .dayOfMonth().withMinimumValue() instead of .withDayOfMonth(1)
EDIT:
This will give you 12/1/YYYY 00:00 and 12/31/YYYY 00:00. If you rather the last of the month be actually the first of the next month (because you are doing a between clause), then remove the minusDays(1) from the lastOfMonth calculation
You can get Start date and end date of month using this:
DateTime monthStartDate = new DateTime().dayOfMonth().withMinimumValue();
DateTime monthEndDate = new DateTime().dayOfMonth().withMaximumValue();