convert date dd/mm/yyyy format from a form to time

2020-07-14 05:11发布

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

4条回答
老娘就宠你
2楼-- · 2020-07-14 05:20

Why not use str_replace?

$timestamp = strtotime(str_replace("/", "-", $dateString));

Or better yet, convert the string into YYYY-MM-DD before you insert.

查看更多
Juvenile、少年°
3楼-- · 2020-07-14 05:26

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 ;)

查看更多
ら.Afraid
4楼-- · 2020-07-14 05:30

Quite lengthy.

$get_array = explode('/', 'dd/mm/yyyy');

$day = $get_array[0];
$month = $get_array[1];
$year = $get_array[2];
$time_Stamp = mktime(0,0,0,$month,$day,$year);
查看更多
狗以群分
5楼-- · 2020-07-14 05:33

Your question is not very clear.

If you receive from a form the date in format "dd/mm/yyyy" and you need to convert it in "yyyy-mm-dd" you can simply use substr:

$date_eng=substr($data_ita,6,4)."-".substr($data_ita,3,2)."-".substr($data_ita,0,2);

and

$data_ita=substr($date_eng,8,2)."/".substr($date_eng,5,2)."/".substr($date_eng,0,4);
查看更多
登录 后发表回答