[英]Initialize javascript Date to noon in "America/New_York"
I have a timezone as a canonical name from the IANA time zone list (eg "America/New_York").我有一个时区作为IANA 时区列表中的规范名称(例如“America/New_York”)。 I do not have the GMT+ value, which varies with Daylight Savings in ways I don't want to have to think about.
我没有 GMT+ 值,它随着夏令时的变化而变化,我不想考虑。
I have a time I want in the target time zone, eg noon on July 12, 2000.我在目标时区有一个我想要的时间,例如 2000 年 7 月 12 日中午。
How do I initialize a javascript Date to that time?如何将 javascript 日期初始化为那个时间?
It's best to use a dedicated Date/Time library, such as luxon
for this type of conversion.对于这种类型的转换,最好使用专用的日期/时间库,例如
luxon
。
We create a DateTime object in the desired timezone, then convert to local.我们在所需的时区创建一个 DateTime object,然后转换为本地。
The DateTime object can be converted to a JavaScript Date using.toJSDate(). DateTime object 可以使用.toJSDate() 转换为 JavaScript 日期。
const { DateTime } = luxon; const zone = 'America/New_York'; const obj = { year: 2000, month: 7, day: 12, hour: 12 }; const timeInZone = DateTime.fromObject(obj, { zone }); const localtime = timeInZone.toLocal(); console.log('Time in zone:', timeInZone.toString()); console.log('Local time: ', localtime.toString()); console.log('Local time (JSDate):', localtime.toJSDate().toString());
.as-console-wrapper { max-height: 100%;important }
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/3.0.1/luxon.min.js" integrity="sha512-6ZJuab/UnRq1muTChgrVxJhSgygmL2GMLVmSJN7pcBEqJ1dWPbqN9CiZ6U3HrcApTIJsLnMgXYBYgtVkJ8fWiw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
This can be done in vanilla JavaScript but it is much more awkward.这可以在原版 JavaScript 中完成,但要尴尬得多。
We must search for the corresponding UTC time for the time in the given timezone.我们必须为给定时区的时间搜索相应的 UTC 时间。
Once we have this we can display in local time.一旦我们有了这个,我们就可以在当地时间显示。
function convertToLocal(date, timeZone) { const dt = Date.parse(toIso(date) + 'Z'); // Test the entire range of offsets for(let offsetMinutes = -900; offsetMinutes <= 900; offsetMinutes += 15) { const test = new Date(dt + offsetMinutes * 60000); if (toIso(date) === toIso(test, timeZone)) { return test; } } } function toIso(date, timeZone) { const opt = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', fractionalSecondDigits: 3, timeZone }; return new Date(date).toLocaleString('sv', opt).replace(' ', 'T').replace(',', '.'); } let zone = 'America/New_York' let timeInZone = '2000-07-12T12:00:00.000'; console.log('Time in zone:', timeInZone); console.log('Local time: ', toIso(convertToLocal(timeInZone, zone)));
.as-console-wrapper { max-height: 100%;important }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.