What is Date function in php?

date_default_timezone_set("Asia/Calcutta");


date() function is used to show current date.

File name : index.php

<?php
$current_date = date('y/m/d');
echo $current_date;
?>

<?php
$current_date = date('Y/M/D');
echo $current_date;
?>

<?php
$current_date = date('Y/M/D H:i:s');
echo $current_date;
?>

Output :-

16/05/22
2016/may/22

example

File name : index.php

<?php
$nextWeek = time() + (7 * 24 * 60 * 60);
// 7 days; 24 hours; 60 mins; 60 secs
echo 'Now: '. date('Y-m-d') ."\n";
echo 'Next Week: '. date('Y-m-d', $nextWeek) ."\n";
// or using strtotime():
echo 'Next Week: '. date('Y-m-d', strtotime('+1 week')) ."\n";
?>

Output :-

Now: 2016-03-30
Next Week: 2016-04-06
Next Week: 2016-04-06

syntax :

date(format,timestamp);

Specifies the format of the outputted date string. The following characters can be used:

  • d - The day of the month (from 01 to 31)
  • D - A textual representation of a day (three letters)
  • j - The day of the month without leading zeros (1 to 31)
  • l (lowercase 'L') - A full textual representation of a day
  • N - The ISO-8601 numeric representation of a day (1 for Monday, 7 for Sunday)
  • S - The English ordinal suffix for the day of the month (2 characters st, nd, rd or th. Works well with j)
  • w - A numeric representation of the day (0 for Sunday, 6 for Saturday)
  • z - The day of the year (from 0 through 365)
  • W - The ISO-8601 week number of year (weeks starting on Monday)
  • F - A full textual representation of a month (January through December)
  • m - A numeric representation of a month (from 01 to 12)
  • M - A short textual representation of a month (three letters)
  • n - A numeric representation of a month, without leading zeros (1 to 12)
  • t - The number of days in the given month
  • L - Whether it's a leap year (1 if it is a leap year, 0 otherwise)
  • o - The ISO-8601 year number
  • Y - A four digit representation of a year
  • y - A two digit representation of a year
  • a - Lowercase am or pm
  • A - Uppercase AM or PM
  • B - Swatch Internet time (000 to 999)
  • g - 12-hour format of an hour (1 to 12)
  • G - 24-hour format of an hour (0 to 23)
  • h - 12-hour format of an hour (01 to 12)
  • H - 24-hour format of an hour (00 to 23)
  • i - Minutes with leading zeros (00 to 59)
  • s - Seconds, with leading zeros (00 to 59)
  • u - Microseconds (added in PHP 5.2.2)
  • e - The timezone identifier (Examples: UTC, GMT, Atlantic/Azores)
  • I (capital i) - Whether the date is in daylights savings time (1 if Daylight Savings Time, 0 otherwise)
  • O - Difference to Greenwich time (GMT) in hours (Example: +0100)
  • P - Difference to Greenwich time (GMT) in hours:minutes (added in PHP 5.1.3)
  • T - Timezone abbreviations (Examples: EST, MDT)
  • Z - Timezone offset in seconds. The offset for timezones west of UTC is negative (-43200 to 50400)
  • c - The ISO-8601 date (e.g. 2013-05-05T16:34:42+00:00)
  • r - The RFC 2822 formatted date (e.g. Fri, 12 Apr 2013 12:01:05 +0200)
  • U - The seconds since the Unix Epoch (January 1 1970 00:00:00 GMT)
  • timestamp Optional. Specifies an integer Unix timestamp. Default is the current local time (time())


    How can we know the number of days between two given dates using PHP?

    File name : index.php

    <?php
    $date1 = date('Y-m-d');
    $date2 = '2015-05-21';
    $days = (strtotime($date1) - strtotime($date2)) / (60 * 60 * 24);
    echo "Number of days : $days";
    ?>

    Calculating Hours Difference in PHP

    File name : index.php

    <form id="frmDate" action="" method="post">
    <div>
    <label style="padding-top:20px;">Start Date</label><br/>
    <input type="text" name="startdate" value="<?php if(!empty($_POST["startdate"])) { echo $_POST["startdate"]; } ?>" class="demoInputBox">
    </div>

    <div>
    <label>End Date</label>
    <span id="userEmail-info" class="info"></span><br>
    <input type="text" name="enddate" value="<?php if(!empty($_POST["startdate"])) { echo $_POST["enddate"]; } ?>" class="demoInputBox">
    </div>

    <div>
    <input type="submit" name="submit" value="Find Difference" class="btnAction">
    </div>
    </form>


    <?php
    function differenceInHours($startdate,$enddate){
    $starttimestamp = strtotime($startdate);
    $endtimestamp = strtotime($enddate);
    $difference = abs($endtimestamp - $starttimestamp)/3600;
    return $difference;
    }
    if(!empty($_POST["submit"])) {
    $hours_difference = differenceInHours($_POST["startdate"],$_POST["enddate"]);
    $message = "The Difference is " . $hours_difference . " hours";
    }
    ?>

    Output :-


    getdate()

    This function will return array of date components, like, mday, wday, month, year, hour and etc

    File name : index.php

    <?php
    print "<br/><br/><b>PHP getdate() returns current date components.</b><br/>";
    $current_date_components = getdate();
    print "<PRE>";
    print_r($current_date_components);
    print "</PRE>";
    ?>

    Output :-

    PHP getdate() returns current date components.
    Array
    (
    [seconds] => 46
    [minutes] => 19
    [hours] => 12
    [mday] => 28
    [wday] => 6
    [mon] => 5
    [year] => 2016
    [yday] => 148
    [weekday] => Saturday
    [month] => May
    [0] => 1464430786
    )

    date_format()

    date_format() expects two argument, DateTime object and date format. The following PHP example shows how to create DateTime object from a date and use this object in date_format() function.

    File name : index.php

    <?php
    $date=date_create("3-6-2007");
    // returns date as 3rd June, 2007
    echo date_format($date,"jS F, Y");
    ?>

    Output :-

    3rd June, 2007

    Timestamp

    time()

    This is the simple and widely used PHP function to get current timestamp value. It requires no arguments to be sent for returning expected resultant UNIX timestamp.

    File name : index.php

    <?php
    $current_timestamp = time();
    echo $current_timestamp;
    ?>

    <?php
    $current_timestamp = strtotime("now");
    echo $current_timestamp;
    ?>

    mktime()

    This function is also used to get UNIX timestamp, but requires set of parameters denoting date components, like hour, minute, second, month, day, year, in the same order specified here. And also have an optional flag representing day light saving time state. And for getting, current timestamp, we have to use PHP date() function within this function, with corresponding parameter for getting current hour, minute, in required order. For example,

    File name : index.php

    <?php
    $current_timestamp_by_mktime = mktime(date("H"),date("i"),date("s"),date("m"),date("d"),date("Y"));
    echo $current_timestamp_by_mktime;
    ?>

    Time Ago Function

    timeago() function the given date is converted into timestamp using PHP built-in strtotime(). And, this timestamp is subtracted from the current timestamp to calculate elapsed time. The time elapsed from the given date till now is used to calculate the time-ago string.

    File name : index.php

    <form name="frmTimeAgo" method="post">
    Enter Date:
    <input type="date" name="date-field" value="<?php if(!empty($_POST["date-field"])) { echo $_POST["date-field"]; } ?>"/>
    <input type="submit" name="submit-date" value="Submit Date" >
    </form>
    <?php
    if(!empty($strTimeAgo)) {
    echo "Result: " . $strTimeAgo;
    }
    ?>

    File name : index.php

    <?php
    $strTimeAgo = "";
    if(!empty($_POST["date-field"])) {
    $strTimeAgo = timeago($_POST["date-field"]);
    }
    function timeago($date) {
    $timestamp = strtotime($date);

    $strTime = array("second", "minute", "hour", "day", "month", "year");
    $length = array("60","60","24","30","12","10");

    $currentTime = time();
    if($currentTime >= $timestamp) {
    $diff = time()- $timestamp;
    for($i = 0; $diff >= $length[$i] && $i < count($length)-1; $i++) {
    $diff = $diff / $length[$i];
    }

    $diff = round($diff);
    return $diff . " " . $strTime[$i] . "(s) ago ";
    }
    }

    ?>

    strtotime()

    The strtotime() function is used to convert an English textual date-time description to a UNIX timestamp.

    File name : index.php

    echo date("Y-m-d", strtotime("now"))."\n";

    Change Date Format :- YYYY-MM-DD to DD-MM-YYYY

    The strtotime() function is used to convert date format.

    File name : index.php

    $created_at = "2020-07-5";
    $newDate = date("d-m-Y", strtotime($created_at));
    $newDate = date("m-d-Y", strtotime($created_at));
    echo "New date format is: ".$newDate. " (DD-MM-YYYY)";





    Previous Next


    Trending Tutorials




    Review & Rating

    0.0 / 5

    0 Review

    5
    (0)

    4
    (0)

    3
    (0)

    2
    (0)

    1
    (0)

    Write Review Here