Mutually restricting begin and end date-times using p:calendar (no validation) - java

We have a requirement to present two p:calendar components to the user, representing a start and end date each. Both datetimes have dates, hours and minutes.
PrimeFaces has perfect mindate, maxdate, minHour, maxHour, minMinute, and minMinute attributes available.
The requirement now is:
It is impossible to set the start datetime to anything greater than or equal to the end datetime.
It is impossible to set the end datetime to anything less than or equal to the end datetime.
The following equation should hold true:
begin datetime < end datetime
Now we tried the following JSF:
<p:calendar id="begin-date"
value="#{debugManager.selectedBeginDate}"
mindate="#{debugManager.minBeginDate}"
maxdate="#{debugManager.maxBeginDate}"
maxHour="#{debugManager.maxBeginHour}"
maxMinute="#{debugManager.maxBeginMinute}"
pattern="yyyy-MM-dd HH:mm"
showButtonPanel="true"
readonlyInput="true"
navigator="true"
showOn="button"
required="true">
<p:ajax event="dateSelect" update="end-date" />
</p:calendar>
<p:calendar id="end-date"
value="#{debugManager.selectedEndDate}"
mindate="#{debugManager.minEndDate}"
minHour="#{debugManager.minEndHour}"
minMinute="#{debugManager.minEndMinute}"
pattern="yyyy-MM-dd HH:mm"
showButtonPanel="true"
readonlyInput="true"
navigator="true"
showOn="button">
<p:ajax event="dateSelect" update="begin-date" />
</p:calendar>
Here's an examplary min/max method (mindate of end-date):
public Date getMinEndDate()
{
return this.getSelectedBeginDate();
}
As you can see, the minimum end date is the currently AJAX-selected begin date. Setting an end date correctly disallows setting the begin date past the end date.
The problems start when involving the time into the equation...
Since the interface of p:calendar has separate methods, the bean has to provide the logic:
public int getMinEndHour()
{
Date selectedBeginDate = this.getSelectedBeginDate();
Date selectedEndDate = this.getSelectedEndDate();
if ( selectedBeginDate != null && DateUtil.isSameDay( selectedBeginDate, selectedEndDate ) )
{
return DateUtil.getHourOf( selectedBeginDate );
}
return ComplianceConstants.DEFAULT_COMPLIANCE_CASE_MIN_END_HOUR;
}
This basically only says if a begin date has been set and it the begin and end dates are currently the same, restrict the selectable end hour (minHour of end-date) to the begin hour.
Operations:
Set the begin datetime to 2013-04-20 12:34 (legit)
Set the end datetime to 2013-04-22 00:00 (legit)
Now the time for end date sits on 00:00 and selecting a calendar date 2013-04-20 should be allowed as long as the end time is somehow adjusted to at least 12:35.
The p:calendar component however cannot know this and now
sets the end datetime to 2013-04-20 00:00 (legit, but false)
...
The problem now is that when the user presses a certain new end date in the calendar, the mindate/maxdate attributes cannot restrict the user to hit the the same as the begin date. If the end date time now happens to be before the same begin date's time there's nothing we can do about it (which is wrong).
The followup problem now is that the user is able to close the calendar and just press the submit button to insert false data into the DB. Of course, a validator could/should be run, but we have to somehow achieve this without a validator.
What we were trying next was to patch the setSelectedBeginDate( Date selectedBeginDate ) and setSelectedEndDate( Date selectedEndDate ) methods to adjust the set java.util.Date time portions if the dates were on the same day. Something like this:
public void adjustSelectedEndDate()
{
if ( this.selectedEndDate != null )
{
this.log.infov( "adjustSelectedEndDate: b-hour = {0}, e-hour = {1}", DateUtil.getHourOf( this.selectedBeginDate ), DateUtil.getHourOf( this.selectedEndDate ) );
if ( DateUtil.isSameDay( this.selectedBeginDate, this.selectedEndDate ) &&
( DateUtil.getHourOf( this.selectedEndDate ) < DateUtil.getHourOf( this.selectedBeginDate ) ) ||
DateUtil.getHourOf( this.selectedEndDate ) == DateUtil.getHourOf( this.selectedBeginDate ) && DateUtil.getMinuteOf( this.selectedEndDate ) <= DateUtil.getMinuteOf( this.selectedBeginDate ) )
{
this.log.info( "Adjusting selected end date!" );
this.selectedEndDate = DateUtil.addOneMinuteTo( DateUtil.copyTime( this.selectedBeginDate, this.selectedEndDate ) );
}
}
}
This required us to add #this to the update attribute of each p:calendar so that the respective getters (getSelectedBeginDate() and getSelectedEndDate + the min/max limiters) will be called during update.
Placing an #this on the update however confuses the p:calendar components, making the time sliders only slidable once. Subsequent slider events are simply ignored, behaving broken.
Q's
How do you generally approach solving this?
Is using p:remoteCommand the way to achieve what we want?
Optional Q:
Why hasn't the PrimeFaces p:calendar been implemented to provide a single minDateTime and maxDateTime, which could potentially solve the problems at hand?
I bet this scenario I described has already been solved before. I'd very much appreciate if you could describe the approach you managed to solve this (or even share a partly solution).

