0

I have a date string of the format dd-mm-yyyy hr:min:sec (time in 24 hour format). How do I convert this string into unix time. I know in php if I write time() gives me unixtime. I am trying to achieve the same result from the date string using javascript.

    var expTime = document.getElementById("expiryDT").value; 
    //the value inside this element is the date with (dd-mm-yyyy hr:min:sec) format.
var todayUnixTime = Math.round(+new Date()/1000);
//this gives me the unixtime in seconds for today, ready to pass into php

How do I convert the string expTime into a unixtime in javascript, so that I can pass it to php;

var expTime = String(document.getElementById("expiryDT").value);

http://jsfiddle.net/N4T5h/2/

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
JINSOUL
  • 35
  • 3
  • 10

5 Answers5

2

The problem is that Date doesn't recognize your date format (dd-mm-yyyy hr:min:sec). Use a valid RFC2822 or ISO 8601 date format, or use the other form of the Date constructor that takes numeric arguments:

new Date(year, month [, day, hour, minute, second, millisecond])

http://jsfiddle.net/N4T5h/3/

Dagg Nabbit
  • 75,346
  • 19
  • 113
  • 141
1

Jinsoul you're right there is an error on format try this instead: https://stackoverflow.com/a/20570223/1717821

Community
  • 1
  • 1
cumanacr
  • 308
  • 3
  • 8
0

var unixTime = Math.round(new Date('January 21,2013 23:14:12').getTime()/1000);

StackSlave
  • 10,613
  • 2
  • 18
  • 35
-1

Try:

 var someDate = new Date(Date.parse(expTime));
DigCamara
  • 5,540
  • 4
  • 36
  • 47
Cedric Ipkiss
  • 5,662
  • 2
  • 43
  • 72
-1

use getTime() method here is a demo: http://jsfiddle.net/nn007/N4T5h/

Noampz
  • 1,185
  • 3
  • 11
  • 19
  • Your fiddle makes sense and I know it is working but for some damn reason when I use the code and try to alert it is saying invalid date `var expTime = String(document.getElementById("expiryDT").value); alert(expTime); // alerts proper date which is inside the field. expTime = new Date(expTime); alert(expTime); //alerts invalid Date ` – JINSOUL Nov 29 '13 at 23:15
  • that is because javascript Date support "mm-dd-yyyy hr:min:sec" and not dd-mm-yyyy hr:min:sec. so you have to do something like this: http://jsfiddle.net/nn007/N4T5h/4/ – Noampz Nov 29 '13 at 23:58