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() ) ;
Related
//[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
For a span of time running from one date to another date, how to get the number of calendar months containing one or more days of my span?
So for example:
2016-01-23/2016-01-23 = 1 calendar month (January)
2016-01-31/2016-02-01 = 2 calendar months (January, February)
2016-01-23/2016-02-28 = 2 calendar months (January, February)
2016-01-15/2016-03-15 = 3 calendar months (January, February, March)
2016-01-15/2017-03-15 = 15 calendar months (Jan-Dec of 2016 plus January, February, March of 2017)
I do not define a month as “30 days”. I am asking about calendar months, January-December.
Similar to this Question but that asks about PHP/MySQL.
Calculate the "epoch" month of both dates, then subtract them and add 1.
Using LocalDate like in the other answer, an epochMonth() helper method makes it easy:
private static int monthsTouched(LocalDate fromDate, LocalDate toDate) {
return epochMonth(toDate) - epochMonth(fromDate) + 1;
}
private static int epochMonth(LocalDate date) {
return date.getYear() * 12 + date.getMonthValue();
}
Like the results in the question, both dates are inclusive.
Note: Validation skipped for brevity, e.g. what is result if fromDate > toDate?
Test
public static void main(String[] args) {
test("2016-01-23", "2016-01-23");
test("2016-01-31", "2016-02-01");
test("2016-01-23", "2016-02-28");
test("2016-01-15", "2016-03-15");
test("2016-01-15", "2017-03-15");
}
private static void test(String fromDate, String toDate) {
System.out.println(monthsTouched(LocalDate.parse(fromDate), LocalDate.parse(toDate)));
}
Output (matches results from question)
1
2
2
3
15
Use ChronoField.PROLEPTIC_MONTH, which returns a count of months from year zero:
import static java.time.temporal.ChronoField.PROLEPTIC_MONTH;
long monthsTouched = date2.getLong(PROLEPTIC_MONTH) - date1.getLong(PROLEPTIC_MONTH) + 1;
Adjust the start and end dates
The key is to adjust your dates.
Move the starting date to the first of the month
Move the ending date to the first of the following month
We move the ending to the next month after because the Half-Open approach is commonly used when considering spans of time. Half-Open means the beginning is inclusive while the ending is exclusive. So lunch hour runs from 12:00 to 13:00 but does not include the 61st minute of 1 PM. A week runs from Monday to Monday, for seven days not including that second Monday.
So a span running from the first of January to the first of March is two months rather than three because we run up to, but do not include, that last date, the first of March.
java.time
The java.time classes built into Java 8 and later make easier work of this.
For date-only values, without a time-of-day and without a time zone, use the LocalDate class.
LocalDate start = LocalDate.parse( "2016-01-31" );
LocalDate stop = LocalDate.parse( "2016-02-01" );
To adjust, use a TemporalAdjuster. Implementations can be found in the TemporalAdjusters class (note the plural 's'). We need firstDayOfMonth and firstDayOfNextMonth.
LocalDate startAdjusted = start.with( TemporalAdjusters.firstDayOfMonth() );
LocalDate stopAdjusted = stop.with( TemporalAdjusters.firstDayOfNextMonth() );
Now use the ChronoUnit class to calculate elapsed whole months.
long calendarMonthsTouched = ChronoUnit.MONTHS.between( startAdjusted , stopAdjusted );
span: 2016-01-31/2016-02-01
calendarMonthsTouched: 2
See this code live in IdeOne.com.
I'm currently trying to improve an aspect of a project of mine.
Users are allowed to do a specific task, but they must book a date in order to do it.
I'm trying to add some more realistic validation onto my date, so that the tasks can't be booked a year in advance, and only a few months.
Currently I'm only checking the year of the input and comparing it to the current year, so if they try to assign themselves a task on 31st of December, they will not be able to because any date they enter will roll over to the next year, and my validation prevents this.
How can I make it so it will check the amount of months, rather than the current year?
I am able to do this for the current year, I just get stuck when the year comes to december and the months roll into January again.
Edit:
Those looking for a way to fix this, go here: Calculating the difference between two Java date instances
Because the lengths of months are different, I would test the number of days. Here's a couple of utility methods that get the job done in one line:
// Tests if the end date is within so many days of the start date
public static boolean isWithinRange(int days, Date end, Date start) {
return TimeUnit.DAYS.convert(end.getTime() - start.getTime(), TimeUnit.MILLISECONDS) < days;
}
// Tests if the specified date is within so many days of today
public static boolean isWithinRange(int days, Date end) {
return isWithinRange(days, end, new Date());
}
Here I've used the TimeUnit class to do the calculation for me.
you can use your own method. Something like this
public boolean isLaterDay(Date date, Date reference) {
if (date.getYear () > reference.getYear ()) return true;
if (date.getYear () < reference.getYear ()) return false;
return (date.getMonth() > reference.getMonth());
}
Another way of doing this would be as follows.
boolean validDate(Calendar inputDate)
{
Calendar validationDate = Calendar.getInstance().add(Calendar.MONTH, numOfMonths);
return inputDate.before(validationDate);
}
You can do something like this to validate the time
private static final int MAX_MONTHS_IN_ADVANCE = 3;
public boolean isValidDate(Date date) {
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MONTH, MAX_MONTHS_IN_ADVANCE);
return date.before(calendar.getTime());
}
Using the Joda-Time library:
If ( dateTimeInQuestion.isBefore( DateTime.now().plusMonths(3) )
java.time
The modern way to do this work is with the java.time classes. These classes supplant the troublesome old legacy date-time classes.
LocalDate
The LocalDate class represents a date-only value without time-of-day and without time zone.
A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.
ZoneId z = ZoneId.of( “America/Montreal” );
LocalDate today = LocalDate.now( z );
Construct the date desired by the user.
LocalDate ld = LocalDate.of( 2016 , 12 , 31 );
Determine the boundaries, say six months ago and six months from now.
LocalDate past = today.minusMonths( 6 );
LocalDate future = today.plusMonths( 6 );
You can compare LocalDate objects with isBefore, isAfter, equals, and compareTo.
Let's test by asking if the user's date is equal to or later than the before boundary (in other words, not before) AND the user's date is before the future boundary. This comparison uses the Half-Open approach commonly used with date-time work. The beginning is inclusive while the ending is exclusive.
Boolean validDate = ( ( ! ld.isBefore( past) ) && ( ld.isBefore( future) ) );
Interval
If you often work with the spans of time, consider using the Interval class found in the ThreeTen-Extra project that adds onto the java.time classes. That class has handy methods such as contains, abuts, overlaps, and more.
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().
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();