I'm looking for a way to compare dates and find the difference with PHP or jQuery (JavaScript). For instance if a user's birthday is 1/16/95 or January 16, 1995 and today is December 24, 2011 how could I get 开发者_运维百科"x Years and x Days"? Or if some one were to save a file and the date of creation is 1/16/95 or January 16, 1995 and 25 seconds passed since creation how could I get that time?
Take a look at DateTime::diff: PHP Manual
Your code could look like this:
$datetime1 = new DateTime('1994-12-16');
$today = new DateTime();
$interval = $datetime1->diff($datetime2);
echo $interval->format('%y years %d days');
If I where you I would use the PHP time() function. This value is always unique and is always interpreted the right way. You can always use strtotime php function to convert a string to a timestamp. Its easy calculating with those timestamps because difference A-B gives you time difference in seconds.
Hope it helps
You just need to convert the date to UNIX time (seconds since Jan 1, 1970), then subtract from "now". That will give you the difference in seconds, which you can then convert to a time string.
PHP has, as expected, some built-in stuff to do it, so it's very simple:
$birth = new DateTime('12/16/94');
$age = $birth->diff(new DateTime("now"));
echo $age->format('%y years and %d days');
(see valid time strings)
In Javascript, you need to do it yourself (but I did it for you):
function timeSince(_date){
// offset from current time
var s = Math.floor( (+new Date - Date.parse(_date)) / 1000 )
, day = 60*60*24
, year = day*365;
var years = Math.floor(s/year)
, days = Math.floor(s/day) - (years*365)
// handle plurals
, ys = ' year' + (years>1 ? 's' : '')
, ds = ' day' + (days>1 ? 's' : '');
return years + ys + ' and ' + days + ds;
};
timeSince(new Date('06/25/1985')); // => '25 years and 278 days'
This is getting the difference in seconds from the date to now, then dividing the value by an year/day's length in seconds. The allowed time strings are much more limited in js though.
精彩评论