how to convert string of format dd/mm/yy to mysql date form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
barbiee
Forum Newbie
Posts: 3
Joined: Wed Feb 19, 2014 6:04 am

how to convert string of format dd/mm/yy to mysql date form

Post by barbiee »

hi..i'm writing a program to load a csv file to mysql. in that csv file there is a date field which contains value of the form : dd/mm/yy H:i,that is 24/01/13 14:58. how can i convert that to mysql date format yyyy-mm-dd. no time is needed.. i tried different functions like:
1) strtotime
2)Datetime:createFromFormat
3)date_format
,but nothing helped.maybe i used them in a wrong way. can anyone please help me to do this. Thanks in advance.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: how to convert string of format dd/mm/yy to mysql date f

Post by Celauran »

The problem here is the two-character year. 24/01/2013 works fine. 24/01/13 not so much. Best bet at this point is probably to tokenize the string, add the leading '20' and rearrange the tokens. Alternately, you could do a regex replace to insert the '20' after the second slash and then parse with DateTime or strtotime.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Re: how to convert string of format dd/mm/yy to mysql date f

Post by Weirdan »

Code: Select all

date_default_timezone_set("Europe/Kiev");
$str = "24/01/13 14:58";
var_dump(DateTime::createFromFormat('d/m/y H:i', $str)->format('Y-m-d')); // string(10) "2013-01-24"
Works for me just fine. Do you get any errors?
barbiee
Forum Newbie
Posts: 3
Joined: Wed Feb 19, 2014 6:04 am

Re: how to convert string of format dd/mm/yy to mysql date f

Post by barbiee »

@Weirdan: thanks friend that worked well... :) (y)

@celauran: thanks friend for helping me.. :)
Post Reply