Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting to date in PHP from yyyymmdd format

I have dates in the following format (yyyymmdd, 18751104, 19140722)... what's the easiest way to convert it to date().... or is using mktime() and substrings my best option...?

like image 857
Serhiy Avatar asked Feb 26 '10 21:02

Serhiy


2 Answers

Use strtotime() to convert a string containing a date into a Unix timestamp:

<?php
// both lines output 813470400
echo strtotime("19951012"), "\n",
     strtotime("12 October 1995");
?>

You can pass the result as the second parameter to date() to reformat the date yourself:

<?php
// prints 1995 Oct 12
echo date("Y M d", strtotime("19951012"));
?>

Note

strtotime() will fail with dates before the Unix epoch at the start of 1970.

As an 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
?>
like image 181
meagar Avatar answered Oct 13 '22 01:10

meagar


Personally, I'd just use substr() because it's probably the lightest way to do it anyway.

But here's a function that takes a date, of which you can specify the format. It returns an associative array, so you could do for example (untested):

$parsed_date = date_parse_from_format('Ymd', $date);
$timestamp = mktime($parsed_date['year'], $parsed_date['month'], $parsed_date['day']);

http://uk.php.net/manual/en/function.date-parse-from-format.php

Although I must say, I don't find that any easier or more effective than simply:

mktime(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6, 2));
like image 40
Teekin Avatar answered Oct 13 '22 01:10

Teekin