最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - How to read timestamp and how to subtract two timestamps? - Stack Overflow

matteradmin3PV0评论

I have the following code to get (timestamp) and (NOW timestamp). I subtract them to get the difference between them but I get a number like 123456 and I can not understand how much this number represent. I want to check if the difference between those two dates are less than one hour, how?

final_time = new Date(2013, 11, 11, 11, 11);
c_date = new Date();
offset_time = c_date.getTimezoneOffset();
var n1 = Math.abs(offset_time);
current_date = new Date(c_date.getTime() - n1 * 60 * 1000);

alert(current_date-final_time);

I have the following code to get (timestamp) and (NOW timestamp). I subtract them to get the difference between them but I get a number like 123456 and I can not understand how much this number represent. I want to check if the difference between those two dates are less than one hour, how?

final_time = new Date(2013, 11, 11, 11, 11);
c_date = new Date();
offset_time = c_date.getTimezoneOffset();
var n1 = Math.abs(offset_time);
current_date = new Date(c_date.getTime() - n1 * 60 * 1000);

alert(current_date-final_time);
Share Improve this question asked Nov 11, 2013 at 10:00 BaselBasel 1,3759 gold badges25 silver badges34 bronze badges 1
  • running your code gives ...2598440754 milis is 721 hours. (if swapping over the subtration at the end to give a positive number, c_date.getTime() - final_time.getTime()). Just take that and work out if that is greater than '60 * 60 * 1000'. Just see 'codebox's answer below, its more eloquent than my ment. – jeff porter Commented Nov 11, 2013 at 10:16
Add a ment  | 

2 Answers 2

Reset to default 8

You can get the difference between the two dates in milliseconds if you do:

var diffInMillis = c_date.getTime() - final_time.getTime()

To find out if this is less than 1 hour you can do this:

var isLessThan1Hour = diffInMillis < 60 * 60 * 1000;

Instead of directly subtracting the timestamps try to diff the dates from which you can individually get hours.From then on one can do a simple maths to do the difference.

That's a more clear and maintainable approach

Post a comment

comment list (0)

  1. No comments so far