Monday, November 2, 2009

Time functions in PHP

Getting time in the right format can be a challenge. The default format is unix timestamp (a number giving the number of seconds since January 1 1970 00:00:00 UTC). However one often want to extract the date in a certain format for display purposes or for use in databases.

There are some functions that are useful for doing this. They are date(),strtotime(), mktime().

mktime will return the unix timestamp from the arguments passed into it, e.g. one can give it minutes, hours, days,months, years:
mktime(0,0,0,3,20,2004) which is "20/03/2004 00:00:00" will be 1079737200.

date will return a string formatted according to the given format. Several arguments can be given, including "Y" for 2009 while "y" gives 09 etc. Examples:
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310

date("d, m, Y", mktime(0,0,0,3,20,2004)) // 20, 03, 2004
date("d, m, Y", strtotime("now")) // 03, 11, 2009 )

currentWeek = date("W", strtotime("now")) //45 for 03.11.2009

strtotime will take a string and try to convert it into a unix timestamp. An example is "now" which will give the time right now in unix timestamp. Other examples are strtotime("10 September 2000") and strtotime("+1 day").


No comments:

Post a Comment