আগামী ১৫ ডিসেম্বর -২০১৭ তারিখ থেকে শুরু হচ্ছে পাঁচ মাস ব্যাপী Professional Web Design and Development with HTML, CSS PHP,MySQL,JavaScript, AJAX, JQUERY, Bootstrap and Live Project কোর্সের ৮৭ তম ব্যাচ এবং ২৬ ডিসেম্বর-২০১৭ তারিখ থেকে শুরু হচ্ছে চার মাস ব্যাপী Zend PHP-7 Certified PHP Engineering (Advance PHP) কোর্সের ৩৫ তম ব্যাচ। প্রত্যেকটি কোর্স এর ফী নির্ধারণ করা হয়েছে ৩০,০০০/= আগ্রহীদেরকে অতিসত্বর মাসুদ আলম স্যার এর সাথে যোগাযোগ করতে অনুরোধ করা যাচ্ছে। স্যার এর মোবাইল: 01722 81 75 91

php working with dates and times

PHP Date and Time

Timestamp

Problem:

 

What’s a timestamp?

 

A timestamp is the number of seconds from January 1, 1970 at 00:00. Otherwise known as the Unix Timestamp, this measurement is a widely used standard that PHP has chosen to utilize.

The below example shows the number of seconds from January 1, 1970 at  00:00.

<?php

echo time();

//Output: 1319421504

?>

Probem:

 

How to display current date and  time using php?

 

Solution:

 

Using PHP’s date() function to show current date and time

<?php
echo date("m/d/y");
?>

Now that you know the basics of using PHP’s datefunction, you can easily plug in any of the following letters to format your timestamp to meet your needs.

Important Full Date and Time:

  • r: Displays the full date, time and timezone offset. It is equivalent to manually entering date(“D, d M Y H:i:s O”)

Time:

  • a: am or pm depending on the time
  • A: AM or PM depending on the time
  • g: Hour without leading zeroes. Values are 1 through 12.
  • G: Hour in 24-hour format without leading zeroes. Values are 0 through 23.
  • h: Hour with leading zeroes. Values 01 through 12.
  • H: Hour in 24-hour format with leading zeroes. Values 00 through 23.
  • i: Minute with leading zeroes. Values 00 through 59.
  • s: Seconds with leading zeroes. Values 00 through 59.

Day:

  • d: Day of the month with leading zeroes. Values are 01 through 31.
  • j: Day of the month without leading zeroes. Values 1 through 31
  • D: Day of the week abbreviations. Sun through Sat
  • l: Day of the week. Values Sunday through Saturday
  • w: Day of the week without leading zeroes. Values 0 through 6.
  • z: Day of the year without leading zeroes. Values 0 through 365.

Month:

  • m: Month number with leading zeroes. Values 01 through 12
  • n: Month number without leading zeroes. Values 1 through 12
  • M: Abbreviation for the month. Values Jan through Dec
  • F: Normal month representation. Values January through December.
  • t: The number of days in the month. Values 28 through 31.

Year:

  • L: 1 if it’s a leap year and 0 if it isn’t.
  • Y: A four digit year format
  • y: A two digit year format. Values 00 through 99.

Other Formatting:

  • U: The number of seconds since the Unix Epoch (January 1, 1970)
  • O: This represents the Timezone offset, which is the difference from Greenwich Meridian Time (GMT). 100 = 1 hour, -600 = -6 hours

Getting the Current Date and Time Using PHP’s getdate() function

Problem:

How to display the current date and/or time?

 

Solution:

Using PHP’s getdate() function we can display the  current date and/or time:

 

<?php

// get current date and time

$now = getdate();

// turn it into strings

$currentTime = $now["hours"]+6 . ":" . $now["minutes"] .":" . $now["seconds"];

$currentDate = $now["mday"] . "." . $now["mon"] . "." . $now["year"];

// result: "It is now 12:37:47 on 30.10.2006" (example)

echo "It is now $currentTime on $currentDate";

?>

Comments

PHP’s getdate() function returns an array of values representing different components of the current date and time. Here’s an example of what the array might look like:

Array

(

[seconds] => 34

[minutes] => 14

[hours] => 9

[mday] => 23

[wday] => 2

[mon] => 5

[year] => 2006

[yday] => 137

[weekday] => Monday

[month] => February

[0] => 1107752144

)

