Javascript 如何使用 Moment JS 获取时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29454824/
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
How to get time using Moment JS
提问by fatCop
I've two javascript variables: startDateand endDate. I want to store the current time(unix timestamp in ms) to endDateand timestamp of 24 hours before in startDate. I'll use this two variables to query the records for last 1 day. How can I do that using moment JS?
我有两个 javascript 变量:startDate和endDate. 我想将当前时间(以毫秒为单位的 unix 时间戳)存储到endDate24 小时之前的时间戳startDate。我将使用这两个变量来查询过去 1 天的记录。我怎样才能使用moment JS做到这一点?
采纳答案by ThisClark
Have you looked at the website yet? It's full of examples - http://momentjs.com/I think what you are trying to do is as simple as
你看过网站了吗?它充满了例子 - http://momentjs.com/我认为你想要做的很简单
var startDate = moment(endDate).subtract(1, 'days');
Following your question more literally, you can do this:
从字面上看你的问题,你可以这样做:
var endDate = moment(); //the current time
Or, you can just ignore the endDate part of this problem and go straight to startDate with
或者,您可以忽略此问题的 endDate 部分并直接使用 startDate
var startDate = moment().subtract(1, 'days'); //one day before the current time
Finally, if you need to format it a certain way, you can apply a formatting rule such as:
最后,如果您需要以某种方式对其进行格式化,您可以应用一个格式化规则,例如:
moment().subtract(1,'days').format('YYYY-MM-DD h:mm:ss a')
Use format without an argument and it gives you ISO 8601 format
使用没有参数的格式,它为您提供 ISO 8601 格式
moment().subtract(1,'days').format() //eg: "2015-04-04T01:53:26-05:00"
回答by Tim McWilliams
This worked for me although I have never found it in the docs. Should have been published but it works.
这对我有用,尽管我从未在文档中找到它。应该已经发布,但它有效。
Try:
尝试:
moment(currentTime).format("hh:mm"));or
var currentTime = moment();
console.log("CURRENT TIME: " + moment(currentTime).format("hh:mm"));
回答by Farzad Jafarizadeh
I think what you are looking for is something like
我认为你正在寻找的是类似的东西
moment(endDate).unix()
which returns something like: 1435161240
返回类似:1435161240
You can even calculate the time from now using
您甚至可以使用从现在开始计算时间
moment(endDate).fromNow()
which returns something like: "2 days ago"
返回类似:“2天前”
回答by Anil Agrawal
You can directly call function momentInstance.valueOf(), it will return numeric value of time similar to date.getTime()in native java script.
您可以直接调用函数momentInstance.valueOf(),它会返回类似于原生 java 脚本中的date.getTime()的时间数值。

