Convert one date format into another in PHP

    |
  • Added:
  • |
  • In: Basic PHP

Is there a simple way to convert one date format into another date format in PHP?

I have this:

$old_date = date('y-m-d-h-i-s'); // works $middle = strtotime($old_date); // returns bool(false) $new_date = date('Y-m-d H:i:s', $middle); // returns 1970-01-01 00:00:00 

But I'd of course like it to return a current date rather than the crack 'o dawn. What am I doing wrong?

This Question Has 12 Answeres | Orginal Question | Tom

strtotime will work that out. the dates are just not the same and all in us-format.

<?php $e1 = strtotime("2013-07-22T12:00:03Z"); echo date('y.m.d H:i', $e1); echo "2013-07-22T12:00:03Z"; $e2 = strtotime("2013-07-23T18:18:15Z"); echo date ('y.m.d H:i', $e2); echo "2013-07-23T18:18:15Z"; $e1 = strtotime("2013-07-21T23:57:04Z"); echo date ('y.m.d H:i', $e2); echo "2013-07-21T23:57:04Z"; ?> 

The Basics

The simplist way to convert one date format into another is to use strtotime() with date(). strtotime() will convert the date into a Unix Timestamp. That Unix Timestamp can then be passed to date() to convert it to the new format.

$timestamp = strtotime('2008-07-01T22:35:17.02'); $new_date_format = date('Y-m-d H:i:s', $timestamp); 

Or as a one-liner:

$new_date_format = date('Y-m-d H:i:s', strtotime('2008-07-01T22:35:17.02')); 

Keep in mind that strtotime() requires the date to be in a valid format. Failure to provide a valid format will result in strtotime() returning false which will cause your date to be 1969-12-31.

Using DateTime()

As of PHP 5.2, PHP offered the DateTime() class which offers us more powerful tools for working with dates (and time). We can rewrite the above code using DateTime() as so:

$date = new DateTime('2008-07-01T22:35:17.02'); $new_date_format = $date->format('Y-m-d H:i:s'); 

Working with Unix timestamps

date() takes a Unix timeatamp as its second parameter and returns a formatted date for you:

$new_date_format = date('Y-m-d H:i:s', '1234567890'); 

DateTime() works with Unix timestamps by adding an @ before the timestamp:

$date = new DateTime('@1234567890'); $new_date_format = $date->format('Y-m-d H:i:s'); 

If the timestamp you have is in milliseconds (it may end in 000 and/or the timestamp is thirteen characters long) you will need to convert it to seconds before you can can convert it to another format. There's two ways to do this:

  • Trim the last three digits off using substr()

Trimming the last three digits can be acheived several ways, but using substr() is the easiest:

$timestamp = substr('1234567899000', -3); 
  • Divide the substr by 1000

You can also convert the timestamp into seconds by dividing by 1000. Because the timestamp is too large for 32 bit systems to do math on you will need to use the BCMath library to do the math as strings:

$timestamp = bcdiv('1234567899000', '1000'); 

To get a Unix Timestamp you can use strtotime() which returns a Unix Timestamp:

$timestamp = strtotime('1973-04-18'); 

With DateTime() you can use DateTime::getTimestamp()

$date = new DateTime('2008-07-01T22:35:17.02'); $timestamp = $date->getTimestamp(); 

If you're running PHP 5.2 you can use the U formatting option instead:

$date = new DateTime('2008-07-01T22:35:17.02'); $timestamp = $date->format('U'); 

Working with non-standard and ambiguous date formats

Unfortunately not all dates that a developer has to work with are in a standard format. Fortunately PHP 5.3 provided us with a solution for that. DateTime::createFromFormat() allows us to tell PHP what format a date string is in so it can be successfully parsed into a DateTime object for further manipulation.

$date = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM'); $new_date_format = $date->format('Y-m-d H:i:s'); 

In PHP 5.4 we gained the ability to do class member access on instantiation has been added which allows us to turn our DateTime() code into a one-liner:

$new_date_format = (new DateTime('2008-07-01T22:35:17.02'))->format('Y-m-d H:i:s'); $new_date_format = DateTime::createFromFormat('F-d-Y h:i A', 'April-18-1973 9:48 AM')->format('Y-m-d H:i:s'); 

The easiest way to do this is

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString); $newDateString = $myDateTime->format('m/d/Y'); 

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

This also avoids the use of strtotime, which can be hard to work with at times.

If you are not transforming from one date format to another, but just want the current date (or datetime) in a specific format then it's even easier:

