-2

I am fairly new to PHP programming and thus am facing a strange problem, through different forums i was able to learn how to convert dates of different formats into our desired formats, but today this was not possible and i was always given 01 Jan no matter what i gave in the variable, which was strange as previously it was working great. My code is following:

I am using a combination of date and strtotime PHP functions, as:

$coll_date_1[$i] = $row->coll_date_1;   //this is 08-08 i.e 8 Aug

$coll_date_1[$i] = date('d M',strtotime($coll_date_1[$i]));  //this return 01 Jan

The 1st line assigns value from database into the variable, and the 2nd line is the function to convert them into desired format. I know i am doing a silly mistake, but cant seem to pin point where that is...

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
Hunain Usman
  • 2,088
  • 5
  • 23
  • 32

3 Answers3

3

That happens because 08-08 is not a valid date format.

You could try adding a "fake" year in front of it, like 2000-08-08, or the current year, like 2013-08-08, and than do

$coll_date_1[$i] = 'YEAR-'.$row->coll_date_1; // "YEAR" could be "2000" or the current year
date('d M', strtotime($coll_date_1[$i]));

Anyway, you should change your database to handle dates in the proper format, which should be YYYY-MM-DD, for example in MySQL you'd use a date type field.

EDIT:

If you cannot change the database structure, but have PHP 5.3+, you can use the DateTime class to parse the date as

DateTime::createFromFormat('m-d', $row->coll_date_1)->format('d M');
Matteo Tassinari
  • 18,121
  • 8
  • 60
  • 81
  • well your right on this one, this actually solved the problem, but you see i am the developer, and the database as mentioned by my senior should be like this[supervisor requirement], is there any workaround over this, so i can get 08 Aug without the year[Or proper format]???? – Hunain Usman Aug 07 '13 at 12:37
2

You can specify the format using DateTime::createFromFormat:

$date = DateTime::createFromFormat("m-d","08-08")//Switch to "d-m" as needed
$date->format("d M");

This makes it easier to change the before format and after format.

Edit: As has been noted. Consider storing your column as a proper date or datetime. This will allow you to make use of the DB's date functions should you need them.

Jim
  • 22,354
  • 6
  • 52
  • 80
0

//this is 08-08 i.e 8 Aug

While it should be 2013-08-08.
Change your database field to proper format. Problem solved.

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
  • 2
    While this is what he should do it's not technically an answer to the question at hand is it? I agree that one thing experienced people at SO should be doing is pointing people in the right direction this is still a comment. Not only does it not handle the question, it doesn't even tell the user HOW to do what you said he should. sorry, -1 – Rick Calder Aug 07 '13 at 12:25