我正在獲取data.value格式中的時間:hh:mm a- 例如12:30 am。
我也知道:
- 用戶的本地時區 (
userTimeZone) - 地點的時區 (
venueTimeZone)
我需要將用戶選擇的時間 ( data.value) 轉換為venueTimeZone. 例如,如果用戶在Americas/New York并且他們選擇了 2022 年 5 月 20 日下午 1:30,并且場地在Americas/Los Angeles- 我有興趣獲得的值是20/05/2022 10:30AM.
這是我的嘗試,但是時區本身并沒有改變 - 我認為這是因為當我創建時userDateTime我moment沒有指定時間偏移量,但我不確定如何從 獲取偏移量userTimeZone,同時考慮 DST .
const userTimeZone = _.get(
Intl.DateTimeFormat().resolvedOptions(),
['timeZone']
);
const venueDateStr = new Date().toLocaleString('en-US', {
timeZone: venueTimeZone,
});
const Date = new Date(restaurantDateStr);
const venueYear = venueDate.getFullYear();
const venueMonth = `0${venueDate.getMonth() 1}`.slice(-2);
const venueDateOfMonth = `0${venueDate.getDate()}`.slice(-2);
const userDateTime = createDateAsUTC(
moment(
`${venueDateOfMonth}/${venueMonth}/${venueYear} ${data.value}`,
'DD/MM/YYYY hh:mm a'
).toDate()
).toLocaleString('en-US', { timeZone: venueTimeZone });
編輯 - 我沒有城市偏移量,我有時區名稱,因此我不能使用任何依賴于城市偏移量的建議答案。
uj5u.com熱心網友回復:
考慮使用Luxon - Moment 的繼任者。(請參閱Moment 的專案狀態。)
// Parse your input string using the user's local time zone
// (this assumes the current local date)
const local = luxon.DateTime.fromFormat('1:30 pm', 'h:mm a');
// Convert to the desired time zone
const converted = local.setZone('America/Los_Angeles');
// Format the output as desired
const formatted = converted.toFormat('dd/MM/yyyy h:mm a').toLowerCase();
console.log(formatted);
<script src="https://cdnjs.cloudflare.com/ajax/libs/luxon/2.4.0/luxon.min.js"></script>
您也可以在沒有庫的情況下執行此操作,但是您可能會發現并非所有瀏覽器都會決議輸入字串,并且您的輸出格式也取決于瀏覽器。
// Get the current local date as a string
const date = new Date().toLocaleDateString();
// Parse the date and time in the local time zone
// Warning: This is non-standard and may fail in some environments
const dt = new Date(date ' 1:30 pm');
// Format the output, converting to the desired time zone
const result = dt.toLocaleString(undefined, { timeZone: 'America/Los_Angeles' });
console.log(result);
當然,有手動方法來決議和格式化日期(使用正則運算式等),但我會留給你或其他人來完成。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/481376.html
標籤:javascript 日期 时间 时区 时刻
