Convert date to timestamp in PHP: step-by-step guide
P粉204136428
P粉204136428 2023-10-08 23:03:38
0
1
847

How do I get the timestamp, for example September 22, 2008?

P粉204136428
P粉204136428

reply all(1)
P粉670838735


This method works on Windows and Unix and is time zone aware, which may be what you want if you use date.

If you don't care about time zones, or want to use the time zone your server uses:

$d = DateTime::createFromFormat('d-m-Y H:i:s', '22-09-2008 00:00:00');
if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093324 (This will vary based on your server time zone...)


If you want to specify which time zone, this is EST. (Same as New York.)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('EST')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093305


Or if you want to use UTC. (Same as "GMT".)

$d = DateTime::createFromFormat(
    'd-m-Y H:i:s',
    '22-09-2008 00:00:00',
    new DateTimeZone('UTC')
);

if ($d === false) {
    die("Incorrect date string");
} else {
    echo $d->getTimestamp();
}

1222093289


Regardless, being strict when parsing strings into structured data is always a good starting point. This can save you the embarrassment of debugging in the future. So I recommend always specifying the date format.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template