Format date (with different input) php

249 views Asked by At

I am working on a multilingual formular and have to solve a date formatting problem:

In German the date format is: DD-MM-YYYY While in another country e.g. England the date format is: YYYY-MM-DD

While this input validation is handled right, I need to get a easy solution for my php script to handle different date formats. In my MySQL-Database the field is created as a "date" field.

I already thought about a function like this:

<? 
if($lang == "de") {
   $date = $_POST['date'];
   $toConvert = DateTime::createFromFormat('d-m-Y', $date);
   $convertedDate = $toConvert->format('Y-m-d');
}

But isn't there a simpler solution as checking all countries with a different time format than Y-m-d? Maybe a library or something? I haven't found anyhting ..

Best regards DB-Dzine

1

There are 1 answers

1
Kasper Sanguesa-Franz On BEST ANSWER

I know that Zend has some of this logic in there zend_date (requires Zend Framework ^^), but I would just use a simple solution like this: (where you get the format from a switch statement)

 $date = $_POST['date'];
 $toConvert = DateTime::createFromFormat('d-m-Y', $date);

 switch($lang){
    case 'de': 
       $format = 'Y-m-d'; 
       break;
    default: 
       $format = 'd-m-Y'; 
       break 
 }

 $convertedDate = $toConvert->format($format);

By doing it by yourself, you know that the format you get is the right one (by your standard, and that isn't destroying something in your application)