Web Development - The Trick To Comparing A Hard-Coded Date With A JavaScript System Date


Granted, much of JavaScript's date complexity results from its need to use GMT date formats, but even so, manipulating dates in JavaScript can often be somewhat difficult. Comparing a hard-coded date with a system date provides a perfect example of this.


For instance, suppose you have a website that needs to compare today's date with a stored date--the visitor's birthday, for instance. Unfortunately, you can't simply convert the hard-coded date into a JavaScript date and compare it to the value returned by:


  • var today = new Date()
  • var bday = new Date("5/15/2005")
  • document.write (today==bday)

That's because the today object also contains the time at which you created the variable, whereas your hard-coded date won't have a time value.


To accommodate this difference in formats, you can break down the system-generated date into its relevant components, like so:


  • var d = new Date() //Get today's date
  • var today = new Date((d.getMonth() +1) + "/" + d.getDate() + "/"
  • + d.getFullYear())

Unfortunately, for some reason, you still won't be able to compare the two dates. Instead, you'll need to further convert the dates to their millisecond equivalents, as seen in the following code:


  • <html>
  • <head>
  • </head>
  • <body>
  • <h1>
  • <script type="text/javascript">
  • var d = new Date() //Get today's date
  • var today = new Date((d.getMonth() +1) + "/" + d.getDate() + "/"
  • + d.getFullYear())
  • var bday = new Date("5/15/2005") // Hard-coded date goes here
  • document.write(today + "<br>")
  • document.write(bday + "<br>")
  • document.write((today==bday) + "<br>")
  • document.write(Date.parse(today)==Date.parse(bday))
  • </script>
  • </h1>
  • </body>
  • </html>

Go back