As the previous listing illustrates, it’s easy enough to use this array to generate a human-readable date and time value. However, formatting options with getdate() are limited, so if you need to customize your date/time display extensively, look at the listing in :” Formatting Timestamps” for an alternative way of accomplishing

the same thing.

NOTE

Notice that the 0th  element of the array returned by getdate() contains a UNIX timestamp representation of the date returned—the same one that mktime() would generate.

Formatting Timestamps

Formatting TimeStamp

Problem:

How to turn a UNIX timestamp into a human-readable string?

 

Solution:

Using PHP’s date() function to alter the appearance of the timestamp with various formatting codes:

<?php

// get date

// result: "30 Oct 2006" (example)

echo date("d M Y"). " <br>";

// get time

// result: "12:38:26 PM" (example)

echo date("h:i:s A"). " <br>";

// get date and time

// result: "Monday, 30 October 2006, 12:38:26 PM" (example)

echo date ("l, d F Y, h:i:s A") . " <br>";

// get time with timezone

// result: "12:38:26 PM UTC"

echo date ("h:i:s A T") . " <br>";

// get date and time in ISO8601 format

// result: "2006-10-30T12:38:26+00:00"

echo date ("c");

?>

Comments:

PHP’s date() function is great for massaging UNIX timestamps into different formats. It accepts two arguments—a format string and a timestamp—and uses the format string to turn the timestamp into a human-readable value. Each character in the format string has a special meaning, and you can review the complete list at http://www.php.net/date.

Checking Date Validity

Checking Date Validity

Problem:

How to check a particular date is valid?

 

Solution:

Using PHP checkdate() function:

<?php

// check date 31-Apr-2006

// result: "valid date"

echo checkdate(10,25,2011) ? "Valid date" : "Invalid date";

echo"<br>";

// result: "Invalid date"

echo checkdate(31,4,2006) ? "Valid date" : "Invalid date";

?>

Comments:

Applications that accept date input from a user must validate this input before using it  for calculations or date operations. The checkdate() function simplifies this task considerably. It accepts a series of three arguments, representing day, month and year, and returns a Boolean value indicating whether the combination make up

a legal date.

An alternative way of accomplishing the same thing can be found in the PEAR Calendar class, available from http://pear.php.net/package/Calendar.

This class offers an isValid() method to test the validity of a particular date value.

 

The following listing illustrates this:

 

<?php

// include Calendar class

include "calendar/Day.php";

// initialize Day object to 31-Apr-2006

//$day = & new Calendar_Day(2006, 4, 31);

$day = & new Calendar_Day(2011,10,25);

// check date

// result: "Invalid date"

echo $day->isValid() ? "Valid date" : "Invalid date";

?>

Converting Strings to Timestamps

Converting Strings to Timestamps

 

Problem

How to convert a time string, encapsulating a date or time value, into the corresponding UNIX timestamp

Solution

Using PHP strtotime() function:

<?php

// define string

//$str = "20030607";

$str =time();

// convert string to timestamp

$ts = strtotime($str);

&nbsp;

// format as readable date/time value

// result: "Saturday, 07 June 2003 12:00:00 AM" (example)

echo ($ts === -1) ? "Invalid string" : date("l, d F Y h:i:s A", $ts);

?>

Comments

PHP’s strtotime() function performs the very important function of converting a human-readable date value into a UNIX timestamp, with minimal calculation required on the part of the application. The date value can be any English-language date descriptor; strtotime() will attempt to identify it and return the corresponding timestamp. If strtotime() cannot convert the description to a timestamp, it will return –1.

In addition to date strings, the strtotime() function also accepts English-language time descriptors like “now,” “next Wednesday,” or “last Friday,” and you can use it to perform rudimentary date arithmetic.

The following listing illustrates this:

<?php

// assume now is "Monday, 30 October 2006 02:56:34 PM"

// define string

$str = "next Friday";

// convert string to timestamp

$ts = strtotime($str);

// format as readable date/time value

// result: "Friday, 03 November 2006 12:00:00 AM"

echo ($ts === false) ? "Invalid string" : date("l, d F Y h:i:s A", $ts)."<br>";

// define string

$str = "2 weeks 6 hours ago";

// convert string to timestamp

$ts = strtotime($str);

// format as readable date/time value

// result: "Monday, 16 October 2006 08:56:34 AM"

echo ($ts === false) ? "Invalid string" : date("l, d F Y h:i:s A", $ts);

?>

Checking for Leap Years

 Checking for Leap Years

Problem

