14
Jul

Using a Unix time stamp, or POSIX time stamp is a quick and fast way to represent a point in them. A Unix time stamp returns the number of seconds since the Unix epoch, January 1, 1970; however, it does not count leap seconds.

To create a Unix time stamp function exactly like the one in PHP, you first have to realize that JavaScript calculates to the millisecond instead of just the second. Obviously, you can either divide by 1000 or take the first ten characters of the substring.

The following function excepts an optional date object as a parameter and returns a Unix time stamp equivalent to the one PHPs time() function would return:

  • 1.
  • function getUnixTimestamp(timeObj)
  • 2.
  •  {
  • 3.
  •   var dateObj = null;
  • 4.
  •  
  • 5.
  •   if (timeObj != null)
  • 6.
  •    {
  • 7.
  •     dateObj = new Date(timeObj);
  • 8.
  •    }
  • 9.
  •  
  • 10.
  •   else
  • 11.
  •    {
  • 12.
  •     dateObj = new Date();
  • 13.
  •    }
  • 14.
  •  
  • 15.
  •   return (parseInt(dateObj.getTime().toString().substring(0, 10)));
  • 16.
  •   // alternatively, the following can be used:
  • 17.
  •   // return (parseInt(dateObj.getTime() / 1000));
  • 18.
  •  }

This function, while extremely basic, will prove to be useful in the next blog post where I will show you how to calculate relative times similar to Twitter and Digg. ex: "1 day 23 hours ago" or "10 minutes 3 seconds ago".

name:
e-mail:
website:
comment:
creativecommons.org by-nc-nd
© chaoscoding 2008