问题
Possible Duplicate:
PHP Date String Format
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.
回答1:
Dates in the
m/d/y
ord-m-y
formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/
), then the Americanm/d/y
is assumed; whereas if the separator is a dash (-
) or a dot (.
), then the Europeand-m-y
format is assumed. Check more here.
Use the default date function.
$var = "20/04/2012";
echo date("Y-m-d", strtotime($var) );
EDIT I just tested it, and somehow, PHP doesn't work well with dd/mm/yyyy format. Here's another solution.
$var = '20/04/2012';
$date = str_replace('/', '-', $var);
echo date('Y-m-d', strtotime($date));
回答2:
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
回答3:
Here's another solution not using date(). not so smart:)
$var = '20/04/2012';
echo implode("-", array_reverse(explode("/", $var)));
回答4:
Do this:
date('Y-m-d', strtotime('dd/mm/yyyy'));
But make sure 'dd/mm/yyyy' is the actual date.
回答5:
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.
来源:https://stackoverflow.com/questions/10306999/php-convert-date-format-dd-mm-yyyy-yyyy-mm-dd