Jump to content

convert date into seconds with javascript


tastro

Recommended Posts

this one doesn't work. :S

 

with this:

 

<script type="text/javascript">
/*year/month/date*/
var test = new Date(1995,11,17);
document.write(test);
</script>

 

i get this:

 

Sun Dec 17 1995 00:00:00 GMT+0100 (Central Europe Standard Time)

 

but i need the outcome time in seconds.

 

by seconds i mean UNIX timestamp.

By using the object in a string context (document.write()) you're invoking the toString() method automatically. You need to call getTime() to get the milliseconds since the UNIX epoch:

 

document.write(test.getTime());

 

Also if you want the time in seconds, you need to divide it by 1000:

 

document.write(test.getTime() / 1000);

 

Edit: I originally said multiply, it's divide, of course :)

yes exactly that's the unix timestamp.

 

sry for the reply before... i didn't even see that you already provided the answer to me. thanks mate! it's working perfect!

 

<script type="text/javascript">
//year/month/date
var time_then = new Date(1995,11,17);
document.write(time_then.getTime());

var time_now = new Date();  
document.write('<br /> '+time_now.getTime());
</script>

 

one more thing... i'm new to javascript, but i'm pretty good at php (i think)

 

how should i write variables in my code?

 

like this:

 

var time_now = new Date();

var time_now = time_now.getTime();

 

like this:

 

var time_now = new Date();

time_now = time_now.getTime();

 

or like this?

 

time_now = new Date();

time_now = time_now.getTime();

Great stuff! It's just basic math really, once you've get the millisecond difference between the two dates. Also to answer your second question, you only need to declare the variable once with var, after that you can just redefine it like in your second example. One thing to note about JS compared with PHP is that variables declared in the global scope are automatically available within functions, unless you declare a local copy with var.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.