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?
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.
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.
The date_format() function returns a date formatted according to the specified format.
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 :-)
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 ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With