[英]from `const now = new Date()`, how can I verify that I am before or equal a particular date at a given timezone and hour?
I have a timezone map with publishing hour in the local zone with news that must define when they should be published on a date using a date picker.我有一个时区地图,在本地区域发布时间,新闻必须使用日期选择器定义何时应该在某个日期发布。
This is a new news article
that is initialized with the following:这是一篇新的新闻
article
,初始化如下:
{ timeZoneId: 'Europe/Paris, releaseHour: 9, publishingDateTime: undefined }
// 9 is the hour GMT+1 { timeZoneId: 'Europe/Paris, releaseHour: 9, publishingDateTime: undefined }
// 9 是 GMT+1 小时I want to know how can I from const now = new Date()
, verify if this article should be published today or the next day, the criteria are:我想知道我如何从
const now = new Date()
,验证这篇文章应该今天发布还是第二天发布,标准是:
now
before releaseHour
? now
是在releaseHour
之前吗? (is 9am GMT+1 in paris already passs or not) How is this possible?这怎么可能?
This is how I have tried:这是我尝试过的方式:
import { isBefore, isEqual } from 'date-fns';
import { utcToZonedTime } from 'date-fns-tz';
export const getNextPublishingDateTime = (now, timeZoneId, releaseHour) => {
const zoned = utcToZonedTime(now, timeZoneId);
const releaseTime = new Date(zoned.toISOString());
releaseTime.setHours(releaseHour, 0, 0, 0);
if (isBefore(zoned, releaseTime) || isEqual(zoned, releaseTime)) {
console.log('before');
return releaseTime;
}
releaseTime.setDate(releaseTime.getDate() + 1);
console.log('after');
return releaseTime;
};
But the hour returned by utcToZonedTime
is not +01:00 offset, instead it is a date at my offset.但是
utcToZonedTime
返回的小时不是 +01:00 偏移量,而是我偏移量处的日期。
I have tried some other ideas, using moment-tz
and vanilla Date
, I found this task a bit complicated and hope to find help with the JS community as this look to be a normal date comparaison.我尝试了一些其他的想法,使用
moment-tz
和 vanilla Date
,我发现这个任务有点复杂,希望能在 JS 社区中找到帮助,因为这看起来是一个正常的日期比较。
You can use the Intl object and formatToParts method to get the current time in any supported timezone using IANA representative locations .您可以使用 Intl 对象和formatToParts方法获取使用 IANA代表位置的任何受支持时区中的当前时间。 It's reasonably well supported .
它得到了相当好的支持。
Eg例如
function getHour(date, loc) { let d = new Intl.DateTimeFormat("en-EN", { hour: 'numeric', hour12: false, timeZone: loc }); return d.formatToParts(date)[0].value; } let loc = 'Europe/Paris'; let now = new Date(); console.log(`The current hour in ${loc} is ${getHour(now, loc)}.`);
The above is just for illustration, there should be validation of input and return values.以上只是为了说明,应该有输入和返回值的验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.