Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
413 views
in Technique[技术] by (71.8m points)

javascript - 在JavaScript中2个日期之间有区别吗? [重复](Get difference between 2 dates in JavaScript? [duplicate])

How do I get the difference between 2 dates in full days (I don't want any fractions of a day) (如何获得整天2个日期之间的差额(我不想一天中的任何时间))

var date1 = new Date('7/11/2010');
var date2 = new Date('12/12/2010');
var diffDays = date2.getDate() - date1.getDate(); 
alert(diffDays)

I tried the above but this did not work. (我尝试了上述方法,但这没有用。)

  ask by chobo2 translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is one way : (这是一种方法 :)

const date1 = new Date('7/13/2010');
const date2 = new Date('12/15/2010');
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
console.log(diffDays);

Observe that we need to enclose the date in quotes. (请注意,我们需要将日期用引号引起来。) The rest of the code gets the time difference in milliseconds and then divides to get the number of days. (其余代码获得时差(以毫秒为单位),然后除以天数。) Date expects mm/dd/yyyy format. (日期应采用mm / dd / yyyy格式。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...