Wednesday, November 21, 2012

Fun (and Frustration) With Dates in PHP

It is easy to have the wrong type and/or wrong value for dates in PHP.  Dates can be represented/stored different ways or types - strings, numbers and something else called date/time class.  PHP tries to cast dates in the proper type based on the context. It follows that your code can easily get off track and debugging the problem is NOT easy. You don't know if the problem is in an implicit cast somewhere or another issue elsewhere in the code.

  • When and if to use which quote marks is one of the devil in the details. 

PHP Code Snippet:
  $sdate="11/10/2012";
  $strstartdate=$sdate;
  echo "Startdate1 = ", $strstartdate;


Result:
  Startdate1 = 11/10/2012

PHP Code Snippet:
  $sdate="11/10/2012";
  $strstartdate='$sdate';
  echo "Startdate2 = ", $strstartdate;


Result:
  Startdate2 = $sdate

PHP Code Snippet:
  $sdate="11/10/2012";
  $strstartdate="$sdate";
  echo "Startdate3 = ", $strstartdate;


Result:
  Startdate3 = 11/10/2012

  • Explicit date type casting helps avoid implicit casting problems and simplifies debugging.

PHP Code Snippet:
  $sdate="11/10/2012";
  $numstartdate=strtotime("$sdate");
  echo "Numdate1 = ", $numstartdate;

  $strstartdate=date("m/d/Y", $numstartdate);
  echo "Strdate1 = ", $strstartdate; 

Results:
  Numdate1 = 1352523600
  Strdate1 = 11/10/2012



  • Add time (one day) to a given date...  Method 1

PHP Code Snippet:
  $sdate="11/10/2012";
  $numstartdate=strtotime(("+1 day"), strtotime("$sdate")); 
  echo "Numdate2 = ", $numstartdate; 
  $strstartdate=date("m/d/Y", $numstartdate);
  echo "Strdate2 = ", $strstartdate; 

Results:
  Numdate2 = 1352610000
  Strdate2 = 11/11/2012

FYI, the difference between Numdate1 and Numdate2 is 86400, which is the number of seconds in a day.


  • Add time (one day) to a given date...  Method 2

PHP Code Snippet:
  $sdate="11/10/2012";
  $dtstartdate = new DateTime($sdate);
  $dtstartdate->add(new DateInterval('P1D'));
  $strstartdate=$dtstartdate->format('d/m/Y');
  $numstartdate=strtotime("$strstartdate");
  echo "Numdate3 = ", $numstartdate;

  echo "Strdate3 = ", $strstartdate;


Results:
  Numdate3 = 1352610000
  Strdate3 = 11/11/2012

No comments: