Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1187
  • Last Modified:

Javascript date/time adding/subtracting

I know this has been posted before, but I can't seem to find it.  I am doing some adding and subtracting of dates and need to display them on the screen in an HTML format.  If, for example, I have the date

02/03/09 3:15 a.m. and need to subtract 5 hours from it (the number of hours will vary), how can I do this and make sure the date/time are truly a real date and time in the past?
0
saturation
Asked:
saturation
1 Solution
 
HonorGodCommented:
In JavaScript, there is a wonderful thing called a Date object.
You can instantiate it and provide a specific date/time.

For example:

  var when = new Date( '02/03/09 3:15 am' )

This datatype has many methods that can be used for extracting different parts of the date.

For example:



<html>
<body>
 
<script type="text/javascript">
 
var when = new Date( '02/03/09 3:15 am' )
 
function D2( val ) {
  return ( val < 10 ) ? '0' + val : val
}
  
document.write( D2( when.getMonth() + 1 ) + '/' +
                D2( when.getDate() ) + '/' + 
                D2( when.getYear() ) + '<br>'
              )
 
document.write( when + '<br>' )
 
var before = when
before.setHours( before.getHours() - 5 )
 
document.write( D2( before.getMonth() + 1 ) + '/' +
                D2( before.getDate() ) + '/' + 
                D2( before.getYear() ) + '<br>'
              )
              
document.write( before + '<br>' )
 
</script>
 
</body>
</html>

Open in new window

1
 
Richard QuadlingSenior Software DeverloperCommented:
Javascript dates are held as whole days with the decimal part being in milliseconds.1 day = 86 400 000 millisecondsSo, 5 hours = 5 * 60 * 60 * 1000
<html>
<head>
<title>Demo date</title>
<script type="text/javascript">
var o_Date = new Date();
 
alert(o_Date);
 
o_Date.setTime(o_Date - 5 * 60 * 60 * 1000);
 
alert(o_Date);
</script>
</head>
</html>

Open in new window

0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now