<<

Numbers and Dates with PHP

Numbers

Numbers can be integer or double. Integer number stores whole numbers. Integer number can have positive or negative sign. By default, is it positive, so the + sign can be omitted when write positive numbers. The maximum value for integer number is – 2147483648 to +2147483647. PHP_INT_MAX constant is used by to store this value. For example,

$max = PHP_INT_MAX; echo "Maximum value for PHP constant is: $max";

Then the output is:

Maximum value for PHP constant is: 2147483647;

Floating point numbers are also known as floats, doubles or real numbers. Floating point number stores fraction value. To store a number as a floating point number, it must be written with .( point). That means, if a variable assign a value 1 then the of a variable is treated as integer. A variable assign a value 1. (one with decimal point) then the data type of a variable is considered as double. Exponential notation can be used in double data type. The exponential notation is consisting of two parts. Mantissa and exponent. This number is written as mantissa e exponent. Mantissa can be integer or floating point number. The exponent must be integer number. The range for exponent is -307 to +308. The exponential notation expand to m * 10e. For example, 3.5e4 expand to 3.5* 104 means 3.5 * 10000 = 35000. In the same way -3.25e-2 expands -3.25*10(-2) = -3.25 * 1/100 = -0.0325. In exponential form the sign of mantissa determine the overall number is positive or negative and the sign of exponent specifies that the number is large or small than 1.

If the number is outside of the range of double value, then it is converted by positive or negative infinity. Positive infinity is represented by the constant named INF. Negative infinity is represented by the constant named –INF. You can directly assign infinity to a variable or the result of an operation may be infinity. Generally, most operation where one operand is infinity, the result is infinity. The exception is when a value is divide by zero, it returns zero.

In case you divide a value by zero, PHP generates warning.

To check whether the variable or expression is infinite, there are two functions available. These functions are:

Function Description is_infinite($value) Reruns true if the $value is infinite else false. is_finite($value) Reruns false if the $value is infinite else true.

For example:

$testinf = is_infinite(10*INF);

Page 1 of 12

echo "
the value of '10 * INF' is : $testinf"; will display 1 on browser.

In-Built useful Number Functions

Function Description abs($value) Returns the absolute value of $value ceil($value) Returns the value rounded up to the next highest integer number . Floor Returns the value rounded down to the next lowest integer number. max($v1, $v2 [,$v3, $v4…]) Returns the maximum value among $v1, $v2,$v3,$v4… min($v1, $v2 [,$v3, $v4…]) Returns the minimum value among $v1, $v2,$v3,$v4… pi() Returns the value of PI (Approximate value of PI is 3.14) pow($base,$exp) Returns the value of $base raise to $exp. round($value [, $precision]) Returns the rounded value of $value to the decimal point specified by $precision. If $precision is omitted, this function consider $precision default value 0. If $precision is negative, this function rounds to a whole number. For example, in case $precision is -1,then it rounds to $value to the nearest 10. If $precision is -2 then it rounds to $value to the nearest 100. sqrt($value) Returns the square root of $value. mt_rand() This functions return a random number using Mersenne Twister function.

Type Casting:

Type casting is used to convert one data type to another type. To type cast a value, write the data type in parentheses before the value. Below are few examples of type casting.

// Type casting

$value = 31.8;

$intcast = (int)$value; echo "
The original $value after casting to integer becomes: $intcast ";

//with string

Page 2 of 12

$value = "31.8 Kilometers"; // strings after the number is ignored

$strint = (int)$value; echo "
The original '$value' after casting to integer becomes: $strint ";

//,

$value = "31,000 Kilometers";

$strint = (int)$value; echo "
The original '$value' after casting to integer becomes: $strint ";

// string and number_format

$value = "Kilometres 31,000"; // strings which not start with number is converted to 0

$strint = (int)$value; echo "
The original '$value' after casting to integer becomes: $strint ";

//only string

$value = "Kilometres";

$strint = (int)$value; echo "
The original '$value' after casting to integer becomes: $strint ";

//out of range value

$value = '10000000000';

$strint = (int)$value; echo "
The original '$value' after casting to integer becomes: $strint ";

The output is:

The original 31.8 after casting to integer becomes: 31 The original '31.8 Kilometers' after casting to integer becomes: 31 The original '31,000 Kilometers' after casting to integer becomes: 31 The original 'Kilometres 31,000' after casting to integer becomes: 0 The original 'Kilometres' after casting to integer becomes: 0 The original '10000000000' after casting to integer becomes: 2147483647

Sprintf

Page 3 of 12

The sprint function is used to format strings and numbers. The general syntax of sprintf function is: sprintf(format, $val1 [,$val2 ….])

The format parameter can take any one value of for formatting $val. The format parameter can take any one of the following data type s : string d : integer f: double/decimal value e: exponential notation : convert integer value corresponding to equivalent ASCII character.

