Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a date format in PHP [duplicate]

I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.

How is this possible?

like image 331
matthy Avatar asked Mar 21 '10 17:03

matthy


People also ask

How convert date from yyyy-mm-dd to dd-mm-yyyy format in PHP?

Answer: Use the strtotime() Function You can first use the PHP strtotime() function to convert any textual datetime into Unix timestamp, then simply use the PHP date() function to convert this timestamp into desired date format. The following example will convert a date from yyyy-mm-dd format to dd-mm-yyyy.

What is Strtotime PHP?

The strtotime() function parses an English textual datetime into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Note: If the year is specified in a two-digit format, values between 0-69 are mapped to 2000-2069 and values between 70-100 are mapped to 1970-2000.

Which PHP function do you use to format date information?

The date_format() function returns a date formatted according to the specified format.


2 Answers

Use strtotime() and date():

$originalDate = "2010-03-21"; $newDate = date("d-m-Y", strtotime($originalDate)); 

(See the strtotime and date documentation on the PHP site.)

Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format :-)

like image 68
richsage Avatar answered Oct 13 '22 23:10

richsage


If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,

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

Or, equivalently:

$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y'); 

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

Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:

<?php     $source = '2012-07-31';     $date = new DateTime($source);     echo $date->format('d.m.Y'); // 31.07.2012     echo $date->format('d-m-Y'); // 31-07-2012 ?> 
like image 28
ceiroa Avatar answered Oct 13 '22 22:10

ceiroa