javascript 仅使用 Moment JS 将 Microsoft JSON 日期转换为本地日期时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30266809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Microsoft JSON Date to Local DateTime Using Moment JS Only
提问by usefulBee
JSON Date: '/Date(1373428800000)/' End Result: 7/9/2013 8:00 PM EST
JSON 日期:'/Date(1373428800000)/' 最终结果:7/9/2013 8:00 PM EST
Currently I do it in 3 steps:
目前我分3步完成:
var a = cleanJsonDate('JsonDate');
var b = formatDate(a); // 7/10/2013 12:00 AM
var c = moment.utc(b); // 7/9/2013 8:00 PM
return c;
Is it possible to accomplish the same result using moment js only?
是否可以仅使用 moment js 来完成相同的结果?
----Update-----
- - 更新 - - -
Combining @ThisClark & @Matt answers. I came as close as possible to the goal; however, the 'h' format does not work for some reason, I still get 20.00.00 instead of 8:00
结合@ThisClark 和@Matt 的回答。我尽可能接近目标;但是,“h”格式由于某种原因不起作用,我仍然得到 20.00.00 而不是 8:00
var m = moment.utc(moment('/Date(1373428800000)/').format('M/D/YYYY h:m A')).toDate();
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>
回答by Matt Johnson-Pint
This format is already supported natively by moment.js. Just pass it directly.
这个格式已经被 moment.js 原生支持。直接传就好了
moment('/Date(1373428800000)/')
You can then use any of the moment functions, such as .format()
or .toDate()
然后您可以使用任何矩函数,例如.format()
或.toDate()
If you want UTC, then do:
如果您想要 UTC,请执行以下操作:
moment.utc('/Date(1373428800000)/')
Again, you can call format
or toDate
, however be aware that toDate
will produce a Date
object, which will still have local time behaviors. Unless you absolutely need a Date
object, then you should stick with format
and other moment functions.
同样,您可以调用format
或toDate
,但请注意,这toDate
将生成一个Date
对象,该对象仍将具有本地时间行为。除非你绝对需要一个Date
对象,否则你应该坚持使用format
和其他矩函数。
回答by ThisClark
I don't see all your code, but if you can just get the value of milliseconds as 1373428800000
out of that json, then you can pass it to moment directly. I think formatDate
is a function you wrote. Does it do something important like manipulate time that you require of moment.js, or could you just use the format function of moment?
我没有看到您的所有代码,但是如果您可以1373428800000
从该 json 中获取毫秒的值,那么您可以将其直接传递给 moment。我想formatDate
是你写的一个函数。它是否做了一些重要的事情,比如你需要的 moment.js 操纵时间,或者你可以只使用 moment 的格式功能?
var date = 1373428800000;
var m = moment.utc(date);
//var m = moment.utc(date).format('M/D/YYYY H:mm A'); <-- alternative format
alert(m);
<script src="http://momentjs.com/downloads/moment.min.js"></script>