In my application I must often check if given hour as ZonedDateTime is the additional hour due to DST. Consider the transition from Summer time to Winter time
1) *date* 01:00:00+02:00
2) *date* 02:00:00+02:00
3) *date* 02:00:00+01:00
4) *date* 03:00:00+01:00
I want to write the simplest possible function isExtraHour(ZonedDate time) that for 1,2,4 will return false and for 3 case will return true Of course using the Java8 Time API.
This is what I would use:
public boolean isExtraHour(final ZonedDateTime time) {
return time.getZone().getRules().getValidOffsets(time.toLocalDateTime()).size() > 1;
}
Note that it returns true for the whole hour of overlap, which I assume is the answer you need.
The easiest I got so far is:
public boolean isExtraHour(final ZonedDateTime time) {
final ZoneOffsetTransition dayTransition = time.getZone().getRules()
.getTransition(time.toLocalDateTime());
return dayTransition != null && dayTransition.isOverlap() && dayTransition.getInstant()
.equals(time.toInstant());
}
Related
I've got a problem comparing.
The second "if" is always fulfilled even if the second condition of the "if" is false.
First, I had to use Timestamp.valueOf so I could transform LocalDateTime to Date ("a" is a type of data "Date"). What i want to do is compare if the current time is greater than a predetermined time (a.getFinFecha()), if so, return 1. If the current time is greater or equal to the predetermined time (a.getFinFecha()) less seven days and is lower than the pretermined date, I want to return 2. Else (which means if the current time is lower than a.getFinFecha() and lower than a.getFinFecha() less 7 days) return 3. The object I'm passing is lower than the pretermined date less 7 days and it returns 2. Never returns 3.
if (java.sql.Timestamp.valueOf(LocalDateTime.now()).compareTo(a.getFinFecha()) > 0) {
return 1;
} else if (java.sql.Timestamp.valueOf(LocalDateTime.now()).getDate() >= (a.getFinFecha().getDate() - 7) && java.sql.Timestamp.valueOf(LocalDateTime.now()).compareTo(a.getFinFecha()) <= 0) {
return 2;
} else {
return 3;
}
I had to use Timestamp.valueOf so I could transform LocalDateTime to Date
No, you hadn't and you shoudn't. Avoid using deprecated methods like getDate() and make use of the java.time API. The simplest solution could be to convert the Date returned by a.getFinFecha() to LocalDateTime and compare according to your requierments:
private int yourMethod() {
Instant instant = Instant.ofEpochMilli(a.getFinFecha().getTime());
LocalDateTime finFecha = LocalDateTime.ofInstant(instant, ZoneOffset.UTC); // or use appropriate offset for your use case
if (LocalDateTime.now().isAfter(finFecha)) {
return 1;
} else if (LocalDateTime.now().isAfter(finFecha.minusDays(7))) {
return 2;
} else {
return 3;
}
}
This question already has answers here:
Determine Whether Two Date Ranges Overlap
(39 answers)
Closed 2 years ago.
In database I have
eventName: "TestEvent",
startDate : ISODate("2018-11-07T13:24:03.124Z"),
endDate: ISODate("2020-11-07T13:24:03.124Z")
I am setting two dates fromDate and toDate,
for example
fromDate:01/01/2020
toDate:01/01/2021
I want to check if the event is within this range I entered.
I tried like this but the results are not correct.
if ((fromDate.after(s.getStartDate()) && toDate.before(s.getEndDate()))
|| s.getStartDate().equals(fromDate) || s.getEndDate().equals(toDate))
Please help me, I am using utils.Date in my project.
If i use :
fromDate:08/08/2017
toDate: 09/09/2022
or
fromDate:08/08/2019
toDate: 09/09/2019
it should return this event in this range.
If i use :
fromDate:01/01/2000
toDate: 01/01/2001
this event should not be in the results
You are trying to check whether two (time) intervals overlap. A simple way to look at it is to say that overlap occurs if (and only if) one or more of the start and end of the 1st interval is within the 2nd, or vice-versa. Test it with:
boolean contains(Date d, Date startInclusive, Date endExclusive) {
return d.compareTo(startInclusive) >= 0 && d.before(endExclusive);
}
yielding
boolean intersects(Date from, Date to, Date start, Date end) {
return contains(from, start, end) || // s <= f < e (from inside start-end)
contains(to, start, end) || // s <= t < e (to inside start-end)
contains(start, from, to); // f <= s < t (from-to fully contains start-end)
}
Note that this is much more readable than writing the (equivalent) boolean expression.
I also fully agree with #deHaar's comment: use classes in java.time instead of java.util.Date. There are many problems with java.util.Date, which is deprecated as of Java 8.
Make sure when you compare the dates they are in the same format.
I think there is an issue with condition and it should look more like :
Date startDate = s.getStartDate();
Date endDate = s.getEndDate();
if ((fromDate.before(startDate) || fromDate.equals(startDate)) &&
(toDate.after(endDate) || toDate.equals(endDate)){
// do you magic here
}
I'm trying to parse a date from a String.
I'd like to identify the case where due to daylight savings, the clocks go back and a time is effectively "repeated" in the same day.
For example, based on UK daylight savings time, the clocks go back an hour at 2AM, 27/10/2019.
Therefore:
12:30AM 27/10/2019,
One hour later - 1:30AM 27/10/2019,
One hour later - 1:30AM 27/10/2019 (as at 2AM, we went back an hour),
One hour later - 2:30AM 27/10/2019.
Therefore "1:30AM 27/10/2019" is referring to two different times. This is the case I am trying to identify.
I have created the following, but it uses Date & Calendar classes, and some deprecated methods. I'd like to do this using the new java.time functionality - and I'm hoping there's an easier solution.
public static boolean isDateRepeatedDST(final Date date, TimeZone timeZone) {
if (timeZone == null) {
// If not specified, use system default
timeZone = TimeZone.getDefault();
}
if (timeZone.useDaylightTime()) {
// Initially, add the DST offset to supplied date
// Handling the case where this is the first occurrence
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MILLISECOND, timeZone.getDSTSavings());
// And determine if they are now logically equivalent
if (date.toLocaleString().equals(calendar.getTime().toLocaleString())) {
return true;
} else {
// Then try subtracting the DST offset
// Handling the second occurrence
calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.MILLISECOND, -timeZone.getDSTSavings());
if (date.toLocaleString().equals(calendar.getTime().toLocaleString())) {
return true;
}
}
}
// Otherwise
return false;
}
ZoneId zone = ZoneId.of("Europe/London");
ZonedDateTime dateTime = ZonedDateTime.of(2019, 10, 27, 0, 30, 0, 0, zone);
for (int i = 0; i < 4; i++) {
System.out.println(dateTime);
dateTime = dateTime.plusHours(1);
}
Output:
2019-10-27T00:30+01:00[Europe/London]
2019-10-27T01:30+01:00[Europe/London]
2019-10-27T01:30Z[Europe/London]
2019-10-27T02:30Z[Europe/London]
You can see that the time 01:30 is repeated and that the offset is different the two times it comes.
If you want a test for whether a time is repeated:
public static boolean isDateRepeatedDST(ZonedDateTime dateTime) {
return ! dateTime.withEarlierOffsetAtOverlap().equals(dateTime.withLaterOffsetAtOverlap());
}
We can use it in the loop above if we modify the print statement:
System.out.format("%-37s %s%n", dateTime, isDateRepeatedDST(dateTime));
2019-10-27T00:30+01:00[Europe/London] false
2019-10-27T01:30+01:00[Europe/London] true
2019-10-27T01:30Z[Europe/London] true
2019-10-27T02:30Z[Europe/London] false
NOTE THIS IS NOT A DUPLICATE OF EITHER OF THE FOLLOWING
Calculating the difference between two Java date instances
calculate months between two dates in java [duplicate]
I have two dates:
Start date: "2016-08-31"
End date: "2016-11-30"
Its 91 days duration between the above two dates, I expected my code to return 3 months duration, but the below methods only returned 2 months. Does anyone have a better suggestion? Or do you guys think this is a bug in Java 8? 91 days the duration only return 2 months.
Thank you very much for the help.
Method 1:
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 2:
long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30"));
Method 3:
I tried to use Joda library instead of Java 8 APIs, it works. it loos will return 3, It looks like Java duration months calculation also used days value. But in my case, i cannot use the Joda at my project. So still looking for other solutions.
LocalDate dateBefore= LocalDate.parse("2016-08-31");
LocalDate dateAfter = LocalDate.parse("2016-11-30");
int months = Months.monthsBetween(dateBefore, dateAfter).getMonths();
System.out.println(months);
Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob. Simply set the days of both instance to the same value (the first day of the month)
Period diff = Period.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(diff); //P3M
Same with the other solution :
long monthsBetween = ChronoUnit.MONTHS.between(
LocalDate.parse("2016-08-31").withDayOfMonth(1),
LocalDate.parse("2016-11-30").withDayOfMonth(1));
System.out.println(monthsBetween); //3
Edit from #Olivier Grégoire comment:
Instead of using a LocalDate and set the day to the first of the month, we can use YearMonth that doesn't use the unit of days.
long monthsBetween = ChronoUnit.MONTHS.between(
YearMonth.from(LocalDate.parse("2016-08-31")),
YearMonth.from(LocalDate.parse("2016-11-30"))
)
System.out.println(monthsBetween); //3
Since Java8:
ChronoUnit.MONTHS.between(startDate, endDate);
//Backward compatible with older Java
public static int monthsBetween(Date d1, Date d2){
if(d2==null || d1==null){
return -1;//Error
}
Calendar m_calendar=Calendar.getInstance();
m_calendar.setTime(d1);
int nMonth1=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
m_calendar.setTime(d2);
int nMonth2=12*m_calendar.get(Calendar.YEAR)+m_calendar.get(Calendar.MONTH);
return java.lang.Math.abs(nMonth2-nMonth1);
}
The documentation of Period#between states the following:
The start date is included, but the end date is not.
Furthermore:
A month is considered if the end day-of-month is greater than or equal to the start day-of-month.
Your end day-of-month 30 is not greater than or equal to your start day-of-month 31, so a third month is not considered.
Note the parameter names:
public static Period between​(LocalDate startDateInclusive, LocalDate endDateExclusive)
To return 3 months, you can increment the endDateExclusive by a single day.
In case you want stick to java.time.Period API
As per java.time.Period documentation
Period between(LocalDate startDateInclusive, LocalDate endDateExclusive)
where
#param startDateInclusive the start date, inclusive, not null
#param endDateExclusive the end date, exclusive, not null
So it is better to adjust your implementation to make your end date inclusive and get your desired result
Period diff = Period.between(LocalDate.parse("2016-08-31"),
LocalDate.parse("2016-11-30").plusDays(1));
System.out.println("Months : " + diff.getMonths());
//Output -> Months : 3
You have to be careful, never use LocalDateTime to calculate months between two dates the result is weird and incorrect, always use LocalDate !
here's is some code to prove the above:
package stack.time;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class TestMonthsDateTime {
public static void main(String[] args) {
/**------------------Date Time----------------------------*/
LocalDateTime t1 = LocalDateTime.now();
LocalDateTime t2 = LocalDateTime.now().minusMonths(3);
long dateTimeDiff = ChronoUnit.MONTHS.between(t2, t1);
System.out.println("diff dateTime : " + dateTimeDiff); // diff dateTime : 2
/**-------------------------Date----------------------------*/
LocalDate t3 = LocalDate.now();
LocalDate t4 = LocalDate.now().minusMonths(3);
long dateDiff = ChronoUnit.MONTHS.between(t4, t3);
System.out.println("diff date : " + dateDiff); // diff date : 3
}
}
My 2%
This example checks to see if the second date is the end of that month. If it is the end of that month and if the first date of month is greater than the second month date it will know it will need to add 1
LocalDate date1 = LocalDate.parse("2016-08-31");
LocalDate date2 = LocalDate.parse("2016-11-30");
long monthsBetween = ChronoUnit.MONTHS.between(
date1,
date2);
if (date1.isBefore(date2)
&& date2.getDayOfMonth() == date2.lengthOfMonth()
&& date1.getDayOfMonth() > date2.getDayOfMonth()) {
monthsBetween += 1;
}
After the short investigation, still not totally fix my question, But I used a dirty solution to avoid return the incorrect duration. At least, we can get the reasonable duration months.
private static long durationMonths(LocalDate dateBefore, LocalDate dateAfter) {
System.out.println(dateBefore+" "+dateAfter);
if (dateBefore.getDayOfMonth() > 28) {
dateBefore = dateBefore.minusDays(5);
} else if (dateAfter.getDayOfMonth() > 28) {
dateAfter = dateAfter.minusDays(5);
}
return ChronoUnit.MONTHS.between(dateBefore, dateAfter);
}
The Java API response is mathematically accurate according to the calendar. But you need a similar mechanism, such as rounding decimals, to get the number of months between dates that matches the human perception of the approximate number of months between two dates.
Period period = Period.between(LocalDate.parse("2016-08-31"), LocalDate.parse("2016-11-30"));
long months = period.toTotalMonths();
if (period.getDays() >= 15) {
months++;
}
This question already has answers here:
Determine Whether Two Date Ranges Overlap
(39 answers)
Closed 8 years ago.
I have two date ranges, (start1,end1):::>>date1 && (start2,end2):::>>date2 .
I want to check if the two dates isOverLaped.
My flow chart I assume "<>=" operators is valid for comparing.
boolean isOverLaped(Date start1,Date end1,Date start2,Date end2) {
if (start1>=end2 && end2>=start2 && start2>=end2) {
return false;
} else {
return true;
}
}
Any Suggestion will be appreciated.
You can use Joda-Time for this.
It provides the class Interval which specifies a start and end instants and can check for overlaps with overlaps(Interval).
Something like
DateTime now = DateTime.now();
DateTime start1 = now;
DateTime end1 = now.plusMinutes(1);
DateTime start2 = now.plusSeconds(50);
DateTime end2 = now.plusMinutes(2);
Interval interval = new Interval( start1, end1 );
Interval interval2 = new Interval( start2, end2 );
System.out.println( interval.overlaps( interval2 ) );
prints
true
since the end of the first interval falls between the start and end of the second interval.
boolean overlap(Date start1, Date end1, Date start2, Date end2){
return start1.getTime() <= end2.getTime() && start2.getTime() <= end1.getTime();
}
//the inserted interval date is start with fromDate1 and end with toDate1
//the date you want to compare with start with fromDate2 and end with toDate2
if ((int)(toDate1 - fromDate2).TotalDays < 0 )
{ return true;}
else
{
Response.Write("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>");
return false;
}
if ((int)(fromDate1 - toDate2).TotalDays > 0 )
{ return true;}
else
{
Response.Write("<script>alert('there is an intersection between the inserted date interval and the one you want to compare with')</script>");
return false;
}
You have two intervals, i1 and i2. There are six cases for how the intervals can be temporally related (at least in a Newtonian world view) but only two are important: if i1 is entirely before i2 or i1 is entirely after i2; otherwise the two intervals are overlapping (the other four cases are i1 contains i2, i2 contains i1, i1 contains the start of i2 and i1 contains the end of i2). Assume i1 and i2 are of type Interval that have Date fields beginTime and endTime. The function then is (note, the assumption here is that if i1 starts at the same time i2 ends, or vice versa, we don't consider that an overlap and we assme for a given interval endTime.before(beginTime) is false):
boolean isOverlapped(Interval i1, Interval i2) {
return i1.endTime.before(i2.beginTime) || i1.beginTime.after(i2.endTime);
}
In the original question, you specify DateTime instead of Date. In java, Date has both date and time. This is in contrast to sql where Date does not have a time element while DateTime does. That is a point of confusion that I stumbled across when I first started using sql after having done only java for many years. Anyway, I hope this explanation is helpful.