Go Back   CodingForums.com > :: Server side development > PHP

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 12-08-2011, 05:19 PM   PM User | #1
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Date Diff Errors

All,

What I read is that date_diff was not working in 5.2, etc and have to have 5.3 or later to make it work. I have 5.3.5 and always errors!!

Simple code of:
Code:
      $cur_date  = date("y/m/d");
      $max_date  = get_max_date();  // Get largest finish date from table
      echo "C=> $cur_date M=> $max_date <br>";
      $dif_date  = date_diff($max_date, $cur_date);
      echo "Report Days=> $dif_date <br>";
should work but always give error of:
Quote:
Warning: date_diff() expects parameter 1 to be DateTime, string given in /var/www/intranet/wordpress/schedule_test/functions/functions.php on line 64
No this is not a WordPress app, just resides under that dir.

All help appreciated!

Thanks!

OMR
OldManRiver is offline   Reply With Quote
Old 12-08-2011, 05:50 PM   PM User | #2
Rowsdower!
Senior Coder

 
Rowsdower!'s Avatar
 
Join Date: Oct 2008
Location: Some say it's everything.
Posts: 2,015
Thanks: 5
Thanked 395 Times in 388 Posts
Rowsdower! has a spectacular aura aboutRowsdower! has a spectacular aura aboutRowsdower! has a spectacular aura about
Quote:
Originally Posted by OldManRiver View Post
All,

What I read is that date_diff was not working in 5.2, etc and have to have 5.3 or later to make it work. I have 5.3.5 and always errors!!

Simple code of:
Code:
      $cur_date  = date("y/m/d");
      $max_date  = get_max_date();  // Get largest finish date from table
      echo "C=> $cur_date M=> $max_date <br>";
      $dif_date  = date_diff($max_date, $cur_date);
      echo "Report Days=> $dif_date <br>";
should work but always give error of:
Quote:
Warning: date_diff() expects parameter 1 to be DateTime, string given in /var/www/intranet/wordpress/schedule_test/functions/functions.php on line 64
No this is not a WordPress app, just resides under that dir.

All help appreciated!

Thanks!

OMR
As it says right there in the error message, it expects a DateTime object but you are passing a string. Your database data is a string. I think if you convert it even just to an integer then it would work (but maybe not? I don't have PHP 5.3+ so I can't test).

Try this and see if it helps:
PHP Code:
      $cur_date  date("y/m/d");
      
$max_date  get_max_date();  // Get largest finish date from table
      
echo "C=> $cur_date M=> $max_date <br>";
      
$max_date intval($max_date);
      
$dif_date  date_diff($max_date$cur_date);
      echo 
