-1

Hi I am struggling with converting a string:

$file = '150220';

into a mysql date format.

I have tried this

$newDate = date("Y-m-d", strtotime($file));

But it returns the following 2015-02-24 (24 being today's date)

Tim S.
  • 13,597
  • 7
  • 46
  • 72
user1479891
  • 139
  • 1
  • 2
  • 15

2 Answers2

5

See: http://php.net/manual/en/datetime.createfromformat.php

So you can use this:

$dateTime = DateTime::createFromFormat('ymd', $file);
$newDate = $dateTime->format('Y-m-d');
Blaatpraat
  • 2,829
  • 11
  • 23
1

strtotime is a wonderful function. It works when you provide YYYY-MM-DD format but not with YY-MM-DD.

EDIT: As said in comments, you have to "turn the string into a valid ISO8601 Notations format by prepending '20' - this is understood by strtotime as specified in the docs "

This will work for the next 85 years with 64 bits systems (Until 2038 on 32 bit systems)

$file = '150220';
$newDate = date("Y-m-d", strtotime("20$file"));

You have to be careful with strtotime because it returns false on error which will make date used today's date.

EDIT: if you want to -1 : first, this code works and it explains why op's code does not work, then consider using the "Add comment" button. Thanks.

Adam
  • 17,838
  • 32
  • 54
  • 150220 its a date in format of ymd . so how strtotime gonna know that? – Nabin Kunwar Feb 24 '15 at 11:01
  • strtotime is a wonderful function. It works when you provide YYYY-MM-DD format but not with YY-MM-DD. – Adam Feb 24 '15 at 11:03
  • so care to explain why is there 20 before $file? and does this code work for 150324 too? does it really answers what op asked for? – Nabin Kunwar Feb 24 '15 at 11:06
  • 20th february of 2015 is "20150220" in YYYY-MM-DD format, you have to put the century in order for it to work – Adam Feb 24 '15 at 11:09
  • Mark could you explain what you are saying? – Adam Feb 24 '15 at 11:10
  • @Adam - he's referring to the fact that 32 bit dates can't go past 2038 - see second note on [PHP strtotime documentation](http://php.net/manual/en/function.strtotime.php). You should explain that you're turning the string into a valid ISO8601 Notations format by prepending '20' - this is understood by strtotime as specified in the docs (http://php.net/manual/en/datetime.formats.date.php) – J Richard Snape Feb 24 '15 at 11:38
  • Yes thanks, i will modify my answer as you suggest. People don't seem to understand such thing. – Adam Feb 24 '15 at 11:47