I am developing a login functionality, where user is not allowed to login between some duration of time, and this is configurable. For example user is not allowed to login between
{
"fromDate": "2022-03-08",
"toDate": 2022-03-15,
"fromTime": "09:00",
"toTime": "16:00",
"timezone": "Canada/Toronto",
"days": [
"Monday",
"Tuesday",
"Wednesday",
"Saturday",
"Sunday",
"Thursday",
"Friday"
]
}
Can anyone help in comparing fromDate and toDate with current User login time. I am tryin to convert all dates in UTC and then compare. As user can login anywhere so as per login time date may change in other country. Any suggestions/reference would be helpful.
CodePudding user response:
This appears to be a schoolwork assignment. So I’ll give a brief outline of the needed code, and let you fill in the details.
Parse your JSON into Java objects.
In the Java ecosystem, you have a choice of frameworks to assist in parsing JSON.
You need to end up with objects of the java.time classes as shown in code here.
LocalDate startDate = LocalDate.parse( "2022-03-08" ) ;
…
LocalTime startTime = LocalTime.parse( "09:00" ) ;
…
ZoneId z = ZoneId.of( "Canada/Toronto" ) ;
Set< DayOfWeek > dows = EnumSet.noneOf( DayOfWeek.class ) ;
dows.add( DayOfWeek.valueOf( "Monday".toUppercase() ) ;
…
Capture the current moment as seen with an offset from UTC of zero hours-minutes-days.
Instant instant = Instant.now() ;
Adjust into target time zone.
ZonedDateTime zdt = instant.atZone( z ) ;
Interrogate for the parts of that moment.
LocalDate ld = zdt.toLocalDate() ;
LocalTime lt = zdt.toLocalTime() ;
DayOfWeek dow = zdt.getDayOfWeek() ;
Compare to your limits.
if( ( ! ld.isBefore( startDate ) ) && ld.isBefore( endDate ) ) { … }
…
if( dows.contains( dow ) { … }
Regarding comparisons, I suggest you learn about Half-Closed versus Fully-Closed. I recommend consistent use of Half-Closed.
All these topics have been addressed many times already on Stack Overflow. So search to learn more.
CodePudding user response:
One practice is to use ZonedDateTime and put the zone at UTC or compare the offsetDateTime
LocalDateTime ldtLowerBound = LocalDateTime.parse("2022-03-08T9:00:00");
LocalDateTime ldtUpperBound = LocalDateTime.parse("2022-03-15T6:00:00");
//For zonedDateTime
ZonedDateTime zdt = ldtLowerBound.atZone(ZoneOffset.UTC);
//For OffsetDateTime
OffsetDateTime odt = ldtLowerBound.atOffset(ZoneOffset.UTC);
Then compare them with user localDateTime with your desired logic.