Convert Javascript time to MySQL format using PHP

2019-02-27 07:50发布

问题:

How can I convert a js Date (like this Sun Jul 13 2014 07:00:00 GMT+0200 (EET)) to MySQL format (like this 2014-07-13 07:00:00) using php ?

回答1:

Since your date string already contains the time zone, you don't need to do anything special:

$when = new DateTime('Sun Jul 13 2014 07:00:00 GMT+0200 (EET)');
echo $when->format('Y-m-d H:i:s');


回答2:

Javascript: This get this time right now in seconds. Dividing by 1000 gets rid of the milliseconds

var time = new Date().getTime() / 1000

PHP: Use the time returned from JS, the integer value

$time = gmdate('H:i:s', time)


回答3:

<?php
print_r(date_parse("Sun Jul 13 2014 07:00:00 GMT+0200"));
?>


Array
(
[year] => 2014
[month] => 7
[day] => 13
[hour] => 7
[minute] => 0
[second] => 0
[fraction] => 0
[warning_count] => 0
[warnings] => Array
    (
    )

[error_count] => 0
[errors] => Array
    (
    )

[is_localtime] => 1
[zone_type] => 1
[zone] => -120
[is_dst] =>
[relative] => Array
    (
        [year] => 0
        [month] => 0
        [day] => 0
        [hour] => 0
        [minute] => 0
        [second] => 0
        [weekday] => 0
    )

)


回答4:

I will try to enhance @akuzminsky answer a little. Since date_parse is using strtotime internally to parse the date, you can use it directly and make your code more flexible.

There is a small drawback since you need to set the time zone in order to use date correctly and avoid php warning. I am setting it to Europe/Athens but you can find here all available codes.

date_default_timezone_set("Europe/Athens");

$unixTimeStamp = strtotime("Sun Jul 13 2014 07:00:00 GMT+0200 (EET)");
$newFormat = date('Y-m-d H:i:s', $unixTimeStamp );

echo $newFormat;