Awesome date functions PHP

Dates are always an important part of any website but sometime it's very difficult to deal with, especially for beginners. So here is a list of a few some important php functions and code snippets that will definitely help you dealing with dates.

Php Date

Get Current time :
It's basic function takes no parameters and returns the current date. This example uses British date formatting, you can change it on line 2.

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

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

$originalDateNow = "2016-10-29";
$newDateNow = date("d-m-Y", strtotime($originalDateNow));

Convert minutes to hours and minutes :
This 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.

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

Get A week Number from date :
Sometime you need to find the week number of a particular date. Pass your date as a parameter to this function, and it will return you the week number.

function findWeekNumber($ndate){
 $res = new DateTime($ndate);
 return $res->format("W");

Difference between two dates:
This function takes two dates and returns the interval between two dates. The result is set to be displayed in hours and minutes.

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

Check date is past or future :
Sometime you need to check that date which you are using is past date and future. So these functions will help you.

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

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

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

Calculate age from date :
Very useful on websites where you need to check that a person is over a certain age to create an account.

function getAge($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;

I hope you like the post . If you like please share.

No comments:

Post a Comment

Download the eBook of react js for beginners

ReactJS basically is an open-source JavaScript library which is used for building user interfaces specifically for single page applications...