10 PHP Functions & Code Snippets to Work with Dates


Get current time, formatted

Super basic function, takes no parameters and returns the current date. This example uses British date formatting, you can change it on line 2.

function nowuk(){
return date('d/m/Y', time());
}

Format a date

The easiest way to convert a date from a format (here yyyy-mm-dd) to another. For more extensive conversions, you should have a look at the DateTime class to parse & format.

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

Source: Stack Overflow

Get week number from a date

When coding you often find yourself in the need of getting the week number of a particular date. Pass your date as a parameter to this nifty function, and it will return you the week number.

function weeknumber($ddate){
$date = new DateTime($ddate);
return $date->format("W");
}

Convert minutes to hours and minutes

Here is a super useful function for displaying times: Give it minutes as an integer (let’s say 135) and the function will return 02:15. Handy!

function convertToHoursMins($time, $format = '%02d:%02d') {
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}

Get difference between two times

This function takes two dates and returns the interval between those two. The result is set to be displayed in hours and minutes, you can easily change it on line 5 to fit your needs.

function dateDiff($date1, $date2){
$datetime1 = new DateTime($date1);
$datetime2 = new DateTime($date2);
$interval = $datetime1->diff($datetime2);
return $interval->format('%H:%I');
}

Check if a date is in the past or in the future

Very simple conditional statements to check if a date is past, present, or future.

if(strtotime(dateString) > time()) {
# date is in the future
}

if(strtotime(dateString) < time()) {
# date is in the past
}

if(strtotime(dateString) == time()) {
# date is right now
}

Source: Art of Web

Calculate age

This very handy function takes a date as a parameter, and returns the age. Very useful on websites where you need to check that a person is over a certain age to create an account.

function age($date){
$time = strtotime($date);
if($time === false){
return '';
}

$year_diff = '';
$date = date('Y-m-d', $time);
list($year,$month,$day) = explode('-',$date);
$year_diff = date('Y') - $year;
$month_diff = date('m') - $month;
$day_diff = date('d') - $day;
if ($day_diff < 0 || $month_diff < 0) $year_diff-;

return $year_diff;
}

Source: AP PHP

Show a list of days between two dates

An interesting example on how to display a list of dates between two dates, using DateTime() and DatePeriod() classes.

// Mandatory to set the default timezone to work with DateTime functions
date_default_timezone_set('America/Sao_Paulo');

$start_date = new DateTime('2010-10-01');
$end_date = new DateTime('2010-10-05');

$period = new DatePeriod(
$start_date, // 1st PARAM: start date
new DateInterval('P1D'), // 2nd PARAM: interval (1 day interval in this case)
$end_date, // 3rd PARAM: end date
DatePeriod::EXCLUDE_START_DATE // 4th PARAM (optional): self-explanatory
);


foreach($period as $date) {
echo $date->format('Y-m-d').'<br/>'; // Display the dates in yyyy-mm-dd format
}

Source: Snipplr

Twitter Style “Time Ago” Dates

Now a classic, this function turns a date into a nice “1 hour ago” or “2 days ago”, like many social media sites do.

function _ago($tm,$rcs = 0) {
$cur_tm = time(); $dif = $cur_tm-$tm;
$pds = array('second','minute','hour','day','week','month','year','decade');
$lngh = array(1,60,3600,86400,604800,2630880,31570560,315705600);
for($v = sizeof($lngh)-1; ($v >= 0)&&(($no = $dif/$lngh[$v])<=1); $v--); if($v < 0) $v = 0; $_tm = $cur_tm-($dif%$lngh[$v]);

$no = floor($no); if($no <> 1) $pds[$v] .='s'; $x=sprintf("%d %s ",$no,$pds[$v]);
if(($rcs == 1)&&($v >= 1)&&(($cur_tm-$_tm) > 0)) $x .= time_ago($_tm);
return $x;
}

Source: CSS Tricks

Countdown to a date

A simple snippet that takes a date and tells how many days and hours are remaining until the aforementioned date.

$dt_end = new DateTime('December 3, 2016 2:00 PM');
$remain = $dt_end->diff(new DateTime());
echo $remain->d . ' days and ' . $remain->h . ' hours';

Source: Stack Overflow

Jean-Baptiste Jung is a self-taught web developer, web designer, and influential blogger from Belgium who has made significant contributions to the WordPress community since 2006. As the founder of CatsWhoCode (established in 2008) and WPRecipes, he has helped countless developers through his tutorials and technical guides. Jung is also a published author of the WordPress 2.7 Cookbook and a regular contributor to prestigious publications like Smashing Magazine. Known for prioritizing quality over quantity in his work, he advocates for passion in web development and believes in making technical knowledge accessible to others. His expertise spans multiple programming languages, with a focus on PHP, WordPress, HTML/CSS, and JavaScript development.

«
»

Leave a Reply

Your email address will not be published. Required fields are marked *