"Report Days=> $dif_date <br>"
Or if that doesn't work I found this on PHP.net:
PHP Code:
function diff($start,$end false) {
    
/*
    * For this function, i have used the native functions of PHP. It calculates the difference between two timestamp.
    *
    * Author: Toine
    *
    * I provide more details and more function on my website
    */

    // Checks $start and $end format (timestamp only for more simplicity and portability)
    
if(!$end) { $end time(); }
    if(!
is_numeric($start) || !is_numeric($end)) { return false; }
    
// Convert $start and $end into EN format (ISO 8601)
    
$start  date('Y-m-d H:i:s',$start);
    
$end    date('Y-m-d H:i:s',$end);
    
$d_start    = new DateTime($start);
    
$d_end      = new DateTime($end);
    
$diff $d_start->diff($d_end);
    
// return all data
    
$this->year    $diff->format('%y');
    
$this->month    $diff->format('%m');
    
$this->day      $diff->format('%d');
    
$this->hour     $diff->format('%h');
    
$this->min      $diff->format('%i');
    
$this->sec      $diff->format('%s');
    return 
true;

Full citation (http://us.php.net/manual/en/function...f.php#105550):
Quote:
Toine (contact at toine dot pro) 26-Aug-2011 02:22
This is a very simple function to calculate the difference between two timestamp values.
PHP Code:
<?php
function diff($start,$end false) {
    
/*
    * For this function, i have used the native functions of PHP. It calculates the difference between two timestamp.
    *
    * Author: Toine
    *
    * I provide more details and more function on my website
    */

    // Checks $start and $end format (timestamp only for more simplicity and portability)
    
if(!$end) { $end time(); }
    if(!
is_numeric($start) || !is_numeric($end)) { return false; }
    
// Convert $start and $end into EN format (ISO 8601)
    
$start  date('Y-m-d H:i:s',$start);
    
$end    date('Y-m-d H:i:s',$end);
    
$d_start    = new DateTime($start);
    
$d_end      = new DateTime($end);
    
$diff $d_start->diff($d_end);
    
// return all data
    
$this->year    $diff->format('%y');
    
$this->month    $diff->format('%m');
    
$this->day      $diff->format('%d');
    
$this->hour     $diff->format('%h');
    
$this->min      $diff->format('%i');
    
$this->sec      $diff->format('%s');
    return 
true;
}

/*
 * How use it?
 *
 * Call your php class (myClass for this example) and use the function :
*/
$start  strtotime('1985/02/09 13:54:17');
$end    strtotime('2012/12/12 17:30:21');
$myClass = new myClass();
$myClass->Diff($start,$end);
// Display result
echo 'Year: '.$myClass->Year;
echo 
'<br />Month: '.$myClass->Month;
echo 
'<br />Day: '.$myClass->Day;
echo 
'<br />Hour: '.$myClass->Hour;
echo 
'<br />Min: '.$myClass->Min;
echo 
'<br />Sec: '.$myClass->Sec;
// Display only month for all duration
$month = ($myClass->Year 12) + $myClass->Month;
echo 
'<br />Total month: '.$month;
// if you want you can use this function without $end value :
$myClass->Diff($start);
// Automatically the end is the current timestamp
?>
__________________
The object of opening the mind, as of opening the mouth, is to shut it again on something solid. –G.K. Chesterton
See Mediocrity in its Infancy
It's usually a good idea to start out with this at the VERY TOP of your CSS: * {border:0;margin:0;padding:0;}
Seek and you shall find... basically:
validate your markup | view your page cross-browser/cross-platform | free web tutorials | free hosting
Rowsdower! is offline   Reply With Quote
Old 12-08-2011, 06:20 PM   PM User | #3
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Latest code

All,

Went to ##php channel on IRC.freenode.net and got this far:
Code:
      $cur_date  = date_create(date("y/m/d"));
      //  Value from get_max_date() is "12/3/8"
      $max_date  = date_create(get_max_date());
      $dif_date  = date_diff($max_date, $cur_date);
      echo "Report Days=> $dif_date  <br>";
but the echo statement errors and I need an integer value as I have a report being generated and the result tells me how many rows the report gets.

Rowsdower!

Thanks for the inputs, but anything less than a numeric value, integer or float will not work for me.

Just not sure how to get there.

Thanks!

OMR
OldManRiver is offline   Reply With Quote
Old 12-08-2011, 06:46 PM   PM User | #4
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
All,

OK created function for what I need, but still need the right code to complete it:
Code:
      $cur_date  = date("y/m/d");
      $max_date  = "12/3/8"  // from get_max_date();
      $dif_date  = e_days($max_date, $cur_date);
      echo "Report Days=> $dif_date <br>";


   function e_days($start,$end) {
      /************************************************************************/
      /* Purpose: To get the elapsed days of date diff as integer.            */
      /************************************************************************/
      $s_date  = date_create($start);
      $e_date  = date_create($end);
      $r_date  = date_diff($e_date, $s_date);
      return $r_date;
   }  // end function
Looked at the "idate" function, but does not have option for elapsed days.Right now getting error:
Quote:
Catchable fatal error: Object of class DateInterval could not be converted to string in /var/www/intranet/wordpress/schedule_test/functions/functions.php on line 49
I've tried the DateInterval options and get the error I posted at:

http://pastebin.com/q8MYwGrU

Thanks!

OMR

Last edited by OldManRiver; 12-08-2011 at 06:49 PM..
OldManRiver is offline   Reply With Quote
Old 12-08-2011, 08:54 PM   PM User | #5
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
DateInterval is an object. Most objects in the default PHP api do not override the __toString magic method, so they cannot be directly printed. You can catch it using a try/catch, but that is not typically what you are wanting to do.

You need to print it out by formatting it:
PHP Code:
print $r_date->format('Report Days => %a days'); 
I personally use OO wheneer I can.
PHP Code:
$dtStart = new DateTime();
$dtEnd = new DateTime('12/3/8');
// This is fine as long as it means December 3, 2008.  Otherwise, you need to use mktime to force it manually since strtotime only works in this format with m/d/yy[yy]

$interval $dtEnd->diff($dtStart);
print 
$interval->format('%a days different'); 
That looks like it will work alright.
Fou-Lu is offline   Reply With Quote
Old 12-09-2011, 01:25 AM   PM User | #6
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Always Error

All;

always get an error when trying any of the OOP date_diff crap:

Quote:
Fatal error: Uncaught exception 'Exception' with message 'DateTime::__construct() [<a href='datetime.--construct'>datetime.--construct</a>]: Failed to parse time string (20/12/01) at position 0 (2): Unexpected character' in /var/www/intranet/wordpress/schedule_test/functions/functions.php:101 Stack trace: #0 /var/www/intranet/wordpress/schedule_test/functions/functions.php(101): DateTime->__construct('20/12/01') #1 /var/www/intranet/wordpress/schedule_test/functions/functions.php(57): e_days('20/12/01', '11/12/08') #2 /var/www/intranet/wordpress/schedule_test/functions/functions.php(471): bld_php_report() #3 /var/www/intranet/wordpress/schedule_test/functions/run_proc.php(78): run_php_rpt() #4 /var/www/intranet/wordpress/schedule_test/index.php(17): include('/var/www/intran...') #5 {main} thrown in /var/www/intranet/wordpress/schedule_test/functions/functions.php on line 101
I really think I must be missing a lib assignment somewhere, but still looking for this solution.

Thanks!

OMR
OldManRiver is offline   Reply With Quote
Old 12-09-2011, 04:27 AM   PM User | #7
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
You are not missing anything; datetime is a part of the core in 5.2+
The error message indicates you're provided date is invalid. If you use / separated date, it requires that you use it in the format of m/d/yy[yy], and is the standard for gnu date time formats. There is no 20th month, and that is what it is complaining about.
Fou-Lu is offline   Reply With Quote
Old 12-09-2011, 04:06 PM   PM User | #8
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
All,

Got around some of the errors with type cating in the following function:
Code:
   function get_date($mydate) {
      /************************************************************************/
      /* Purpose: To get only the date string from the passed date/string.    */
      /************************************************************************/
      $datstr = (float) $mydate;
      $new_date = date('y/m/d', $datstr);
      return (string) $new_date;
   }        // end function
Now working on the errors from the date math calls.

Thanks!

OMR
OldManRiver is offline   Reply With Quote
Old 12-09-2011, 04:24 PM   PM User | #9
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Partially Working - Date values change

All,

OK got my function working with:
Code:
      $cur_date  = date("y/m/d");
      $max_date  = get_max_date();
      $dif_date  = e_days($max_date, $cur_date);

   function e_days($end,$start) {
      /************************************************************************/
      /* Purpose: To get the elapsed days of date diff as integer.            */
      /************************************************************************/
      $dts = date('m/d/Y',(float)$start);
      $dte = date('m/d/Y',(float)$end);
      echo "ST=> $start DT=> $dts SE=> $end DE=> $dte <br>";
      $dtS = new DateTime($dts);
      $dtE = new DateTime($dte);
      $int = $dtE->diff($dtS);
      print $int->format('%a days different');
      //$r_date  = date_diff($dte, $dts);
      return (integer) $interval;
   }  // end function
But conversion of date from format 'y/m/d' to 'm/d/Y' completely changes the values of the dates. I saw a writeup on this, but do not know the fix. Right now going to change the statements passing date to the function so will be in '/m/d/Y' format to eliminate the errors.

If you have fix for the date "format" value change, then please submit.

Thanks!

OMR
OldManRiver is offline   Reply With Quote
Old 12-09-2011, 04:41 PM   PM User | #10
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
The above definitely won't work as intended.
date creates a string in the format specified using the value of the integer timestamp. Attempting to cast a string to a numeric type is successful until it cannot find a valid replacement. $dts above will contain the value 01/01/1970 indicating 11 seconds since unix epoch.

If you use y/m/d format consistently with your data, you can construct this using createFromFormat on the datetime class available from 5.3+.
PHP Code:
$dt DateTime::createFromFormat('y/m/d'$ymd); 
Fou-Lu is offline   Reply With Quote
Old 12-09-2011, 05:03 PM   PM User | #11
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Works

All,

OK this code works error free:
Code:
   function e_days($end,$start) {
      /************************************************************************/
      /* Purpose: To get the elapsed days of date diff as integer.            */
      /************************************************************************/
      $dtS = new DateTime($start);
      $dtE = new DateTime($end);
      $int = $dtE->diff($dtS);
      $ret = (integer) $int->format('%a');
      return $ret;
   }  // end function
Thanks for the help all!!! Kudos!!!

OMR
OldManRiver is offline   Reply With Quote
Old 12-16-2011, 08:47 PM   PM User | #12
OldManRiver
New Coder

 
Join Date: Dec 2005
Posts: 76
Thanks: 0
Thanked 0 Times in 0 Posts
OldManRiver is an unknown quantity at this point
Another short problem

All,

One of my dates is in the format 'm/d/y' and needs to convert to 'Y/m/d'

but all my conversion have the year at 1969.

I read some on this being a problem, but never found a good solution.

Open to ideas and code.

Searching google for "PHP howto get accurate dates" or "PHP getting accurate dates" does not produce anything useful.

Thanks!

OMR

Last edited by OldManRiver; 12-16-2011 at 08:49 PM..
OldManRiver is offline   Reply With Quote
Old 12-17-2011, 10:30 AM   PM User | #13
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
If its already in the format of using m/d/y, any strtotime method will work. m/d/yy[yy] is a standard in gnu time format.
This isn't an issue with PHP now. This is an issue with your data being stored in multiple formats. Previous issues you had was using y/m/d and d/m/y formats. Using different types of formats provides no consistent way to verify. I can validate if 20/01/01 is invalid (which it is), but I cannot validate that 02/01/01 is valid or invalid. Is that supposed to be january 2, 2001, or february 1, 2001? Stick with either a unixtimestamp or a database driven date format instead, which will match the formats usable by the gnu format.
Follow this page under the calendar items to see what formats are considered legal by methods like strtotime: http://www.gnu.org/software/tar/manu...t-formats.html
PHP adheres to most of the rules above. Some items do not work (like fortnight), but these can get around all of these by using +2 week for example.
Fou-Lu is offline   Reply With Quote
Old 12-31-2012, 01:33 PM   PM User | #14
kununurra
New to the CF scene

 
Join Date: Dec 2012
Posts: 1
Thanks: 0
Thanked 0 Times in 0 Posts
kununurra is an unknown quantity at this point
Exclamation date_diff php 5.3 problems

Hi all,
works great until php 5.3, i got these errors:
Warning: date_diff() expects parameter 1 to be DateTime, string given in /mnt
it was working until php 5.3 cames out. Any ideas how to get it back to work with php 5.3?

Code:
if (! function_exists(date_diff)) {
function date_diff($start_date, $end_date, $returntype="d")
{


   if ($returntype == "s")
       $calc = 1;
   if ($returntype == "m")
       $calc = 60;
   if ($returntype == "h")
       $calc = (60*60);
   if ($returntype == "d")
       $calc = (60*60*24);

   $_d1 = explode("-", $start_date);
   $y1 = $_d1[0];
   $m1 = $_d1[1];
   $d1 = $_d1[2];

   $_d2 = explode("-", $end_date);
   $y2 = $_d2[0];
   $m2 = $_d2[1];
   $d2 = $_d2[2];

   if (($y1 < 1970 || $y1 > 2037) || ($y2 < 1970 || $y2 > 2037))
   {
       return 0;
   } else
   {
       $today_stamp    = mktime(0,0,0,$m1,$d1,$y1);
       $end_date_stamp    = mktime(0,0,0,$m2,$d2,$y2);
       $difference    = round(($end_date_stamp-$today_stamp)/$calc);
       return $difference;
   }
}
the line which reports these date_diff problem:
$no_days=date_diff($pickup_date, $return_date, $returntype="d")+1;

i checked it thousand times and i havent any ideas.
So what could be wrong? any ideas?
Wish all a great 2013!
kununurra is offline   Reply With Quote
Old 12-31-2012, 03:21 PM   PM User | #15
Fou-Lu
God Emperor


 
Fou-Lu's Avatar
 
Join Date: Sep 2002
Location: Saskatoon, Saskatchewan
Posts: 15,741
Thanks: 4
Thanked 2,465 Times in 2,434 Posts
Fou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to allFou-Lu is a name known to all
The problem here is your custom signature doesn't adhere to the signature used by the built in function. The built in signature is DateInterval date_diff(DateTime, DateTime, boolean);, but the custom one is int date_diff(String, String, String);. Therefore, since you've moved to 5.3 and the date_diff function became available, you can no longer use any signatures of the custom function. Everywhere you have used date_diff will need to be replaced completely to work with the datetime::diff, or you can rename the custom function and rename all the calls to it in order to continue using your custom function.
Fou-Lu is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 01:34 AM.


Advertisement
Log in to turn off these ads.