Steini
Steini

Reputation: 2783

Mysql DATETIME to unix timestamp JavaScript / JQuery

Heya heres a (hopefully) easy one,

how can I convert this DATETIME value:

2014-01-16 12:00:00

to an unix timestamp via JavaScript or JQuery?

In PHP It is easy but in JavaScript it seems hard. I found out that Date.parse() or new Date() provide me that but this only helps with timestamps containing this other format with day of the week.

Is there a way to convert this 'numeric' variant aswell?

Thanks in advance~

Upvotes: 1

Views: 8342

Answers (4)

xdazz
xdazz

Reputation: 160903

You could do this, but note 2014-01-16 12:00:00 is the local time of the machine.

var ts = new Date('2014-01-16 12:00:00').getTime() / 1000;

Update:

As @devnull69 said, Firefox only accepts the ISO format, you have to replace the space to T.

Upvotes: 3

devnull69
devnull69

Reputation: 16574

In order to convert this string to a Javascript date format, you need to replace the space character between date and time with the character T in order to create a valid ISO8601 format. Then you can use .getTime() for the unix timestamp of this date.

var timestamp = new Date('2014-01-16 12:00:00'.replace(' ', 'T')).getTime();

Upvotes: 12

Karthick Kumar
Karthick Kumar

Reputation: 2361

        <script>
        function test(date){
            n=date;
            var d=new Date(n).getTime() / 1000
            console.log(d);
        }
        </script>
        <body onLoad="test('2014-01-16 12:00:00')">
        </body>

Upvotes: 0

Butt4cak3
Butt4cak3

Reputation: 2429

Date.prototype.getTime returns a unix timestamp in milliseconds. If you want it in seconds, divide it by 1000.

function mysql_to_unix(date) {
    return Math.floor(new Date(date).getTime() / 1000);
}

mysql_to_unix("2014-01-16 12:00:00"); // returns 1389870000

Upvotes: 0

Related Questions