Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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...?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
833 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

<?php
// both lines output 813470400
echo strtotime("19951012"), "
",
     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
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...