如何使用Moment.js转换为12小时时钟或基于时区的24小时时钟

发布于 2025-01-25 20:26:03 字数 1054 浏览 4 评论 0原文

因此,我从一个非常奇怪的格式开始,从本质上讲,这是午夜后的几分钟(在我想达到的时区中)。因此,如果我在纽约,含义是凌晨6:30,则起始价值为390。

到目前为止,这是我的代码:

const open_time = (String(startingTime / 60)).split(".") // startingTime of 390 becomes an array of ['6','5']
const open_hour = open_time[0] // open hour becomes '6'
var open_minutes = 0 // if the startingTime was evenly divisible by 60, that means we're on the hour
if (open_time[1] !== undefined) { // startingTime wasn't evenly divisible by 60, need to do some calculations
    open_minutes = Number(`0.${open_time[1]}`) * 60 // get the minutes into the hour
}
const open_minutes_formatted = open_minutes.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
}) // make sure the minutes format in 00 - 09 instead of 0 - 9 for the first 10 minutes of the hour.
const hours = `${open_hour}:${open_minutes_formatted}` // final string outputted

在这一点上,时间的格式为6:30,或者是下午15:15: 00。我的问题是,如何根据用户在哪里使用Moment.js这次格式化这次与24小时时钟进行格式化?

在代码中的这一点上,我使用模块tzlookup来获取用户所在位置的时区,因此我认为我可以使用它,但不确定实际转换的外观。任何帮助!

So I'm starting with a REALLY weird format, which is essentially the minutes after midnight represented as a number (in the timezone I'm trying to get to). So if I'm in New York and mean 6:30 AM, the starting value is 390.

Here's my code so far:

const open_time = (String(startingTime / 60)).split(".") // startingTime of 390 becomes an array of ['6','5']
const open_hour = open_time[0] // open hour becomes '6'
var open_minutes = 0 // if the startingTime was evenly divisible by 60, that means we're on the hour
if (open_time[1] !== undefined) { // startingTime wasn't evenly divisible by 60, need to do some calculations
    open_minutes = Number(`0.${open_time[1]}`) * 60 // get the minutes into the hour
}
const open_minutes_formatted = open_minutes.toLocaleString('en-US', {
    minimumIntegerDigits: 2,
    useGrouping: false
}) // make sure the minutes format in 00 - 09 instead of 0 - 9 for the first 10 minutes of the hour.
const hours = `${open_hour}:${open_minutes_formatted}` // final string outputted

At this point, hours is formatted to something like 6:30, or if it's in the afternoon, 15:00. My question is, how do I use moment.js to format this time based on the 12 hour clock vs 24 hour clock based on where the user is?

At this point in the code, I've used the module tzlookup to get the timezone for where the user is located so I think I can use that, but not sure how the actual conversion looks. Any help appreciated!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文