简体   繁体   English

使用MomentJS将字符串转换为Javascript中的Timestamp

[英]Convert string to Timestamp in Javascript using MomentJS

I have a string like : 我有一个字符串:

var from = '2016-06-06T21:03:55' ;

Now how do I convert it into a timestamp such that I can give it as an input to momentjs. 现在我如何将其转换为时间戳,以便我可以将其作为momentjs的输入。 Basically, I want to find the difference in the timestamps as seen in this post : Get hours difference between two dates in Moment Js 基本上,我想找到时间戳中的差异,如本文所示: 在Moment Js中获取两个日期之间的小时差异

Look at the last answer in the above post. 看看上面帖子中的最后一个答案。

Please please help em out. 请帮帮忙吧。 I am stck on it since hours now. 从现在开始几个小时我就开始了。

Pass this variable to the moment ctor. 将此变量传递给ctor。

var from = '2016-06-06T21:03:55' ;
var a = moment('2016-06-06T22:03:55');
var b = moment(from);

console.log(a.diff(b, 'minutes')); //60
console.log(a.diff(b, 'hours')); //1
console.log(a.diff(b, 'days')); //0 
console.log(a.diff(b, 'weeks')); //0

Or you can use the format method to see the value fo the moment variables, like : 或者您可以使用format方法查看时刻变量的值,例如:

b.format('DD/MM/YYYY hh:mm:ss'); // 06/06/2016 09:03:55
b.format(); // 2016-06-06T21:03:55+10:00

Option 1 选项1

You can initialize a Date object and call getTime() to get it in Unix form. 您可以初始化Date对象并调用getTime()以Unix格式获取它。 It comes out in milliseconds so you'll need to divide by 1000 to get it in seconds. 它以毫秒为单位,因此您需要除以1000才能在几秒钟内得到它。

(new Date("2016/06/06 21:03:55").getTime()/1000)

It may have decimal bits so wrapping it in Math.round would clean that. 它可能有十进制位,因此将其包装在Math.round会清除它。

Math.round(new Date("2016/06/06 21:03:55").getTime()/1000)

Demo: https://jsfiddle.net/nanilab/0jpxu30z/ 演示: https//jsfiddle.net/nanilab/0jpxu30z/

Option 2 选项2

The Date.parse() method parses a string representation of a date, and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (eg 2015-02-31). Date.parse()方法解析日期的字符串表示形式,并返回自1970年1月1日00:00:00 UTC或NaN后的毫秒数(如果字符串无法识别,或者在某些情况下包含非法日期值) (例如2015-02-31)。

var input = "2016-06-06 21:03:55";
input = input.split(" - ").map(function (date){
    return Date.parse(date+"-0500")/1000;
}).join(" - ");

Demo: https://jsfiddle.net/nanilab/cweq2q0q/ 演示: https//jsfiddle.net/nanilab/cweq2q0q/

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM