0

i've got code

$dss='2011 04 28 10:00:45';
echo date('Y', strtotime($dss));

it display 1970- why?

1

4 Answers 4

6

it display 1970- why?

Becuase the format YYYY MM DD HH:MM:SS isn't one of the formats that strtotime accepts. In particular, it's failing to find a valid date string.

If you're using PHP 5.3 or better, look at DateTime::createFromFormat(), which takes a date-formatted string and creates a new DateTime object based on that format.

If you're stuck on a lower version of PHP, your "best" choice is the clunky strptime.

Or you can just stick dashes between the YYYY and MM and then between the MM and the DD, yielding YYYY-MM-DD, a perfectly cromulent format.

Sign up to request clarification or add additional context in comments.

2 Comments

so how can i convert this string to date?
@kusanagi, I have updated my answer with a few ways to deal with the string.
2

As Charles says it's not a valid date format. This should reformat it:

$dss = preg_replace('/^(\d+) (\d+) (.+)$/i', '$1-$2-$3', $dss);

Comments

0

It seems that you want only the year from this sting. You can simply do this:

$dss='2011 04 28 10:00:45';
echo substr($dss, 0, 5);

Comments

0

Wrong answer before...was -1 worthy...I'm now climbing backwards onto the donkey, putting the pail on my head, and leaving town.

5 Comments

Where did the 'Delete' link go? Read too quickly and now regret it :/
@Steve, I can't find one for my own answer either. Weird. Maybe you can edit your answer into correctness? (Hint: On error, strtotime returns either false or -1 based on the PHP version being used.)
Yes, was, and is, Weird. Thanks for the tip though! Taken, with some self-deprecating flippancy.
@Steve, I filed a bug, looks like it'll be fixed very soon (moments?)
Great, thanks. And to the -1 person, cheers on the reversal :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.