最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get hours in moment.js in GMT timezone? - Stack Overflow

programmeradmin4浏览0评论

For example if I do for the above date object something like: value.hours(), I get as output 16 instead of 18. I believe it returns the hours in the original GMT time, not like in my date object which is GMT+2. I can of course add 2 to the returned result, but it bees cumbersome. Is there any way to get the hours correctly in my case?

For example if I do for the above date object something like: value.hours(), I get as output 16 instead of 18. I believe it returns the hours in the original GMT time, not like in my date object which is GMT+2. I can of course add 2 to the returned result, but it bees cumbersome. Is there any way to get the hours correctly in my case?

Share Improve this question edited Dec 21, 2017 at 15:21 Brad Larson 170k45 gold badges400 silver badges572 bronze badges asked Oct 6, 2017 at 13:10 typostypos 6,67215 gold badges42 silver badges55 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 1

I'm not sure as to what you've already tried, but I put the following into JSFiddle and it worked like a charm. I am currently in CST in America and it is 8:30 in the morning here. When I ran the snippet below I got today's date at 1:30 PM which I would assume is accurate in difference.

HTML

<div id="m1"></div>

JavaScript

var a = moment.tz(new Date(), "GMT");
document.getElementById('m1').innerHTML = a.format("YYYY MM DD; HH:mm");

The Moment.js documentation states the following in regards to creating a Moment object with a native JavaScript Date object:

You can create a Moment with a pre-existing native JavaScript Date object.

var day = new Date(2011, 9, 16);
var dayWrapper = moment(day);

This clones the Date object; further changes to the Date won't affect the Moment, and vice-versa.

To find the information quoted above quickly, when you reach the Moment.js documentation, it is located under the Parse section under sub-section Date.

To display local time:

value.local();
value.hours(); // 18

To reverse:

value.utc();
value.hours(); // 16

I think that you can solve it by doing what the docs says. Something like this:

moment().tz("America/Los_Angeles").format();

https://momentjs./timezone/docs/#/using-timezones/

I guess maybe this works

var localDateString = new Date("GMT-DATETIME").toLocaleString(); 
//Converting GMT date to your local datetime in string


var localHours = new Date(localDateString).getHours();
发布评论

评论列表(0)

  1. 暂无评论