How to check if a particular year is a leap year?

 

Solution

Write a function to see if the year number is divisible by 4 or 400, but not 100:

<?php

// function to test if leap year

function testLeapYear($year) {

$ret = (($year%400 == 0) || ($year%4 == 0 && $year%100 != 0))? true : false;

return $ret;

}

// result: "Is a leap year"

echo testLeapYear(2004) ? " 2004 Is a leap year<br>" : "2004 Is not a leap year<br>";

// result: "Is not a leap year"

echo testLeapYear(2001) ? "2001 Is a leap year" : "2001 Is not a leap year";

?>

Comments

A year is a leap year if it is fully divisible by 400, or by 4 but not 100. The function testLeapYear() in the previous listing  encapsulates this logic, using PHP’s % operator to check for divisibility, and returns a Boolean value indicating the result.

An alternative way to do this is to use the checkdate() function to test for the presence of an extra day in February of that year.

The following listing illustrates this:

<?php

// function to test if leap year

function testLeapYear($year) {

return checkdate(2, 29, $year);

}

// result: "Is a leap year"

echo testLeapYear(2004) ? "2004 Is a leap year<br>" : "2004 Is not a leap year<br>";

// result: "Is not a leap year"

echo testLeapYear(2001) ? "2001 Is a leap year" : "2001 Is not a leap year";

?>

Finding the Number of Days in a Month

Finding the Number of Days in a Month 

Problem:

How to find the number of days in a particular month?

Solution:

Use PHP’s date() function with the “t” modifier:

<?php

// get timestamp for month and year Mar 2005

$ts = mktime(0,0,0,2,1,2005);

//$ts = time();

// find number of days in month

// result: 31

echo date("t", $ts);

?>

Comments

Given a UNIX timestamp, the date() function’s “t” modifier returns the number of days in the corresponding month. The return value will range from 28 to 31

Finding the Number of Days or Weeks in a Year

  Finding the Number of Days or Weeks in a Year 

Problem:

How to find the number of days or weeks in a particular year?

Solution:

Use PHP’s date() function with the “z” or “W” modifiers:

<?php

// get total number of days in the year 2001

$numDays = date("z", mktime(0,0,0,12,31,2001))+1;

// get total number of weeks in the year 2001

$numWeeks = date("W", mktime(0,0,0,12,28,2001));

// result: "There are 365 days and 52 weeks in 2001."

echo "There are $numDays days and $numWeeks weeks in 2001.\n";

?>

Comments:

Given a UNIX timestamp, the date() function’s “z” modifier returns the day number in the year, while the “W” modifier returns the week number. By passing a timestamp representation of the last day or last week of the year, it’s possible to quickly find the total number of days or weeks in the year.

Note that the value returned by the “z” modifier is indexed from 0, so it is necessary to add 1 to the final result to obtain the actual number of days in the year.

Finding the Day Name for a Date

 Finding the Day Name for a Date

Problem:

You want to find which day of the week a particular date falls on.

Solution:

Use PHP’s date() function with the “l” modifier:

<?php

// get timestamp for date 04-Jun-2008

$ts = mktime(0,0,0,6,4,2008);

// get day of week

// result: "Wednesday"

echo date("l", $ts);

?>

Comments:

Given a timestamp representing a particular date, the date() function’s “l” modifier returns the weekday name corresponding to that date. If you need a numeric value (0 = Sunday, 1 = Monday …) .

Finding the Year Quarter for a Date

 

Problem:

You want to find which quarter of the year a particular date falls in.

Solution

Use PHP’s date() function with the “m” modifier:

<?php

// get timestamp for date 04-Jun-2008

$ts = mktime(0,0,0,6,4,2008);

// get quarter

// result: 2

echo ceil(date("m", $ts)/3);

?>

Comments

Given a timestamp representing a particular date, the date() function’s ‘m’ modifier returns the month number (range 1–12) corresponding to that date. To obtain the corresponding year quarter, divide the month number by 3 and round it up to the nearest integer with the ceil() function.

 

Converting Local Time to GMT

Problem:

How to convert local time to Greenwich Mean Time (GMT)?

Solution:

Use PHP’s gmdate() function:

<?php

// convert current local time (IST) to GMT

// result: "15:06:25 30-Oct-06 GMT" (example)

echo gmdate("H:i:s d-M-y T") . "<br>";

// convert specified local time (IST) to GMT

// result: "23:00:00 01-Feb-05 GMT" (example)

