可以直接相减,获得的结果就是两个时间之间相差的毫秒数,然后可以再从中计算获得相差的年月日时分秒来。
比如下面的代码是获得今年(2018年)剩余的天数:
var d1=new Date()var d2=new Date(2019,0,1)
var d=parseInt((d2-d1)/1000/3600/24)
console.log("2018年剩余的天数为"+d+"天")
js中没有如同C#中的AddDays的方法,所以重写了Date对象的prototype,扩展了增加日期的方法,
代码如下:
Date.prototype.Format = function(fmt)
{
//author:
meizz
var o
=
{
"M+" : this.getMonth() + 1, //月份
"d+" : this.getDate(), //日
"h+" : this.getHours(), //小时
"m+" : this.getMinutes(), //分
"s+" : this.getSeconds(), //秒
"q+" : Math.floor((this.getMonth() + 3) / 3), //季度
"S" : this.getMilliseconds() //毫秒
}
if
(/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 -
RegExp.$1.length))
for (var k
in o)
if (new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) :
(("00" + o[k]).substr(("" + o[k]).length)))
return
fmt
}
Date.prototype.addDays = function(d)
{
this.setDate(this.getDate() + d)
}
Date.prototype.addWeeks = function(w)
{
this.addDays(w * 7)
}
Date.prototype.addMonths= function(m)
{
var d =
this.getDate()
this.setMonth(this.getMonth() + m)
if
(this.getDate() <d)
this.setDate(0)
}
Date.prototype.addYears = function(y)
{
var m =
this.getMonth()
this.setFullYear(this.getFullYear() + y)
if (m
<this.getMonth())
{
this.setDate(0)
}
}
var now = new Date()
now.addDays(1)//加减日期操作
alert(now.Format("yyyy-MM-dd"))
“javascript”把日期减一天,可以按照下面的进行改动:
方法一:var today=new Date();
var t=d.getTime()-1000*60*60*24;
var yesterday=new Date(t);
alert(t);
方法二:var myDate = new Date();
alert(myDate);
var date = myDate.getDate();
date = date - 1;
myDate.setDate(date);
alert(myDate);
JavaScript一种直译式脚本语言,是一种动态类型、弱类型、基于原型的语言,内置支持类型。它的解释器被称为JavaScript引擎,为浏览器的一部分,广泛用于客户端的脚本语言,最早是在HTML(标准通用标记语言下的一个应用)网页上使用,用来给HTML网页增加动态功能。