5

I have a bit of PHP code:

$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;

Which is used for formatting the date. The expected output would be 2015-12-01 but it returns 2016-12-01. What am i missing?

2
  • The date inside date_create() seems to be in text format. Commented Feb 18, 2016 at 5:24
  • you first need string to time convert..you can follow this stackoverflow.com/questions/6238992/… Commented Feb 18, 2016 at 5:29

4 Answers 4

9

Use createFromFormat method first, provide the input format:

$exd = DateTime::createFromFormat('d M, Y', '01 Dec, 2015');
// arguments (<format of the input>, <the input itself>)
$exd = date_format($exd, 'Y-m-d'); // then choose whatever format you like
echo $exd;
Sign up to request clarification or add additional context in comments.

Comments

4

The date_create() function accepts only the parameter link, This function is also and alias function of DateTime::__construct()

check the function date_create_from_format() its also a alias function of DateTime::createFromFormat(). Refer link

$exd = date_create_from_format('j M, Y', '01 Dec, 2015');
//$exd = date_create('01 Dec, 2015');
$exd = date_format($exd, 'Y-m-d');
echo $exd;

Comments

1

It can be a date function call simply. Use stringtotime for exact/precise date/time value

date("Y-m-d",strtotime("01 Dec 2015"))

When you run this code the out put will show

2015-12-01

this is because of the comma in the string which terminates the date string in the compiler. If you specify exactly the timezone (like $timezone = 'America/New_York) . parameter you can show precise time as well.

Comments

-2

i got the solution of your bug that is date_format(datae_variable,date_format);

<?php
     $exd = date_create('01 Dec, 2015');
     $exd1 = date_format($exd,"Y-m-d");//here you make mistake
     echo $exd1;
?>

4 Comments

Good try... But please confirm the results before try. You can use phpfiddle.org for debugging and checking the results.
this code is also run phpfiddle.org check that first
Please check the result. Expected would be 2015-12-01 but result was 2016-12-01
oooh am sorry i just check the format sorry ! r u from where? please

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.