Converting date in PHP from yyyymmdd to yyyy mm dd format

gruodžio 12th, 2011

I have dates in the following format (yyyymmdd, 18751104, 19140722) and i need normal date (yyyy mm dd, 1875 11 04, 1914 07 22).

1. first you can use strtotime and date functions (this will fail with dates before the Unix epoch at the start of 1970. )
<?php
// prints 1995 Oct 12
echo date("Y M d", strtotime("19951012"));
?>

2. Alternative which will work with dates before 1970
<?php // Returns the year as an offset since 1900, negative for years before
$parts = strptime("18951012", "%Y%m%d");
$year = $parts['tm_year'] + 1900; // 1895
$day = $parts['tm_mday']; // 12
$month = $parts['tm_mon']; // 10 ?>

3. simple method – date_parse_from_format

<?php $parsed_date = date_parse_from_format('Ymd', $date); ?> 

4. substr because it’s probably the lightest way to do it

mktime(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6, 2));
Be Sociable, Share!

Leave a Reply