0

I have this code:

$date = substr($item[8], 7, 9);
$date = str_replace('/', '-', $date);

At this point, $date contains:

12-21-12  <---- December 21, 2012

Now I am trying to output date into a input type="date" friendly format as such:

<input type="date" name="date" value="<?php echo date('Y-m-d', strtotime($date)); ?>">

But it won't output properly.

If I change type="date" to type="text" I see the following output:

1969-12-31

Clearly something isn't working right in

date('m-d-Y', strtotime($date));

Can anyone help me clear up the problem?

2
  • From PHP docs for strtotime: To avoid potential ambiguity, it's best to use ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() when possible. Commented Dec 30, 2012 at 22:28
  • 1
    I think, in addition to what you're seeing in the answers, you're also doing american-style dates with european-style hyphens: codepad.org/mcKrN6DH Commented Dec 30, 2012 at 22:38

3 Answers 3

2

Dates must be in Y-m-d format, not m-d-Y.

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

4 Comments

@JaredFarrish Nope, it's in the specification
While it does answer the question, this doesn't solve the problem.
Hold on, look at the code; it's being sent incorrectly to the browser: codepad.org/mcKrN6DH It may be misformatted by rule, but it's also outputted incorrectly to the input.
Jared is correct. By removing $date = str_replace('/', '-', $date); the problem is solved.
2

If you are using PHP 5.3+, I encourage using the DateTime class.

In your case:

$date = DateTime::createFromFormat('m-d-y', '12-21-12');
echo $date->format('Y-m-d'); // 2012-12-21

As noted strtotime('12-21-12') because the date format is ambiguous in respect to the month and year.

3 Comments

I guess I don't have php 5.3 because $date won't echo anything.
@Jonathan, unfortunate. Take a look at strptime() as noted by Matti.
Well, the PHP docs do say that this is the correct way to handle these date ambiguities. Removing the useless swap at the second line really solves the issue, though.
0

Removing

$date = str_replace('/', '-', $date);

Solves the problem.

Comments

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.