Add & Sub Dates in php

Status
Not open for further replies.

zester

New Member
Messages
23
Reaction score
0
Points
0
HI all
I need to do a lot of adding and subtracting dates, so I was trying to make a function for it, but I just can’t get dates to add or sub right. Dose php have a built-in function for this, or do any of you know where to find one. I am tiring to subtract the last login date from today’s date to get time sense last login in YYYY-MM-DD-HH-II-SS

This is what I have
$date = date('Y-m-d H:i:s');
$Lastlogin=$rows['Lastlogin']; (from my DB in the same format as $date)
$away = $date - $Lastlogin;
But
$away always = 2008
And I will need to do more adding and subtracting in the program so I would like have something like this
SubDate(date1,date2)
And
ADDdate(date1,date2)
Can anyone help me.

[FONT=&quot]Zester out[/FONT]
 

sybregunne

Member
Messages
54
Reaction score
0
Points
6
Why don't you use a time stamp instead. Or in worst-case scenario split the date into components of hours, minutes seconds... etc. and just do the math from there. But I think unix timestamps will be easier but a bit limited I am also not very familiar with date and time handing in php but I will try to lookup the manual for a solution, if you find a solution can you post here so that I will know also. :)
Edit:
PHP:
  $date1 = date('Y-m-d H:i:s');
  echo $date1."<br>";
  $date2 = '2008-07-22 09:00:32';
  echo $date2."<br>";
  $date3 = strtotime($date1)-strtotime($date2);
  echo "you've been away ".$date3."seconds<br>";

Work on this you have the seconds.
Edit:
PHP:
  $date1 = date('Y-m-d H:i:s');
  echo $date1."<br>";
  $date2 = '2008-07-22 09:00:32';
  echo $date2."<br>";
  $date3 = strtotime($date1)-strtotime($date2);
  echo "you've been away ".$date3." seconds<br>";
  $balance = $date3;

  $_days=24*60*60;
  $_hours=60*60;
  $_mins=60;
  
  $days = $date3-($date3%$_days);
  $hours = (($date3-$days)-(($date3-$days)%$_hours));
  $mins = (($date3-$days-$hours)-(($date3-days-hours)%$_mins));
  $secs = $date3-$days-$hours-$mins;

  $days=$days/$_days;
  $hours=$hours/$_hours;
  $mins=$mins/$_mins;
  echo "You have been away for ".$days." days, ".$hours." hours, ".$mins." minutes and ".$secs." seconds.<br>";

This is the updated one. I hope this helps. :)
 
Last edited:

zester

New Member
Messages
23
Reaction score
0
Points
0
Thanks this works good for what I needed.
I still cannot believe that a programming languishes like PHP does not have function for date manipulation.

Zest out
 
Status
Not open for further replies.
Top