$now = new DateTime(); $timestring = $now->format('Y-m-d h:i:s'); 

This other question also refers to the same topic: Convert date format yyyy-mm-dd => dd-mm-yyyy.

Try this:

$old_date = date('y-m-d-h-i-s'); $new_date = date('Y-m-d H:i:s', strtotime($old_date)); 

The following is an easy method to convert dates to different formats.

// Create a new DateTime object $date = DateTime::createFromFormat('Y-m-d', '2016-03-25'); // Output the date in a different format echo $date->format('Y-m-d'); 
$old_date = date('y-m-d-h-i-s'); // works 

you are doing wrong here, this should be

$old_date = date('y-m-d h:i:s'); // works 

separator of time is ':'


I think this will help...

$old_date = date('y-m-d-h-i-s'); // works preg_match_all('/(\d+)-(\d+)-(\d+)-(\d+)-(\d+)-(\d+)/', $old_date, $out, PREG_SET_ORDER); $out = $out[0]; $time = mktime($out[4], $out[5], $out[6], $out[2], $out[3], $out[1]); $new_date = date('Y-m-d H:i:s', $time); 

OR


$old_date = date('y-m-d-h-i-s'); // works $out = explode('-', $old_date); $time = mktime($out[3], $out[4], $out[5], $out[1], $out[2], $out[0]); $new_date = date('Y-m-d H:i:s', $time); 

The second parameter to date() needs to be a proper timestamp (seconds since January 1, 1970). You are passing a string, which date() can't recognize.

You can use strtotime() to convert a date string into a timestamp. However, even strtotime() doesn't recognize the y-m-d-h-i-s format.

PHP 5.3 and up

Use DateTime::createFromFormat. It allows you to specify an exact mask - using the date() syntax - to parse incoming string dates with.

PHP 5.2 and lower

You will have to parse the elements (year, month, day, hour, minute, second) manually using substr() and hand the results to mktime() that will build you a timestamp.

But that's a lot of work! I recommend using a different format that strftime() can understand. strftime() understands any date input short of the next time joe will slip on the ice. for example, this works:

$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34 $old_date_timestamp = strtotime($old_date); $new_date = date('Y-m-d H:i:s', $old_date_timestamp); 

You need to convert the $old_date back into a timestamp, as the date function requires a timestamp as its second argument.

This is the other way you can convert date format

 <?php $pastDate = "Tuesday 11th October, 2016"; $pastDate = str_replace(",","",$pastDate); $date = new DateTime($pastDate); $new_date_format = $date->format('Y-m-d'); echo $new_date_format.' 23:59:59'; ?> 

Try this:

$tempDate = explode('-','03-23-15'); $date = '20'.$tempDate[2].'-'.$tempDate[0].'-'.$tempDate[1]; 

To convert $date from (dd-mm-yyyy hh:mm:ss) to a proper mysql datetime I go like this:

$date = DateTime::createFromFormat('d-m-Y H:i:s',$date)->format('Y-m-d H:i:s'); 

Just using strings, for me is a good solution, less problems with mysql. Detects the current format and changes it if necessary

class dateTranslator { public static function translate($date, $lang) { $divider = ''; if (empty($date)){ return null; } if (strpos($date, '-') !== false) { $divider = '-'; } else if (strpos($date, '/') !== false) { $divider = '/'; } //spanish format DD/MM/YYYY hh:mm if (strcmp($lang, 'es') == 0) { $type = explode($divider, $date)[0]; if (strlen($type) == 4) { $date = self::reverseDate($date,$divider); } if (strcmp($divider, '-') == 0) { $date = str_replace("-", "/", $date); } //english format YYYY-MM-DD hh:mm } else { $type = explode($divider, $date)[0]; if (strlen($type) == 2) { $date = self::reverseDate($date,$divider); } if (strcmp($divider, '/') == 0) { $date = str_replace("/", "-", $date); } } return $date; } public static function reverseDate($date) { $date2 = explode(' ', $date); if (count($date2) == 2) { $date = implode("-", array_reverse(preg_split("/\D/", $date2[0]))) . ' ' . $date2[1]; } else { $date = implode("-", array_reverse(preg_split("/\D/", $date))); } return $date; } 

USE

dateTranslator::translate($date, 'en') 

Search
I am...

Sajjad Hossain

I have five years of experience in web development sector. I love to do amazing projects and share my knowledge with all.

Connect Social With PHPAns
Top