Php datetime function example

Like any other programming language we have built-in date object in php script, and php datetime function, here we learn how to work with different date format in php script, how to work with date in php programming.

Get Datetime in Php

To get current date we can use php date object, then can create different date format as per our need, but there are some built-in function in php that help us working with date object. Let's learn how to use date, time in php code.

php date format

  • d - Represents the day of the month (01 to 31)
  • m - Represents a month (01 to 12)
  • Y - Represents a year (in four digits)
  • l (lowercase 'L') - Represents the day of the week
<?php            
echo "Date is " . date("Y-m-d") . "<br>";
echo "Today (Day) is " . date("l") . "<br>";;
echo "Today (month) is " . date("m") . "<br>";
echo "Today (date) is " . date("d") . "<br>";
echo "Today (Year) is " . date("Y") . "<br>";
?>

So, remember date("Y-m-d") to get the current date of server in php.

php datetime add

Learn how to add days, months, year in php date, date_add() Function in PHP Syntax date_add(object,interval);

<?php
$date=date_create("2018/05/10");
date_add($date,date_interval_create_from_date_string("50 days"));
echo date_format($date,"Y-m-d");
?>
php date time difference

Find out difference between two dates, date_diff() Function in PHP Syntax date_diff(datetime1,datetime2,absolute);

<?php
$date1=date_create("2018/05/10");
$date2=date_create("2018/12/10");
$diff=date_diff($date1,$date2);
?>
different Time function in Php

Like date object, we can also get time and time zone in php script.

  • date_timestamp_get()

    Returns the Unix timestamp

  • date_timestamp_set()

    Sets the date and time based on a Unix timestamp

  • date_timezone_get()

    Returns the time zone of the given DateTime object

  • date_timezone_set()

    Sets the time zone for the DateTime object

You may be interested in reading following posts:

 
DateTime in Php
Learn php programming, php web development with free tutorials
Other Popular Tutorials
PHP Examples | Join PHP Online Course