$ts = mktime(4,30,0,2,2,2005);

echo gmdate("H:i:s d-M-y T", $ts);

?>

Comments:

The gmdate() function formats and displays a timestamp in GMT. Like the date() function, it accepts a format string that can be used to control the final appearance of the date and time value. Conversion to GMT is performed automatically based on the time zone information returned by the operating system.

Converting Between Different Time Zones

 

Problem:

How to obtain the local time in another time zone, given its GMT offset?

Solution

Write a PHP function to calculate the time in the specified zone:

<?php

// function to get time

// for another time zone

// given a specific timestamp and hour offset from GMT

function getLocalTime($ts, $offset) {

// performs conversion

// returns UNIX timestamp

return ($ts - date("Z", $ts)) + (3600 * $offset);

}

// get current local time in Singapore

// result: "00:11:26 31-10-06 SST"

echo date("H:i:s d-m-y", getLocalTime(mktime(), 8)) . " SST \n";

// get current local time in India

// result: "21:41:26 30-10-06 IST"

echo date("H:i:s d-m-y", getLocalTime(mktime(), +5.5)) . " IST \n";

// get current local time in USA (Eastern)

// result: "11:11:26 30-10-06 EST"

echo date("H:i:s d-m-y", getLocalTime(mktime(), -5)) . " EST \n";

// get current local time in USA (Pacific)

// result: "08:11:26 30-10-06 PST"

echo date("H:i:s d-m-y", getLocalTime(mktime(), -8)) . " PST \n";

// get time in GMT

// when it is 04:30 AM in India

// result: "23:00:00 01-02-05 GMT "

echo date("H:i:s d-m-y", getLocalTime(mktime(4,30,0,2,2,2005), 0)) ." GMT \n";

?>

Comments:

Assume here that you’re dealing with two time zones: Zone 1 and Zone 2. The user-defined function getLocalTime() accepts two arguments: a UNIX timestam for Zone 1 and the time zone offset, in hours from GMT, for Zone 2. Because it’s simpler to perform time zone calculations from GMT, the Zone 1 UNIX timestamp is first converted to GMT (see the listing in “3.12: Converting Between Different Time Zones” for more on this step) and then the stated hour offset is added to it to obtain a new UNIX timestamp for Zone 2 time. This timestamp can then be formatted for display with the date() function.

Note that given UNIX timestamps are represented in seconds, the hour offset passed to getLocalTime() must be multiplied by 3600 (the number of seconds in 1 hour) before the offset calculation can be performed.

Note also that if the hour offset passed to getLocalTime() is 0, GMT time will be returned.

TIP

There’s also a third “shortcut” solution to this problem: simply use the date_default_timezone_set() function to set the default time zone to the target city or time zone, and use the date() function to return the local time in that zone. Here’s an example:

<?php

// set default time zone to destination

// result: "00:11:26 31-10-06 SST"

date_default_timezone_set('Asia/Singapore');

echo date("H:i:s d-m-y") . " SST \n";

// set default time zone to destination

// result: "08:11:26 30-10-06 PST"

date_default_timezone_set('US/Pacific');

echo date("H:i:s d-m-y") . " PST \n";

?>

Converting Minutes to Hours

 

Problem:

How to convert between mm and hh:mm formats.

Solution:

Divide or multiply by 60 and add the remainder:

<?php

// define number of minutes

$mm = 156;

// convert to hh:mm format

// result: "02h 36m"

echo sprintf("%02dh %02dm", floor($mm/60), $mm%60);

?>

<?php

// define hours and minutes

$hhmm = "02:36";

// convert to minutes

// result: "156 minutes"

$arr = explode(":", $hhmm);

echo $arr[0]*60 + $arr[1] . " minutes";

?>

Comments:

Which is more easily understood: “105 minutes” or “1 hour, 45 minutes”? The previous listing takes care of performing this conversion between formats. Given the total number of minutes, the number of hours can be obtained by dividing by 60, with the remainder representing the number of minutes. The sprintf() function takes care of sticking the two pieces together. Given a string in hh:mm format, the explode() function splits it on the colon (:) separator, converts the first element from hours to minutes by multiplying it by 60, and then adds the second element to get the total number of minutes.

Comparing Dates

Problem:

How to compare two dates to see which is more recent.

Solution:

Use PHP’s comparison operators to compare the timestamps corresponding to the two dates:

<?php

// create timestamps for two dates

$date1 = mktime(0,0,0,2,1,2007);

$date2 = mktime(1,0,0,2,1,2007);

// compare timestamps

// to see which represents an earlier date

if ($date1 > $date2) {

$str = date ("d-M-Y H:i:s", $date2) . " comes before " .date ("d-M-Y H:i:s", $date1);

} else if ($date2 > $date1) {

$str = date ("d-M-Y H:i:s", $date1) . " comes before " .date ("d-M-Y H:i:s", $date2);

} else {

$str = "Dates are equal";

}

// result: "01-Feb-2007 00:00:00 comes before 01-Feb-2007 01:00:00"

echo $str;

?>

Performing Date Arithmetic

 

Problem:

How to add (subtract) time intervals to (from) a date?

Solution:

Convert the date to a UNIX timestamp, express the time interval in seconds, and add (subtract) the interval to (from) the timestamp:

<?php

// set base date

$dateStr = "2008-09-01 00:00:00";

// convert base date to UNIX timestamp

// expressed in seconds

$timestamp = strtotime($dateStr);

// express "28 days, 5 hours, 25 minutes and 11 seconds"  in seconds

$intSecs = 11 + (25*60) + (5*60*60) + (28*24*60*60);

// add interval (in seconds)  to timestamp (in seconds)

// format result for display

// returns "2008-09-29 05:25:11"

$newDateStr = date("Y-m-d h:i:s", $timestamp + $intSecs);

echo $newDateStr;

?>

Comments:

When you’re dealing with temporal data, one of the more common (and complex) tasks involves performing addition and subtraction operations on date and time values. Consider, for example, the simple task of calculating a date 91 days hence.

Usually, in order to do this with any degree of precision, you need to factor in a number of different variables: the month you’re in, the number of days in that month, the number of days in the months following, whether or not the current year is a leap year, and so on.PHP doesn’t provide built-in functions for this type of arithmetic, but it’s nevertheless fairly easy to do.

The previous listing illustrates one approach to the problem, wherein the time interval is converted to seconds and added to (or subtracted from) the base timestamp, also expressed in seconds.

 

Displaying a Monthly Calendar

 

Problem:

How to print a calendar for a particular month.

Solution:

Use PEAR’s Calendar class:

&nbsp;

<?php

// include Calendar class

include "calendar/Month/Weekdays.php";

include "calendar/Day.php";

// initialize calendar object

$month = new Calendar_Month_Weekdays(2011, 10);

// build child objects (days of the month)

$month->build();

// format as table

echo "<pre>";

// print month and year on first line

echo "          " . sprintf("%02d", $month->thisMonth()) . "/" .$month->thisYear() . "\n";

// print day names on second line

echo "  M   T   W   T   F   S   S\n";

// iterate over day collection

while ($day = $month->fetch()) {

if ($day->isEmpty()) {

echo "    ";

} else {

echo sprintf("%3d", $day->thisDay()) . " ";

}

if ($day->isLast()) {

echo "\n";

}

}

echo "</pre>";

?>

Comments

Displaying a dynamic calendar on a Web page might seem trivial, but if you’ve ever tried coding it firsthand, you’ll know the reality is somewhat different. Better than working your way through the numerous calculations and adjustments, then, is using the PEAR Calendar class, available from http://pear.php.net/package/Calendar. This class is designed specifically to generate a monthly or yearly calendar that you can massage into whatever format you desire.The Calendar package includes a number of different classes, each for a specific purpose.

The previous listing uses the Calendar_Month_Weekdays() class, which provides the methods needed to generate a monthly calendar sorted into weeks. (This is the same type you probably have hanging on your wall.) The class is initialized with a month and year, and its build() method is invoked to build the calendar data structure. A while() loop is then used in combination with the fetch() method to iterate over the Calendar data structure and print each day. Four utility method—isFirst(), isLast(), isEmpty() and isSelected()—enable you

to customize the appearance of particular dates in the month.

The Calendar package is fairly sophisticated, and enables a developer to create and customize a variety of different calendar types. There isn’t enough space here to discuss it in detail, so you should take a look at the examples provided with the package to understand what you can do with it.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I’m a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, Canadian International Development Agency (CIDA), World Vision, Care Bangladesh, Helen Keller, US AID and MAX Group where I worked on ERP software and web development., but now i’m a founder and CEO of TechBeeo Software Company Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.

9 comments on “php working with dates and times

Leave a Reply

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