I have an application where some operations are only allowed at certain time of period to every user no matter from which country he accessing Application just like stock exchange has fixed time window.
Suppose I set operational time to 01:00 AM to 11:00 PM Eastern Time (ET) and I am storing time to UTC format in DB. and this is From time 6:00:00 to time 4:00:00.
Below is how I handled it
const nowGetTime = nowDateTime.getTime();
const availableLocaleFrom = new Date(this.setDateTime(new Date(), this.availableFrom)); // Here Adding current date to existing time as without it we can't convert date
const availableLocaleTo = new Date(this.setDateTime(new Date(), this.availableTo));
const start = this.convertUTCDateToLocalDate(availableLocaleFrom);
const end = this.convertUTCDateToLocalDate(availableLocaleTo);
// console.log('start', availableLocaleFrom, 'end', availableLocaleTo);
// same day but ahead of start
if (start.getDate() > new Date().getDate()) {
start.setDate(start.getDate() - 1 );
}
if (start.getTime() > end.getTime()) {
end.setDate(end.getDate() + 1 );
}
if (end.getTime() - start.getTime() > (1000 * 60 * 60 * 24)) {
end.setDate(end.getDate() - 1 );
}
this.isMarginAvailable = ( nowGetTime > start.getTime() && nowGetTime < end.getTime());
Helping functions
setDateTime(date: Date, str: string) {
var sp = str.split(':');
date.setHours(parseInt(sp[0],10));
date.setMinutes(parseInt(sp[1],10));
date.setSeconds(parseInt(sp[2],10));
return date;
}
convertUTCDateToLocalDate(onlyLocaleDate) {
return new Date(Date.UTC(onlyLocaleDate.getFullYear(), onlyLocaleDate.getMonth(), onlyLocaleDate.getDate(), onlyLocaleDate.getHours(), onlyLocaleDate.getMinutes(), onlyLocaleDate.getSeconds()));
}
And this function is not working well. Like in Tokyo when Tokyo's local time is 2:30 pm condition is not satisfying Happening same for Australia at certain period.
I am struggling since 2 days, trying many if else conditions and still trying some reliable solution. This conditions not satisfying when time frame is beyond 12 hours.
Thanks