Preface:
I don't work with JSF, but there are a couple of things that might steer you back to where you want to be:
a) when working with just the date portion of a dateTime in a standard calendar, consider using:
someCalendar.set(Calendar.MILLISECOND, 0)
b) consider using joda-time, as it seems to be frequently recommended (here, here , and many other places) over the standard library for correctness, performance, and ease of use in many situations.
c) Make sure your bean scope is surviving each ajax call (not redirecting, only sending standard post-backs, etc) and each event handler is getting the faces context (eg. FacesContext facesContext = FacesContext.getCurrentInstance();)
d) mindate and the like probably don't work like you expect , and I don't expect that automatic behavior can be quite so easily interjected.
When those options aren't available, and you have to do it all yourself with what you have:
Philisophical / UX:
The first thing I would do is remove the expectation of arrangement or perspective from the pair of dates. Don't treat the pair as a vector that exposes or expects a direction on the timeline.
In other words, is a start or from date always less than or earlier than an end or to date? No, as can be seen for a query of historical data, or for applying corrections to events that have either yet to happen or have already happened?
This connotation can easily confuse a user as to whether they are going 'back to' or 'forward from' (and can easily confuse yourself). Instead I would treat a pair of dates with a time-period between them as just and simply that a pair of dates or a range or a period that declares an interval, and infer their relative position on the timeline depending on the any consequently chosen values. In this way you can honor the respective and inherent requirements that the dates never be equal, and the left is always to the left, the right always to the right.
We can't infer what 'start' or 'from' means, but we can infer some meaning and relative relationship: a right, a left, and a between on a chronological timeline. Note: Always resolve dates to UTC before doing any calculation or comparison.
long oneDateValue = oneDate.toUtc().toMilliseconds();
long anotherDateValue = anotherDate.toUtc().toMilliseconds();
long right = max (oneDateValue, anotherDateValue);
long left = min (oneDateValue, anotherDateValue);
Evaluating Precision:
The second thing I would look at when working with a range of dates in any language is similar to how you might deal with floating point numbers. For comparisons, do not compare for equality, but instead compare the delta to an "acceptable error level". In other words, the application is really only concerned with a certain degree of precision, so make sure that only that precision is captured and considered:
const int dateTimeResolutionInMs = 86400000; // milliseconds per day
public bool areEssentiallySame(long left, long right) {
// the difference between right and left is less than our precision
// requires, thus dates are effectively the same
return (right - left < dateTimeResolutionInMs);
}
Coercing Precision:
Thirdly, how do we resolve the difference in values even if within the range of the resolution? (Out application was given more precision than it can handle or expect or needs).
long diff = value % dateTimeResolutionInMs;
Truncate: return value - diff;
Nearest (w/bias): return value + (diff < dateTimeResolutionInMs/ 2) ? -1 * diff : dateTimeResolutionInMs - diff;
Others: there are lots of other strategies for either shrinking or expanding a value to a preferred resolution or precision
Addendum:
As far as getting post-backs/Ajax calls to return a view with the values you expect for the events fired by a calendar element, you may want to separate that concern off to a new question if the note in the preface didn't get you anywhere, and you know for certain your bean is properly registered and recognized. You may have some browser/browser-version specific issues that contribute to the undesired behavior, and like anything else, there are issues, both known and unknown.

Related

Check date range in java without time AND using jodatime

