我需要花一个小时将其转换为本地时间,如下所示:
const dataDate = '07:08'
const utcDate = new Date(dataDate);
console.log(utcDate)
我的方法有一些问题
- 只有当我也添加了日期时,这才有效
- 这转换为utc
我只需要将小时转换为本地时间,我还需要将其解析为以下内容:
[parseInt(hour), 0, 0, 0].map(function (x) { return parseInt(x, 10); })
为了提供更多的上下文,我需要创建一个具有特定时间表的可共享日历,用户可以设置要显示的某个事件的特定时间。
如果您有权访问完整日期
考虑到您的用例是可共享日历,我假设您可以访问完整的UTC日期。如果不是这样,跳到下一个部分
// The important thing is getting a `Date` object. The timezone in the timestamp
// doesn't really matter at this point. It will be handled internally anyway.
const date = new Date("2011-11-11T07:08:00Z");
一旦你有了日期对象,如果你真正想要的只是小时,您可以使用以下方法来完成此操作。但请注意,在整个应用程序中,您可能不仅应该使用相同的方法来获取时间,还应该使用相同方法来获取日期或时间的任何部分。
const utcHour = date.getUTCHours(); //> 7
// For the hour according to the timezone configured in the RUNTIME
// environment (e.g. the user's browser, if running on the client side):
const runtimeHour = date.getHours(); //> 8 (depends on the runtime timezone)
// For an arbitrary timezone, in case you have the user's timezone stored in
// a config you could use the `.toLocaleTimeString()` method.
// Note that this method is VERY slow (~6000 times slower than `.getHours()`
// for example in a quick benchmark I ran in my machine on Node 16). You
// should probably be careful about how often this is being called (e.g. in
// loops or in a frontend component that is frequently updated/rendered).
const tzHour = Number(date.toLocaleTimeString("en", {
hour: "numeric", // omit minutes and seconds
hour12: false, // force it to be 0-23
timeZone: "America/Sao_Paulo" // set the user's timezone
})); //> 5
您应该使用哪一个真正取决于您的确切实现。您可能还想检查这个答案,它进一步解释了Date
是如何处理时区的。
注意:
.toLocaleTimeString()
方法取决于Intl.DateTimeFormat
API。在MDN检查Date.prototype.toLocaleTimeString()
以获取兼容性表。
关于手动计算时间偏移的注意事项
您需要日期来可靠地调整时间。
如果你因为某种原因没有约会,你可以这样做,但那会意味着相当多的工作,它永远不会真正可靠,因为你不会例如,可以考虑夏令时调整。
还要记住,有些时区的运行时间是一小时的几分之一:
+XX30
:Asia/Tehran
、Asia/Kabul
、Australia/Adelaide
+XX45
:Australia/Eucla
Australia/Lord_Howe
的夏令时调整为30分钟
根据应用程序的要求,手动计算可能没有你想象的那么简单。我建议将这些计算到内部Date
实现(如前一节所示(,而不是尝试手动调整时间(请记住,您必须从min开始处理溢出→小时→白天→月→年(。
关于解析时间字符串
至于您在问题中提到的时间字符串的解析,您可以执行以下操作:
const rawTime = "07:08";
const [hour, minutes, seconds = 0] = rawTime.split(":").map(Number); //> [7, 8, 0]
// or if you only care about the hours
const hour = Number(rawTime.split(":", 1)); //> 7
// or you could also use a quirk of `parseInt()`, as it ignores everything
// starting at the first non-numeric character:
const hour = parseInt(rawTime); //> 7
- 如果使用
new Date()
实例化新日期,则返回的值为UTC
时区中的当前日期/时间 - 然后,您可以使用
Date.setHours()
和Date.setMinutes()
将特定的小时/分钟设置为该小时/分钟 - 最后,您可以通过
Date.toLocaleDateString()
将UTC
日期转换为本地日期
所以我会为你的情况做这样的事情:
const date = new Date();
const [hour, minute] = '7:28'.split(':')
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
};
date.setHours(hour);
date.setMinutes(minute);
console.log(date.toLocaleDateString('en-US', options));