Moment.js local relative time

牧云@^-^@ 提交于 2020-01-07 05:29:11

问题


I have dates in my database set to Europe/London time. I am using Moment.js to show relative time e.g. "3 minutes ago". This works fine for me as I am in the same timezone, but for example, someone who is PST timezone would see "in 8 hours". How can I fix this?

My current code is like this:

$('time').text( moment( '2016-01-22 18:00:00' ).fromNow() );


回答1:


To echo Jon's answer, moment's relative time functionality is strictly UTC based, so the behavior you describe won't actually happen, unless you are interpreting the original timestamp in local time.

It's hard to say if you're doing that or not, as you didn't give a sample value of the input string.

If your times are indeed UTC based, but that's not reflected in the input string, then use moment.utc instead of just moment.

And no, London is not the same as UTC.




回答2:


I believe that the best approach is to store the date in UTC and then convert this to the local time zone for display. Note that this is not necessarily the same as London time because UTC does away with daylight savings time nonsense. You can do everything that you need with the date class provided the time stamp stored in the database does not have to deal with the vagaries of time zone and DST. The date class maintains its own epoch internally as milliseconds elapsed since midnight 1 January 1970 UTC. You can evaluate the difference between two Date objects as follows:

var agora = Date.now();
var stored = ... // the date that was stored in your database
var diff_msec = agora.getTime() - stored.getTime();

Knowing that the difference and that its units are milliseconds, you can convert the difference to whatever units are best for presentation.



来源:https://stackoverflow.com/questions/34951990/moment-js-local-relative-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!