I have a date supplied by the user and of course today's date.
I'm attempting to verify that the difference between the 2 days is at least 2 weeks. I've done this using standard libraries - but I'm attempting to do this using jodaTime and I'm having some difficulty.
// BAD CODE - doesn't work
// NOTE: getUserSuppliedDate() returns an instance of java.sql.Date
// Also assume that validation prior to this call has been run that
// validates that the userSuppliedDate comes AFTER today's date - not sure if
// that is relevant in the context I'm attempting to use these particular jodaTime APIs.
DateTime jodaStartDate = new DateTime(getUserSuppliedDate());
if (Days.daysBetween(jodaStartDate, DateTime.now()).isLessThan(Days.days(14))) {
System.out.println("Bad user. You have chosen...poorly.");
}
else {
System.out.println("Well done user. You have supplied wisely.");
}
// GOOD CODE ---- ? Help =)
Your code gives you the wrong result because the dates supplied to Days.daysBetween() are in the wrong order. Since you specified that the user supplied date comes after the current date, your approach will result in a negative number of days.
It will work correctly if you switch the order, putting the earliest date first.
Compare the following two:
DateTime jodaStartDate = new DateTime().withYear(2018)
.withMonthOfYear(7)
.withDayOfMonth(5); // 15 days from now
System.out.println(Days.daysBetween(jodaStartDate, DateTime.now())); // "P-15D"
System.out.println(Days.daysBetween(DateTime.now(), jodaStartDate)); // "P15D"
In the first case, -15 days will evaluate to less than 14 days.
Using weeks instead of days, you'd run into the same problem:
System.out.println(Weeks.weeksBetween(jodaStartDate, DateTime.now())); // "P-2W"
System.out.println(Weeks.weeksBetween(DateTime.now(), jodaStartDate)); // "P2W"

How to check time lies within a range?

I looked at this question and my problem is similar but not exactly identical. I have many timestamps in problem and they are all in the form "yyyyMMddHHmmssSSS", so I am parsing the string as follow:
DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS").parse("20180301050630663")
which will output 2018-03-01T05:06:30.663 (I do not know what the "T" in the middle stands for and do not know how to get rid of it)
Problem is I only care about the timestamps that lies within the range of [09:15:00.000am -12:00:00.000pm] and [15:15:00.000pm -18:00:00.000pm] across all different dates (inclusive too, meaning that if the timestamp is exactly at 09:15:00.000, then it should return true too).
However, how should I tackle this problem because sometimes the dates could be different, i.e. it could be across different dates 2018-03-01T05:06:30.663, 2018-03-02T10:36:30.596,2018-03-11T05:06:30.663? Since the date and times always come together, shall I extract the time from the timestamp ? What is the best way to deal with this in this situation ? I am not too familiar with the datetime libraries in Java.
You were on the right track with DateTimeFormatter. Rather than use DateTimeFormatter.parse, you can pass this formatter to LocalTime.parse which will effectively discard the date portion of the timestamp. You can then use Comparable.compareTo to see whether it's in the ranges you've given.
final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
LocalTime time = LocalTime.parse("20180301050630663", formatter);
if (time.compareTo(LocalTime.of(9, 15)) >= 0
&& time.compareTo(LocalTime.of(12, 0)) <= 0)
{
System.out.println("First period");
}
else if (time.compareTo(LocalTime.of(15, 15)) >= 0
&& time.compareTo(LocalTime.of(18, 0 )) <= 0)
{
System.out.println("Second period");
}
If your ranges were exclusive rather than inclusive, you could have used LocalTime.isAfter and LocalTime.isBefore which would have resulted in slightly nicer looking code.

How to compare time in freemarker?

