How do I get timestamp from e.g. 22-09-2008
?
If you know the format use strptime
because strtotime
does a guess for the format, which might not always be correct. Since strptime
is not implemented in Windows there is a custom function
Remember that the returnvalue tm_year
is from 1900! and tm_month
is 0-11
Example:
$a = strptime('22-09-2008', '%d-%m-%Y');
$timestamp = mktime(0, 0, 0, $a['tm_mon']+1, $a['tm_mday'], $a['tm_year']+1900)
If you want to know for sure whether a date gets parsed into something you expect, you can use DateTime::createFromFormat()
:
$d = DateTime::createFromFormat('d-m-Y', '22-09-2008');
if ($d === false) {
die("Woah, that date doesn't look right!");
}
echo $d->format('Y-m-d'), PHP_EOL;
// prints 2008-09-22
It's obvious in this case, but e.g. 03-04-2008
could be 3rd of April or 4th of March depending on where you come from :)
Please be careful about time/zone if you set it to save dates in database, as I got an issue when I compared dates from mysql that converted to timestamp
using strtotime
. you must use exactly same time/zone before converting date to timestamp otherwise, strtotime() will use default server timezone.
Please see this example: https://3v4l.org/BRlmV
function getthistime($type, $modify = null) {
$now = new DateTime(null, new DateTimeZone('Asia/Baghdad'));
if($modify) {
$now->modify($modify);
}
if(!isset($type) || $type == 'datetime') {
return $now->format('Y-m-d H:i:s');
}
if($type == 'time') {
return $now->format('H:i:s');
}
if($type == 'timestamp') {
return $now->getTimestamp();
}
}
function timestampfromdate($date) {
return DateTime::createFromFormat('Y-m-d H:i:s', $date, new DateTimeZone('Asia/Baghdad'))->getTimestamp();
}
echo getthistime('timestamp')."--".
timestampfromdate(getthistime('datetime'))."--".
strtotime(getthistime('datetime'));
//getthistime('timestamp') == timestampfromdate(getthistime('datetime')) (true)
//getthistime('timestamp') == strtotime(getthistime('datetime')) (false)
$time = '22-09-2008';
echo strtotime($time);
Here is a very simple and effective solution using the split
and mtime
functions:
$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date);
//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);
It worked like a charm for me.
Use PHP function strtotime()
echo strtotime('2019/06/06');
date — Format a local time/date