Skip to content

Instantly share code, notes, and snippets.

@ikamal7
Created April 25, 2021 11:09
Show Gist options
  • Save ikamal7/ee8ffcd5533d18a1a6eb568482a85ebf to your computer and use it in GitHub Desktop.
Save ikamal7/ee8ffcd5533d18a1a6eb568482a85ebf to your computer and use it in GitHub Desktop.
<?php
function time_Ago( $time ) {
// Calculate difference between current
// time and given timestamp in seconds
$diff = time() - $time;
// Time difference in seconds
$sec = $diff;
// Convert time difference in minutes
$min = round( $diff / 60 );
// Convert time difference in hours
$hrs = round( $diff / 3600 );
// Convert time difference in days
$days = round( $diff / 86400 );
// Convert time difference in weeks
$weeks = round( $diff / 604800 );
// Convert time difference in months
$mnths = round( $diff / 2600640 );
// Convert time difference in years
$yrs = round( $diff / 31207680 );
// Check for seconds
if ( $sec <= 60 ) {
echo "$sec seconds ago";
}
// Check for minutes
else if ( $min <= 60 ) {
if ( $min == 1 ) {
echo "one minute ago";
} else {
echo "$min minutes ago";
}
}
// Check for hours
else if ( $hrs <= 24 ) {
if ( $hrs == 1 ) {
echo "an hour ago";
} else {
echo "$hrs hours ago";
}
}
// Check for days
else if ( $days <= 7 ) {
if ( $days == 1 ) {
echo "Yesterday";
} else {
echo "$days days ago";
}
}
// Check for weeks
else if ( $weeks <= 4.3 ) {
if ( $weeks == 1 ) {
echo "a week ago";
} else {
echo "$weeks weeks ago";
}
}
// Check for months
else if ( $mnths <= 12 ) {
if ( $mnths == 1 ) {
echo "a month ago";
} else {
echo "$mnths months ago";
}
}
// Check for years
else {
if ( $yrs == 1 ) {
echo "one year ago";
} else {
echo "$yrs years ago";
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment