Home  >  Article  >  Web Front-end  >  Example analysis of comparing two timestamps in JS

Example analysis of comparing two timestamps in JS

黄舟
黄舟Original
2017-10-24 09:36:012291browse

Instance analysis of comparison of two timestamps in JS

<script type="text/javascript" language="javascript">
function TimeDifference()
{
//定义两个变量time1,time2分别保存开始和结束时间
var time1="2009-12-02 12:25";
var time2="2009-12-03 12:35";
//判断开始时间是否大于结束日期
if(time1>time2)
{
   alert("开始时间不能大于结束时间!");
   return false;
}
//截取字符串,得到日期部分"2009-12-02",用split把字符串分隔成数组
var begin1=time1.substr(0,10).split("-");
var end1=time2.substr(0,10).split("-");
//将拆分的数组重新组合,并实例成化新的日期对象
var date1=new Date(begin1[1] + - + begin1[2] + - + begin1[0]);
var date2=new Date(end1[1] + - + end1[2] + - + end1[0]);
//得到两个日期之间的差值m,以分钟为单位
//Math.abs(date2-date1)计算出以毫秒为单位的差值
//Math.abs(date2-date1)/1000得到以秒为单位的差值
//Math.abs(date2-date1)/1000/60得到以分钟为单位的差值
var m=parseInt(Math.abs(date2-date1)/1000/60);
//小时数和分钟数相加得到总的分钟数
//time1.substr(11,2)截取字符串得到时间的小时数
//parseInt(time1.substr(11,2))*60把小时数转化成为分钟
var min1=parseInt(time1.substr(11,2))*60+parseInt(time1.substr(14,2));
var min2=parseInt(time2.substr(11,2))*60+parseInt(time2.substr(14,2));
//两个分钟数相减得到时间部分的差值,以分钟为单位
var n=min2-min1;
//将日期和时间两个部分计算出来的差值相加,即得到两个时间相减后的分钟数
var minutes=m+n;
document.writeln(minutes);
}
TimeDifference();
</script>

var start=1491789600000;//2017-4-10 10:00
var end=1494381600000;//2017-5-10 10:00
var utc=end-start;
   天:utc/(24*60*60*1000);
小时:utc/(60*60*1000);
   分:utc/(60*1000);

JavaScript Get the currentTime stamp:
First method:

var timestamp = Date.parse(new Date());

Result:

1280977330000

Second method:

var timestamp = (new Date()).valueOf();

Result:

1280977330748

Third method:
##

var timestamp=new Date().getTime();

Result:

1280977330748

第一种:获取的时间戳是把毫秒改成000显示,
第二种和第三种是获取了当前毫秒时间戳
转换成毫秒之即可比较时间的大小

The above is the detailed content of Example analysis of comparing two timestamps in JS. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn