Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix date inconsistency from external source PHP

Tags:

php

datetime

I have an issue. The dates from the API come back to me as Feb 4 2016. I have to apply some date modifications for which I need the date in format 02-04-2016. The code works well for the dates returned from the API that are above 9, such as Feb 10 2016 because when I manipulate this, I get it neatly as 02-10-2016. However, the problem is with the dates below 10, such as Feb 4 2016 because these lead to 02-4-2016 which causes an error.

What I would like to know is how I can consistently get the format of 02-04-2016 regardless of dates from API are above 9 or below 10. The following is my code.

// Split checkin  date string from API
list($month, $day, $year, $time) = explode(' ', $checkindate); 

// change short month name (e.g Feb) to month number (e.g. 02)
$monthname = $month;
$month = date('m', strtotime($monthname));

// new checkin date in example format 02-20-2016
 $checkin_new = $month.'/'.$day.'/'.$year; // this is the part that causes an error when date returned by API is below 10, for example Feb 4 2016. Other dates above 9 such as Feb 10 2016 work well and don't cause an issue.


// Subtract days
 $newdate = new DateTime($checkin_new ); 
 $subtracteddate = $newdate->modify("-1 day");
like image 845
mush Avatar asked Nov 09 '22 21:11

mush


1 Answers

For getting the date in February use mktime function:

echo date("M d Y ", mktime( 0,0,0,2, 4, 2016));
echo "<br />";
echo gmdate("M d Y ", mktime( 0,0,0,2, 2, 2016));

This would give output:

Feb 04 2016
Feb 01 2016
like image 112
varunkumar Avatar answered Nov 15 '22 11:11

varunkumar