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

Categories

0 votes
427 views
in Technique[技术] by (71.8m points)

php - strtotime() & date() weird behaviour when converting date in to same format as it was before

I have to convert date format in to mm-dd-yyyy I don't know what is the current date format it is dynamic so if I have dynamic date format is already in mm-dd-yyyy then date() function is returning below outout

    $date='02-13-2011';
    echo date('m-d-Y',strtotime($date));

output is

  01-01-1970

?>

http://codepad.org/AFZ6jel7

So I have to check if the date is already in mm-dd-yyyy then do not apply date formatting. Is there any other way do this? may be passing one other parameter in these functions or something similar.

Thanks.

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

I strongly suspect that this is what's causing the problem:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

(Found in the strtotime documentation.)

You've got dash separators, so it's assuming d-m-y format, parsing it as a month of 13, and thus effectively failing.

Options I can think of off the top of my head, without being a PHP developer:

  • If there's a function which allows you to explicitly say what format the string is in, use that.

    For example DateTime::createFromFormat()

  • Change your format to use slashes
  • Change your format to use d-m-y instead of m-d-y

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...