Momentjs时区-在特定时区的时间获取日期 [英] Momentjs timezone - getting date at time in specific timezone
问题描述
我正在尝试从UTC基准在用户的特定时区(在本例中为美国/洛杉矶")中使用momentjs/momentjs时区创建日期.但是,我没有得到我期望的结果:
I am attempting to create a date from a UTC base in a user's specific timezone, in this case "America/Los Angeles" using momentjs/momentjs timezone. However, I'm not getting the results I expect:
var tempDate = moment(1448841600000); //moment("2015-11-30"); //monday 11/30 in UTC
var adjustedStart = moment.tz(tempDate, "America/Los_Angeles");
adjustedStart.hour(9);
adjustedStart.minute(30);
console.log("adjustedStart in milliseconds:" + adjustedStart.valueOf());
控制台输出为1448875800000,这是UTC/GMT的11/30/15 9:30 AM,我期望的1448904600000是太平洋海岸时间的11/30/15 9:30 AM.如何将此开始日期转换为用户所在时区的正确时间?
The console output is 1448875800000 which is 11/30/15 9:30AM in UTC/GMT, I was expecting 1448904600000 which is 11/30/15 9:30AM in Pacific Coast time. How can I translate this start date to the right time in the user's timezone?
推荐答案
是的,1448841600000
是您说的日期:
moment(1448841600000).utc().format()
// "2015-11-30T00:00:00+00:00"
但这是太平洋时间的前一天
But that is a day earlier in Pacific time
moment(1448841600000).tz('America/Los_Angeles').format()
// "2015-11-29T16:00:00-08:00"
当您将其调整为9:30太平洋时,它位于29号,而不是30号.
When you adjust it to 9:30 pacific, it's on the 29th, not the 30th.
moment(1448841600000).tz('America/Los_Angeles').hour(9).minute(30).format()
// "2015-11-29T09:30:00-08:00"
致电valueOf
时,结果为:
moment(1448841600000).tz('America/Los_Angeles').hour(9).minute(30).valueOf()
// 1448818200000
这是正确的值,但是与您提供的值不同.但是,这确实是我在运行您的代码时得到的.
This is the correct value, however it's different than the one you provided. However, it is indeed what I get when I run your code as well.
Chrome调试窗口中的屏幕截图,其中包含您的确切代码:
Screenshot from Chrome debug window, with your exact code:
此外,在您写的评论中:
Also, in comments you wrote:
//moment("2015-11-30"); //monday 11/30 in UTC
实际上,这将是当地时间 ,而不是UTC.如果要使用UTC,请使用:
Actually, that would be in local time, not UTC. If you wanted UTC, you'd use:
moment.utc("2015-11-30")
尽管我不清楚您是使用此字符串输入还是数字时间戳.
Though it's unclear to me whether you are using this string input or the numeric timestamp.
如果您要问的是希望将UTC日期视为本地日期,然后应用任意本地时间-这是一个有点奇怪的操作,但是会发生以下情况:
If what you are asking is that you want the UTC date to be treated as if it were local and then have an arbitrary local time applied - that is a somewhat strange operation, but it would go something like this:
var tempDate = moment.utc(1448841600000);
var adjustedStart = moment.tz([tempDate.year(), tempDate.month(), tempDate.date(), 9, 30],
"America/Los_Angeles");
console.log("adjustedStart in milliseconds:" + adjustedStart.valueOf());
// adjustedStart in milliseconds:1448904600000
这提供了您所要求的价值,但对我来说-这是一种气味,说明期望有问题.我会仔细研究需求和系统的其他部分.
This gives the value you asked for, but to me - this is a smell that something is wrong with the expectation. I'd look a lot closer at the requirement and the other parts of the system.
这篇关于Momentjs时区-在特定时区的时间获取日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!