如何在javascript中获取指定时区的一天的UTC开始时间和结束时间? [英] How to get the start time and end time in utc of a day for a specified timezone in javascript?

查看:52
本文介绍了如何在javascript中获取指定时区的一天的UTC开始时间和结束时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如标题所述,我想获取某个时区的一天的开始时间和结束时间,并将它们转换为 UTC 时间.这是我的实施部分:

As the title stated, I want to get the start time and end time of a day for certain timezone and convert them to utc time. Here is my part of my implementation:

//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 = ?

问题是如何将某个时区的时间转换为UTC时间.或者有没有其他像样的解决方案?谢谢!

The question is how to convert the time in certain timezone to utc time. Or is there any other decent solutions to it? Thank you!

我想出了一种自己制作的方法,但不太体面.

I figured out a way to make it myself which is not quite decent.

var converted = moment.tz(moment(), timezone).format("YYYY-MM-DD");         
var full_format = "YYYY-MM-DD HH:mm:ss";
var start = converted + " 00:00:00";
var end = converted + " 23:59:59";
var utc_start_time = moment(start).add(utc_offset * -1, 'hours').format(full_format);
var utc_end_time = moment(end).add(utc_offset * -1, 'hours').format(full_format); 

欢迎提出任何改进建议.谢谢

Any suggestions on improvements are welcome. Thanks

推荐答案

取决于你到底想做什么:

Depending on what exactly you want to do:

// 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();

然后您可以使用 format 函数格式化 startend.

You can then format start and end however you like with the format function.

还要记住,并非每个时区的每一天都从午夜开始,也不是所有当地的日子都有 24 小时.

Keep in mind also that not every day starts at midnight in every time zone, nor do all local days have 24 hours.

这篇关于如何在javascript中获取指定时区的一天的UTC开始时间和结束时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