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
617 views
in Technique[技术] by (71.8m points)

date - Work with a time span in Javascript

Using Date.js already, but can also use another library if necessary.

Not sure what is the best way to work with time deltas. Specifically, I want to display the time that has elapsed between now and a past date-time.

So I need to do something like this:

var elapsed_time = new Date() - pastDate;
pastDate.toString('days-hours-minutes-seconds');

Gotten it to mostly work using Date.js, but the problem is now I'm working with a Date object and not a timespan, so what should be an 23 hour time span is instead 23 hours after the Date's very first time:

var result = (new Date()) - past_date;
"result" is the number (probably milliseconds): 15452732
var result = (new Date() - past_date
"result" is a date from 1969: Wed Dec 31 1969 23:17:32

What I need is:

0 days 23 hours 17 minutes and 32 seconds

Any ideas?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Sounds like you need moment.js

e.g.

moment().subtract('days', 6).calendar();

=> last Sunday at 8:23 PM

moment().startOf('hour').fromNow();

=> 26 minutes ago

Edit:

Pure JS date diff calculation:

var date1 = new Date("7/Nov/2012 20:30:00");
var date2 = new Date("20/Nov/2012 19:15:00");

var diff = date2.getTime() - date1.getTime();

var days = Math.floor(diff / (1000 * 60 * 60 * 24));
diff -=  days * (1000 * 60 * 60 * 24);

var hours = Math.floor(diff / (1000 * 60 * 60));
diff -= hours * (1000 * 60 * 60);

var mins = Math.floor(diff / (1000 * 60));
diff -= mins * (1000 * 60);

var seconds = Math.floor(diff / (1000));
diff -= seconds * (1000);

document.write(days + " days, " + hours + " hours, " + mins + " minutes, " + seconds + " seconds");

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

...