正如标题所述,我想获得某个时区的一天的开始时间和结束时间,并将它们转换为utc时间。以下是我实施的部分内容:
Form2 BarForm = new Form2() { SomeEvent = progress};// <- When i assign handler in Form2 class progress in Form1 is always null
问题是如何将某个时区的时间转换为utc时间。或者还有其他合适的解决方案吗?谢谢!
编辑:
我想出了一种自己做的方法,这种做法并不太合适。
//convert current local time to specified timezone time
var converted = moment.tz(moment(), timezone).format("YYYY-MM-DD");
var full_format = "YYYY-MM-DD HH:mm:ss";
// get start time and end time in the timezone
var start = converted + " 00:00:00";
var end = converted + " 23:59:59";
// how to convert them in utc time by momentjs or other methods?
var utc_start_time = ?
var utc_end_time = ?
欢迎任何有关改进的建议。感谢
答案 0 :(得分:2)
取决于您想要做什么:
// for the current day
var start = moment.tz(timezone).startOf('day').utc();
var end = moment.tz(timezone).endOf('day').utc();
// for a specific moment (m)
var start = m.clone().tz(timezone).startOf('day').utc();
var end = m.clone().tz(timezone).endOf('day').utc();
// for a specific calendar date
var m = moment.tz(date, format, timezone);
var start = m.clone().startOf('day').utc();
var end = m.clone().endOf('day').utc();
然后,您可以使用start
函数格式化end
和format
。
请记住,不是每天都在每个时区的午夜开始,所有当地时间都不是24小时。
答案 1 :(得分:1)
这是使用Intl.DateTimeFormat处理时区的本机解决方案。
它可以找到指定时区的一天的开始/结束。
要将Date
实例转换为UTC时间,请使用Date.prototype.toISOString。
const beginingOfDay = (options = {}) => {
const { date = new Date(), timeZone } = options;
const parts = Intl.DateTimeFormat("en-US", {
timeZone,
hourCycle: "h23",
hour: "numeric",
minute: "numeric",
second: "numeric",
}).formatToParts(date);
const hour = parseInt(parts.find((i) => i.type === "hour").value);
const minute = parseInt(parts.find((i) => i.type === "minute").value);
const second = parseInt(parts.find((i) => i.type === "second").value);
return new Date(
1000 *
Math.floor(
(date - hour * 3600000 - minute * 60000 - second * 1000) / 1000
)
);
};
const endOfDay = (...args) =>
new Date(beginingOfDay(...args).getTime() + 86399999);
const beginingOfYear = () => {};
console.log(beginingOfDay({ timeZone: "GMT" }));
console.log(endOfDay({ timeZone: "GMT" }));
console.log(beginingOfDay({ timeZone: "Asia/Tokyo" }));
console.log(endOfDay({ timeZone: "Asia/Tokyo" }));
答案 2 :(得分:0)
我也遇到了这个问题。不幸的是,moment.js 似乎在告诉人们使用其他选项。 (我猜从他们的网站来看,他们更关注美国政治,呃)。此外,已接受的答案中的许多时刻功能现在都已弃用。 Luxon 是当时建议作为替代方案的第一个库。
import { DateTime } from "luxon";
var dt = DateTime.local() //get the current time in local timezone, for me this is Pacific Time (West Coast USA)
.endOf('day') // set the time to the end of the current day
.setZone('GMT'); // change time zone back to GMT (zero offset)
console.log(dt.toISO()); // 2021-01-12T07:59:59.999Z