The format-code must start with % symbol end ends with data type.

Few examples for sprintf function is shown below.

//sprintf examples

$msg = sprintf("The book on %s has %d pages","PHP", 543); echo "
$msg";

$s1 = sprintf("%c",65); echo "
The ASCII character for value 65 is : $s1";

$s2 = sprintf("%06d",42); echo "
The value 42 padded with 0 for length 0f 6 is: $s2";

$date = sprintf("%02d-%02d-%04d", 3,5,2015); echo "
Print the date in DD-MM-YYYY format : $date";

$s4 = sprintf("%09.2f", 123.4567890);

Page 4 of 12

echo "
The value is: $s4";

The output of the above code is:

The book on PHP has 543 pages The ASCII character for value 65 is : A The value 42 paddedwith 0 for length 0f 6 is: 000042 Print the date in DD-MM-YYYY format : 03-05-2015 The value is: 000123.46

Date:

PHP is used timestamp to display date and time. Timestamp stores an integer value, which stores the numbers of second since midnight on January 1, 1970 GMT (Greenwich Mean Time). This point of time is known as the Unix Epoch. Timestamp stored as a 32-bit signed integer number by most systems in the world. Hence these system timestamp can range from December 13, 1901 to January 19, 2038. When the system uses timestamps, reaches its upper limit January 19, 2038 its rolls over to the lower limit in 1901. When this may happens, it may create many problems. This problem is known as the year 2038 problem. This problem is similar to Y2K problem, so year 2038 problem is also known as Y2K38 problem. One way to solve the Y2K38 problem is to use DateTime objects. The DateTime object is explain later on.

To create and format timestamp date( ) is used. The general syntax for date( ) function is:

Date($format [, $timestamp])

Where $format represents various formatting option for date and $ts is a timestamp.

The date function returned the formatted timestamp. The format is specified in $format. By default the time stamp is current date and time. The $timestamp can be specified for any date or time.

For example:

$d = date('j-n-Y'); echo "
Today is $d"; display

Today is 31-5-2015.

There are many formatting options available. Following table shows few formatting options.

Page 5 of 12

Format Description j Day of month without leading zero. d Day of month with leading zero. D Day of week in three letters (i.e.: Mon). l Day of week full-name (i.e.: Monday) n Month number without leading zero m Month number with leading zero M Month name in three letters. S Ordinal Suffix of a day F Full Month Name. y Year in two digits. Y Year in four digits. L Leap year or not. For leap year it is return 1 otherwise 0. h Hours in 24 hour format without leading zero. g Hours in 12 hour format without leading zero. H Hours in 24 hour format with leading zero. G Hours in 12 hour format with leading zero i Minutes with leading zero s Seconds with leading zero A AM/PM in uppercase a am/pm in lowercase U Seconds since unix epoch

For example,

$d = date('j-n-Y \a\t H:i A '); echo "
Today is $d"; will display

Today is 31-5-2015 at 08:57 AM

Useful functions for working with Timestamps

Function Description time() Returns current date time as timestamp mktime([$h [,$m [,$s [,$M [,$D [,$Y]]]]]]) Returns timestamp based on the parameters passed. If any parameter is skipped, then the value of current date and time is set. checkdate($M,$D,$Y) Returns true if the $M (month), $D (date) and $Y (year) provide valid date. getdate([$ts]) Returns an array having parts of time

Page 6 of 12

stamp. If $ts is omitted, it uses current date and time.

Following code shows use of timestamp functions:

$ts = time(); echo "
The value of current time stamp is : $ts";

$mts = mktime(10, 10, 00,13, 4, 2012 ); echo "
The new time stamp has value: $mts";

$chkdt = checkdate(11,30,2015); echo "
30 Novemebr 2015 by checkdate returns: $chkdt
";

Then the output will be:

The value of current time stamp is : 1433058159 The new time stamp has value: 1357290600

30 November 2015 by checkdate returns: 1

You can find many timestamp functions at PHP manual on the web.

Strtotime function in PHP

The strtotime function returns timestamp for a string. The general syntax is

Strtotime($str [,$ts])

If timestamp $ts is omitted, then this functions consider current date and time as timestamp. Whenever timestamp $ts is specified, then it works relative to specified timestamp $ts. The strtotime functions supports most of the date and time formats and most relative time specifications.

Below shows few examples of absolute templates used with strtotime function.

$date1 = strtotime('2015-06-01'); //Mon June 1 2015 00:00

$date2 = strtotime(‘Jun 1’); //Mon June 1 2015 00:00

$date3 = strtotime(‘6:45’); // Mon June 1 2015 6:45

The following code snippets represent relative templates with strtotime function.

//Assume that the current date time is 06/01/2015 10:44:00 PM (June 1, 2015)

$date4 = strtotime('+1 hour'); //Mon 06/01/2015 11:44:00 PM

Page 7 of 12

