How to get strtotime() to recognise dd/mm/yy?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • code green
    Recognized Expert Top Contributor
    • Mar 2007
    • 1726

    How to get strtotime() to recognise dd/mm/yy?

    I am reading a CSV file with dates in non-US format:
    $date = 25/10/2010 19:34
    which should to write to MySQL as 2010-10-25. The time element is not important.
    I have only just noticed (after a couple of months) that $tmstmp = strtotime($date )
    is returning false because strtotime expects a US style date.

    Is there anybody that knows a way around this? I am suprised I have never encountered this problem so far.
    I can only think of string manipulation to re-order the date format.
  • dlite922
    Recognized Expert Top Contributor
    • Dec 2007
    • 1586

    #2
    I think there's just no way. I believe it's built in to PHP. I'm not sure even if setting the region will influence it at all either, you can try it.

    IMO string manipulation is your best reliable bet.

    Here's one I did all on one line, quite inefficiently might I add.

    Code:
    
    $date = "25/10/2010 19:34";
    
    $ts = strtotime(
        end(explode('/',current(explode(' ',$date,2)),3)).'/'.
        next(explode('/',current(explode(' ',$date,2)),3)).'/'.
        current(explode('/',current(explode(' ',$date,2)),3)).' '.
        end(explode(' ',$date,2)));
    
    echo date("r",$ts);
    That's definitely the wrong way to do it, but it's a challenge to anybody else to see who can do it on one line.

    Dan

    Comment

    • code green
      Recognized Expert Top Contributor
      • Mar 2007
      • 1726

      #3
      Thanks for your reply Dan. It is nice to know the whole world has to kowtow to the US way of writing the date wrong.
      Anyway, I worked on it yesterday and got it down to two lines of string manipulation
      Code:
      list($dd,$mm,$yy) = explode('/',$date);
      $date = sprintf('%s/%s/%s',$mm,$dd,$yy);
      I 'borrowed' the list() idea from another site but sprintf was mine.
      I did set about writing a generic function, something like
      Code:
      function formatDate(string $oldformat, string $newformat, string date, string delimiter)
      But it quickly grew in size due to the permutations and whether a time element was involved

      Comment

      Working...