Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert date dd/mm/yyyy format from a form to timestamp?

I have a form requiring date in dd/mm/yyyy format and I've tried to convert it to a timestamp with strtotime() function

but I've seen it works only if you fill the form with date written like dd-mm-yyyy

how could i solve? I don't know abroad but here in Italy nobody writes dates like that dd-mm-yyyy

like image 237
GabAntonelli Avatar asked Sep 12 '13 09:09

GabAntonelli


1 Answers

Stop using strotime(), date(), time() etc. functions, start using DateTime.

Perfect solution for all types of known input :

$dt = DateTime::createFromFormat('d/m/Y', $yourDMYinput);
echo $dt->getTimestamp(); # or $dt->format('U');

And why do you need timestamp for?

Why explode, replace or even cut string??? Just use createFromFormat.

Q1: Because its not supported below PHP 5.3.

There is v5.5 already out. I think answers should be for the latest code, not for code from the year 2006. Yes v5.2 was released in 2006 and v5.3 in 2009 (see release dates). If OP requests old code, find it on SO, and close this question with duplicate; don't answer it.

Q2: Because I don't know DateTime.

Learn it.

Q3: Because I can do more with strotime(), date(), time() etc.

Show me one thing that this functions can do, and DateTime cannot.

"Deprecated" code examples :

$input = '12/09/2013'; # dd/mm/yyyy

$new = substr($input,6,4)."-".substr($input,3,2)."-".substr($input,0,2);
$new = strtotime($new);
echo "$new\n";

$m = explode('/', $input);
$new = mktime(0,0,0,$m[1],$m[0],$m[2]);
echo "$new\n";

$new = str_replace("/", "-", $input);
$new = strtotime($new);
echo "$new\n";

preg_match('~^(\d+)/(\d+)/(\d+)$~', $input, $m);
$new = strtotime("$m[3]-$m[2]-$m[1]");
echo "$new\n";

$m = sscanf($input, '%d/%d/%d');
$new = strtotime("$m[2]-$m[1]-$m[0]");
echo "$new\n";

If you have another example of deprecated code, edit this answer and add it ;)

like image 80
Glavić Avatar answered Oct 05 '22 23:10

Glavić