$date5 = strtotime(‘-2 days’); //Sat 05/30/2015 11:44:00 PM

$date6 = strtotime(‘next Sunday’) //Sun 06/07/2015 00:00

Datetime

 The datetime class facilitate to work with date and time using an object-oriented way.  To create datetime object pass any string to the DateTime class constructor. The string passed in the constructor is string which is any string which accepted by the strtotime function.

The general syntax of creating datetime object is: new DateTime([$param])

Following table shows the generally used methods of DateTime object.

Method Description format($format) Returns a formatting string with $format. The formatting options are the same as used with the date function. setTime($h, $m, $s) Set time using hour $h, minute $m and second $s setDate($y, $m, $d) Set date using year $y, month $m and date $d modify($str) Modify the date and time based on the formatting string $str. This function works similar to the strtotime function for a relative date or time. getTimestamp() Gets the date and time as timestamp. setTimestamp($ts) Sets the date and time using timestamp $ts.

To get the current date and time, do not required passing any parameter. Following code snippet displays current date and time.

$dt = new DateTime();

$disp = $dt->format('d-m-Y h:m:s '); echo $disp;

?>

22-11-2015 01:11:47 [Considering today is November 22,2015]

The following code shows the use of setTime function.

Page 8 of 12

$t = new DateTime(); echo $t->format('d-m-Y h:m:s');

$t->setTime(4,07,15); echo "
".$t->format('d-m-Y g:i:s a');

?>

22-11-2015 03:11:14 22-11-2015 4:07:15 am

To modify the date and time modify function is used. Before using the modify function, clone the object and apply the modify function.

$invoicedate = new DateTime('2014-03-23 14:30:18');

$due_date = clone $invoicedate; echo " Invoice date is:".$invoicedate->format('M j Y g:i:s a');

$due_date->modify('+4 weeks'); echo "
Due Date (After 4 weeks of invoice date) is: ".$due_date->format('M j Y \a\t g:i:s a');

?>

Invoice date is:Mar 23 2014 2:30:18 pm Due Date (After 4 weeks of invoice date) is: Apr 20 2014 at 2:30:18 pm

A timestamp can be converted to datetime object.

$tomorrow = strtotime('tomorrow 8am');

$nextday = new DateTime();

$nextday->setTimestamp($tomorrow); echo $nextday->getTimestamp();

?>

The output of the above code is:

Page 9 of 12

1448262000

DateInterval Class

 The date interval class is used to represent a span of time.  The syntax to create dateinterval class object o New DateInterval($str) . The string $str must be start with P (period of time for Date) . The string $str can take T to represent period of time.

Following table represents the parts of the interval string.

Part Description Example P Begins the interval code nY Specifies the number of years P1Y nM Specifies the number of 1. P3M Months 2. P2Y6M nW Specifies the number of 1. P2W Weeks 2. P1M3W nD Specifies the number of days 1. P5D 2. P1Y2M3D T Begins the time portion of the interval code. nH Specifies the number of hours 1. PT2H 2. P3DT10H nM Specifies the number of 1. PT10M minutes 2. P1MT2H3M nS Specifies the number of 1. PT20S seconds 2. P1Y1MT1M12S

Following code snippet using DateInterval object

$i1 = new DateInterval('P30D'); // 30 Days Interval print_r($i1);

DateInterval Object ( [y] => 0 [m] => 0 [d] => 30 [h] => 0 [i] => 0 [s] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )

Below are few code which demonstrate the use of DateInterval

$i2 = new DateInterval('P1Y23D'); // 1 Year 23 Days

$i3 = new DateInterval('PT1H2M12S'); // 1 Hour 2 Minutes 12 Second

Page 10 of 12

$i4 = new DateInterval('P1Y23DT2H5M12S'); // 1 Year 23 Days 2 Hours 5 Minutes 12 Seconds

To display the interval format function of the DateInterval object is used. The format method takes format parameter as string. It allows following format code.

Syntax:

Format($format)

The codes for formatting are described below.

Code Description %R Sign of the interval + for positive interval value and – for negative interval value. %y Years %m Months %d Days %h Hours %i Minutes %s Seconds

For example,

$i5 = new DateInterval('P2M10D'); echo "
".$i5->format('%m months, %d days'); will print

2 months, 10 days

Use the DateInterval and DateTime classes together

Following table shows 3 more methods of DateTime object which uses DateInterval objects.

Name Description add($interval) Add the $interval time sub($interval) Subtract the $interval time diff($date) Returns a DateInterval object which represents the amount of time between the current Datetime object and $date.

The following code shows example for sub method.

$votingage = new DateInterval('P18Y');

$dob = new DateTime();

Page 11 of 12

$dob->sub($votingage); echo '
You can vote only if you were born on or before: '. $dob->format('j/n/Y');

?>

The output will be

You can vote only if you were born on or before: 23/11/1997

Page 12 of 12