I am trying to convert a date from dd/mm/yyyy => yyyy-mm-dd
. I have using the mktime() function and other functions but I cannot seem to make it work. I have managed to explode
the original date using '/'
as the delimiter but I have no success changing the format and swapping the '/'
with a '-'
.
Any help will be greatly appreciated.
This question is related to
php
date
formatting
mktime
I can see great answers, so there's no need to repeat here, so I'd like to offer some advice:
I would recommend using a Unix Timestamp integer instead of a human-readable date format to handle time internally, then use PHP's date()
function to convert the timestamp value into a human-readable date format for user display. Here's a crude example of how it should be done:
// Get unix timestamp in seconds
$current_time = date();
// Or if you need millisecond precision
// Get unix timestamp in milliseconds
$current_time = microtime(true);
Then use $current_time
as needed in your app (store, add or subtract, etc), then when you need to display the date value it to your users, you can use date()
to specify your desired date format:
// Display a human-readable date format
echo date('d-m-Y', $current_time);
This way you'll avoid much headache dealing with date formats, conversions and timezones, as your dates will be in a standardized format (Unix Timestamp) that is compact, timezone-independent (always in UTC) and widely supported in programming languages and databases.
Try Using DateTime::createFromFormat
$date = DateTime::createFromFormat('d/m/Y', "24/04/2012");
echo $date->format('Y-m-d');
Output
2012-04-24
EDIT:
If the date is 5/4/2010 (both D/M/YYYY or DD/MM/YYYY), this below method is used to convert 5/4/2010 to 2010-4-5 (both YYYY-MM-DD or YYYY-M-D) format.
$old_date = explode('/', '5/4/2010');
$new_data = $old_date[2].'-'.$old_date[1].'-'.$old_date[0];
OUTPUT:
2010-4-5
Here's another solution not using date(). not so smart:)
$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
Source: Stackoverflow.com