In Freemarker, I can use .now?time to get the current time, but how do I compare that to another time?
For example, how would I properly test if the current time is between 8:00 AM and 5:00 PM?
<#if .now?time gte (?) && .now?time lte (?)>
//do something
<#/if>
I don't know what to put in the (?) because I'm not sure how to create date scalars in Freemarker.
Although you can compare two java.util.Date-s as far as they are both of the same kind (like both are time-only values), then it's up to you to ensure that the internal representations are consistent (like a time-only value is in the epoch-day VS on some other day). Thus it's mostly meant to be used for comparing date-time values (timestamps) where no such issue exists. So, since you know that you want an epoch-based time, you could do the following hack:
<#assign nowTime = .now?time?string.iso?time.iso>
Now it's correctly comparable with "8:00:00 AM"?time, however, I recommend using ISO format, because the locale-specific format is kind of fragile (like if you change locale, it won't work): '08:00:00'?time.iso. Note that for this you need at least FreeMarker 2.3.21.
I read the source of freemarker 2.3.21 and found that current freemarker does not support comparing .now?time and time object such as "8:00:00 AM"?time.
That is because.now?time is internally treated as current time such as 2014-10-21 15:11:30,
and "8:00:00 AM"?time is treated as 1970-01-01 08:00:00.
Therefore, <#if .now?time gte "8:00:00 AM"?time > is always true.
If you think it's a bug you may report to http://sourceforge.net/p/freemarker/bugs/ or send a question in freemarker's mailing list.
So the current workaround is to create the Date object and compare it in the java code.
If you happen to use Liferay you can try the compareTo() function:
It returns negative if the date is earlier, positive if it is later and zero if they are equal.
<#assign time1 = "11:55:00"?time>
<#assign time2 = "11:56:00"?time>
${dateUtil.compareTo(time1, time2)} <#-- Return -1 -->
${dateUtil.compareTo(time2, time1)} <#-- Return 1 -->
${dateUtil.compareTo(time1, time1)} <#-- Return 0 -->

Java equivalent of C's _timezone, _daylight and time()

With this C code:
int a = time(NULL);
_daylight = 0;
_timezone = 0;
int b = time(NULL);
assert(a != b);
"a" and "b" will have different values (and not just because they are called a few milliseconds apart). The difference will be whatever the offset of your PC's timezone is from UTC time. Also, changing the _daylight and _timezone values effect pretty much every other function I might use in my C app -- I assume because they all respect that value.
Is there anything like that in Java, or specifically for Java on Android OS? I tried TimeZone.setDefault(), but that didn't change the value that System.currentTimeMillis() returned, so I assume it isn't going to have a "global" effect like the C variables.
I understand that System.currentTimeMillis() is different than time(), in that it "always" returns the number of millis since now and epoch, and the time() function allows you to get "false" (fudged) values that are adjusted according to these global variables you can set.
Just trying to emulate a legacy C app on Android OS. It clears those _timezone and _daylight values which pretty much means it ignores any timezones. So if a user running the app on the west coast enters a time of 3pm, and then they change their timezone settings, or a user on the est coast views that item, it will still show as 3pm.
I know I can use the Calendar object and other methods to make sure I do the proper conversions, but I'd rather just have an easy "I don't care about timezones" settings like I did in the C app and then truely not have to worry about them.
Edit: I would still like to hear what other options I have, but for now I came up with this Java code that I'll do my best to always use for any code that needs to mimic the C app:
// IMPORTANT: Use this function everywhere a Calendar object is needed, instead of calling
// Calendar.getInstance() directly. This returns the correct kludged time that matches
// what our PC application uses (_daylight=0, _timezone=0, time(NULL) in C)
public static Calendar GetCalendarInstance()
{
// Get the current UTC time
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
// Offset it by the system time zone offset.
// This mimics what the C time(NULL) function does when you set _timezone=0 and _daylight=0
cal.add(Calendar.MILLISECOND, TimeZone.getDefault().getOffset(cal.getTimeInMillis()));
return(cal);
}
Also, I did already find one place in my Android app that I need the real, not adjusted, system time (when using AlarmManager to schedule a PendingIntent). So I guess "global" could be dangerous either way. I still think 95% of my code will be using the version that mimics the C app though, so if possible I'd like to default to that and then only have to do special handling for the other few places.

Better way to check if a joda.time.Interval spans exactly 1 calendar week (accounting for daylight savings etc)

Is there a better way of doing this?
boolean oneCalendarWeek = interval.getStart().plusWeeks(1).equals( interval.getEnd() );
I guess the following won't work because of the way equals is implemented...
boolean oneCalendarWeek = interval.toPeriod().equals( Weeks.ONE );
From the comments:
i really want to know if the api supports something like my second example which i think is clearer than the first
While the example using Weeks.ONE does not work (since Period.equals() first checks if the two Period instances support the same number of fields, and Weeks.ONE only supports one field), this should work instead:
boolean oneCalendarWeek = interval.toPeriod().equals( Period.weeks(1) );
Here is a code sample that tests this for an interval that starts before the start of DST and ends while in DST. However, I'm not 100% sure how this would behave if the start or end time of the Interval fell exactly on the DST boundary.

Categories

Resources