Am trying to get a LocalDate instance for each Year in a Period. For example, for this:
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(2011, Month.DECEMBER, 19);
Period period = Period.between(birthday, today);
I want 2012-12-19, 2013-12-19, 2014-12-19, 2015-12-19.
Given the methods of Period this isn't possible. Is there a way around this? Is it possible using another method?
Care must be taken when looping over dates. The "obvious" solution does not work properly. The solution of Soorapadman will work fine for the date given (the 19th December), but fail if the start date is the 29th February. This is because 1 year later is the 28th, and the date will never return to the 29th February, even when another leap year occurs.
Note that this problem is more pronounced for month addition. A start date of the 31st January will return the sequence 28th February (or 29th), then 28th March 28th April and so on. This is unlikely to be the desired output, which is probably the last date of each month.
The correct strategy is as follows:
public List<LocalDate> datesBetween(LocalDate start, LocalDate end, Period period);
List<LocalDate> list = new ArrayList<>();
int multiplier = 1;
LocalDate current = start;
while (!current.isAfter(end)) {
current = start.plus(period.multipliedBy(multiplier);
list.add(current);
multiplier++;
}
return list;
}
Note how the strategy adds an increasing period to the same start date. The start date is never altered. Using the same start date is critical to retain the correct month length of that date.
You can try like this using Java 8;
LocalDate start = LocalDate.of(2011, Month.DECEMBER, 19);
LocalDate end = LocalDate.now();
while (!start.isAfter(end)) {
System.out.println(start);
start = start.plusYears(1);
}
}
Related
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DATE));
int months = 1;
calender.add(Calendar.MONTH, months );
String time = sdf .format(calender .getTime());
System.out.println(time);
Since current month is April and last date is 2020-04-30
Next month last date I should get 2020-05-31
but I am getting last date as 2020-05-30
Any thing am i doing wrong ?
java.time
I recommend that you use java.time, the modern Java date and time API, for your date work. It’s much nicer to work with than the old classes Calendar and SimpleDateFormat.
LocalDate endOfNextMonth =
YearMonth // Represent an entire month in a particular year.
.now(ZoneId.of("Europe/Volgograd")) // Capture the current year-month as seen in a particular time zone. Returns a `YearMonth` object.
.plusMonths(1) // Move to the next month. Returns another `YearMonth` object.
.atEndOfMonth(); // Determine the last day of that year-month. Returns a `LocalDate` object.
String time = endOfNextMonth.toString(); // Represent the content of the `LocalDate` object by generating text in standard ISO 8601 format.
System.out.println("Last day of next month: " + time);
Output when running today:
Last day of next month: 2020-05-31
A YearMonth, as the name maybe says, is a year and month without day of month. It has an atEndOfMonth method that conveniently gives us the last day of the month as a LocalDate. A LocalDate is a date without time of day, so what we need here. And its toString method conveniently gives the format that you wanted (it’s ISO 8601).
Depending on the reason why you want the last day of another month there are a couple of other approaches you may consider. If you need to handle date ranges that always start and end on month boundaries, you may either:
Represent your range as a range of YearMonth objects. Would this free you from knowing the last day of the month altogether?
Represent the end of your range as the first of the following month exclusive. Doing math on the 1st of each month is simpler since it is always day 1 regardless of the length of the month.
What went wrong in your code?
No matter if using Calendar, LocalDate or some other class you need to do things in the opposite order: first add one month, then find the end of the month. As you know, months have different lengths, so the important part is getting the end of that month where you want to get the last day. Putting it the other way: setting either a LocalDate or a Calendar to the last day of the month correctly sets it to the last day of the month in qustion but does not instruct it to stay at the last day of the month after subsequent changes to its value, such as adding a month. If you add a month to April 29, you get May 29. If you add a month to April 30, you get May 30. Here it doesn’t matter that 30 is the last day of April while 30 is not the last day of May.
Links
Oracle tutorial: Date Time explaining how to use java.time.
Wikipedia article: ISO 8601
You'd better use LocalDate like this:
LocalDate now = LocalDate.now();
LocalDate lastDay = now.withDayOfMonth(now.lengthOfMonth());
LocalDate nextMonth = lastDay.plusMonths(1);
Don't use deprecated classes from java.util.*.
Use classes from java.time.*.
Example with LocalDate :
public class Testing {
public static void main(String args[]) {
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate date = LocalDate.now();
int months = 1;
date = date.plusMonths(months);
date = date.withDayOfMonth(date.lengthOfMonth());
System.out.println(date.format(dateTimeFormatter));
}
}
Output :
2020-05-31
Example with Calendar :
public class Testing {
public static void main(String args[]) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar calender = Calendar.getInstance();
int months = 1;
calender.add(Calendar.MONTH, months);
calender.set(Calendar.DAY_OF_MONTH, calender.getActualMaximum(Calendar.DAY_OF_MONTH));
String time = sdf.format(calender.getTime());
System.out.println(time);
}
}
Output :
2020-05-31
I need to get Instant time from week number of year. Now I'm using old Calendar API to calculate time:
int week = 1; // week of year
final Calendar cal = new GregorianCalendar();
cal.set(0, 1, 0, 0, 0, 0); // reset calendar
cal.set(Calendar.YEAR, Year.now().getValue());
cal.set(Calendar.WEEK_OF_YEAR, week);
cal.setTimeZone(TimeZone.getTimeZone(ZoneOffset.UTC));
final Instant start = cal.getTime().toInstant();
final Instant end = start.plus(Period.ofWeeks(1));
Is it possible to get Instant from week of year using new Java time API (java.time package)?
WeekFields wf = WeekFields.of(Locale.getDefault());
int week = 1; // week of year
LocalDate startDate = LocalDate.now(ZoneOffset.UTC)
.with(wf.weekOfWeekBasedYear(), week)
.with(wf.dayOfWeek(), 1);
Instant startInstant = startDate.atStartOfDay(ZoneOffset.UTC).toInstant();
LocalDate endDate = startDate.plusWeeks(1);
Instant endInstant = endDate.atStartOfDay(ZoneOffset.UTC).toInstant();
System.out.println("" + startInstant + " - " + endInstant);
My locale uses ISO week numbers. The output here was:
2019-12-29T00:00:00Z - 2020-01-05T00:00:00Z
If you want ISO weeks independently of the locale, set wf to WeekFields.ISO. If you want some other week numbering scheme, set wf accordingly.
In case any other readers were wondering, Kirill is defining the end of the week as the first moment of the following week. This is recommended. It’s known as using half-open intervals for time intervals.
I also agree with the question that one should clearly prefer using java.time for this task rather than Calendar. Calendar is poorly designed and long outdated, and I believe that the code using java.time is clearer to read.
Furthermore, the code in the question using Calendar doesn’t set the day to the first day of the week, so will not give you that day. And while I haven’t tested, I suspect that the code will sometimes produce unexpected results around New Year.
My code using WeekFields from java.time will stay within the current week-based year, which is not the same as the calendar year. For example, if I had run it on December 30, 2019, it would still have given med week 1 of 2020 because we were already in that week.
You could adjust the week using the following methods:
LocalDateTime localDateTime = LocalDateTime.of(2020, 1, 1, 0, 0);
System.out.println(localDateTime); //2020-01-01T00:00
localDateTime = localDateTime.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 2);
System.out.println(localDateTime); //2020-01-08T00:00
localDateTime = localDateTime.plusWeeks(10);
System.out.println(localDateTime); //2020-03-18T00:00
and to parse it to Instant depends on what class from the API you are using:
LocalDateTime.now().toInstant(ZoneOffset.of("+04:00"));
ZonedDateTime.now().toInstant();
The LocalDateTime doest not have a Zone, so you must a provide a ZoneOffset to parse it to a Instant.
In order to set the month you can use this lambda expression:
LocalDate.now().with(temporal
-> temporal.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 1l)
);
Now get instant is easy:
LocalDate localDate = LocalDate.now().with(temporal
-> temporal.with(ChronoField.ALIGNED_WEEK_OF_YEAR, 1l)
);
Instant instant = localDate.atStartOfDay().atZone(ZoneId.systemDefault()).toInstant();
If you don't want cto change time, then you can use this instead of last line:
Instant instant = localDate.atTime(LocalTime.now()).atZone(ZoneId.systemDefault()).toInstant();
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 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).
I have two DateTime variables: DateTime begin, DateTime end, now I want to "walk trough" the period between these dates and determine date by date if that specific date is a monday, tuesday, etc... (Giving the days a number from 1 to 7).
I can't seen to figure out how to walk through the period date by date...
Thanks in advance.
Something along the lines;
for (DateTime current = begin; current.isBefore(end); current = current.plusDays(1)) {
// do stuff
}
This should work i guess
ArrayList<Integer> days = new Arraylist<Integer>();
while(begin.isBefore(end)){
days.add(begin.getDayOfWeek());
begin.plusDays(1);
}