1

I just tried,

date_create_from_format('Ym','201302')

And I guess because it's the 29th today, it's actually giving me back March 1st.

I was hoping to get back 2013-02-01 00:00:00.

Is there a different function that will parse a date "correctly"? If not, I can extract it myself, not a big deal.

4

2 回答 2

5

If format does not contain the character ! then portions of the generated time which are not specified in format will be set to the current system time.

If format contains the character !, then portions of the generated time not provided in format, as well as values to the left-hand side of the !, will be set to corresponding values from the Unix epoch.

The Unix epoch is 1970-01-01 00:00:00 UTC. (DateTime Manual)

So, adding a ! at the beginning of your format string should fix your problem.

于 2013-09-29T20:48:32.243 回答
0

TheWolf's solution seems to work perfectly, but here's an alternative I started writing anyway:

function CompactStrToTime($str) {
    $year = strlen($str)>=4 ? substr($str,0,4) : date('Y');
    $month = strlen($str)>=6 ? substr($str,4,2) : 1;
    $day = strlen($str)>=8 ? substr($str,6,2) : 1;
    $hour = strlen($str)>=10 ? substr($str,8,2) : 0;
    $min = strlen($str)>=12 ? substr($str,10,2) : 0;
    $sec = strlen($str)>=14 ? substr($str,12,2) : 0;
    return mktime($hour,$min,$sec,$month,$day,$year);
}
于 2013-09-29T20:55:32.837 回答