PHP Date Question

I am trying to do a little math using dates in PHP. I am modifying a crickbox and I want to implement the following functions.


If post date = today, message return time

else, if date = yesterday, return "yesterday"

else date = X days ago


How to use php date functions to calculate the number of days ago timestamp (timestamp formatted during UNIX)

+6
date php
source share
6 answers

Try the following:

$shoutDate = date('Ym-d', $shoutTime); if ($shoutDate == date('Ym-d')) return date('H:i', $shoutTime); if ($shoutDate == date('Ym-d', mktime(0, 0, 0, date('m'), date('d') - 1, date('Y')))) return 'yesterday'; return gregoriantojd(date('m'), date('d'), date('y')) - gregoriantojd(date('m', $shoutTime), date('d', $shoutTime), date('y', $shoutTime)) . ' days ago'; 
+8
source share

In php 5.3.0 or higher, you can use DateTime :: diff (aka date_diff ()).

In almost any php, you can convert dates to Unix timestamps and divide the difference between them by 86400 (1 day in seconds).

+3
source share

Use the fact that time is stored in seconds:

  $days = floor(($shoutTime - time()) / 86400) + 1; // 86400 = 24*60*60 switch ($days) { case 0: return date('H:i', $shoutTime); case -1: return 'yesterday'; case 1: return 'tomorrow'; } return "$days ago"; 
+3
source share

I do not think it has been pointed out that you can use strtotime to get "Yesterday". This makes it more readable (and easier to remember) than calculating dates manually, and is probably also less error prone.

$ int = strtotime ("Yesterday");


 if(date('Ym-d', $shoutTime) == date('Ym-d') { return date('H:i:s', $shouTime); } elseif(date('Ym-d', $shoutTime) == date('Ym-d', strtotime('Yesterday')) { return "Yesterday."; } else { $days = floor($shoutTime - time() / 86400); return "$days ago."; } 
+1
source share

Use the DateTime class, and then you have the diff method.

0
source share

Try using date_parse.
From the manual:

 <?php print_r(date_parse("2006-12-12 10:00:00.5")); ?> 

Will be printed

 Array ( [year] => 2006 [month] => 12 [day] => 12 [hour] => 10 [minute] => 0 [second] => 0 [fraction] => 0.5 [warning_count] => 0 [warnings] => Array() [error_count] => 0 [errors] => Array() [is_localtime] => ) 
0
source share

All Articles