Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Ten PHP Code Snippets to Work With Dates

DZone's Guide to

Ten PHP Code Snippets to Work With Dates

Dates are always an important part of any website or app, but they can be a little tricky to deal with, especially for beginners. Here is a list of a few PHP functions and code snippets that will definitely come in handy when dealing with dates.

· Web Dev Zone
Free Resource

Learn how to build modern digital experience apps with Crafter CMS. Download this eBook now. Brought to you in partnership with Crafter Software

Dates are always an important part of any website or app, but they can be a little tricky to deal with, especially for beginners. Here is a list of a few PHP functions and code snippets that will definitely come in handy when dealing with dates.

Get Current Time, Formatted

Here's a super basic function—takes no parameters and returns the current date. This example uses British date formatting, but you can change the format on line 2.

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

Format a Date

Here's 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 & 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 in the 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. It's 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

Crafter is a modern CMS platform for building modern websites and content-rich digital experiences. Download this eBook now. Brought to you in partnership with Crafter Software.

Topics:
date ,code snippets ,datetime ,snippets ,function ,basic ,class

Published at DZone with permission of Jean-Baptiste Jung, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}