Two functions to convert date

MitkOK 0 Tallied Votes 219 Views Share

Hello.

I know that there are many ways to convert date in PHP, but i use those to two convert from/to MySQL DB.

// this function convert date from YYYY-MM-DD to DD-MM-YYYY in order to use in HTML table for example

function mysql2table($date) {
 	
          $new = explode("-",$date);
          $a=array ($new[2], $new[1], $new[0]);

          return $n_date=implode("-", $a);
 }
 
// this function convert date from DD-MM-YYYY to YYYY-MM-DD in order to use in MySQL table in DATE format for example

 function table2mysql($year,$month,$day) {

         if ($day<=9) { $day="0".$day; }
         if ($month<=9) { $month="0".$month; }
         $a=array ($year, $month, $year);

         return $n_date=implode("-", $a);
 }

Dani AI

Generated

Nice, simple helpers from — they show the idea clearly. A couple of practical notes that improve correctness and robustness.

First: the second function has a bug (it builds year, month, year instead of year, month, day). Change the third element to the day value, and validate the parts before assembling. Relying on string explode/implode works only when the input is exactly the expected format.

A safer, recommended approach is to use PHP's DateTime parsing/formatting so input is strictly validated and ambiguous strings are avoided (this sidesteps the potential ambiguity of strtotime, which mentioned). Example conversion helpers using DateTime and error checks:

function mysqlToTable($date) {
    $dt = DateTime::createFromFormat('Y-m-d', $date);
    $err = DateTime::getLastErrors();
    if ($dt === false || $err['error_count'] || $err['warning_count']) return false;
    return $dt->format('d-m-Y');
}

function tableToMySQL($date) {
    $dt = DateTime::createFromFormat('d-m-Y', $date);
    $err = DateTime::getLastErrors();
    if ($dt === false || $err['error_count'] || $err['warning_count']) return false;
    return $dt->format('Y-m-d');
}

If you build a date from separate numeric fields, validate with checkdate() and zero-pad with sprintf to guarantee YYYY-MM-DD. If formatting is only for display, offload it to the database with DATE_FORMAT (as suggested) to avoid repeating formatting in PHP. Finally, always validate user input and use prepared statements when inserting formatted dates into MySQL.

jishu 0 Newbie Poster

you have any idea where i learn PHP first time?
I have only HTML idea

Ginetta 0 Newbie Poster

You could use the date format at the data source... when you run the sql query:

SELECT date_format(date_column, '%M %D, %Y') as date FROM table;

asimshahiddIT 0 Newbie Poster

<?php
$0
$new_date=date("Y-m-d",strtotime($old_date));
?>
please the format to any format

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.