How to get the week starting date by giving a week number and the year. Monday first day in week
<?php
function WeekStartDate($week,$year,$format="d-m-Y") {
date_default_timezone_set('Europe/Paris');
$firstDayInYear=date("N",mktime(0,0,0,1,1,$year));
if ($firstDayInYear<5)
$shift=-($firstDayInYear-1)*86400;
else
$shift=(8-$firstDayInYear)*86400;
if ($week>1) $weekInSeconds=($week-1)*604800; else $weekInSeconds=0;
$timestamp=mktime(0,0,0,1,1,$year)+$weekInSeconds+$shift;
return date($format,$timestamp);
}
echo WeekStartDate(44,2011);
//result: 31-10-2011
?>
date
(PHP 4, PHP 5)
date — Format a local time/date
Description
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().
Parameters
- format
-
The format of the outputted date string. See the formatting options below. There are also several predefined date constants that may be used instead, so for example DATE_RSS contains the format string 'D, d M Y H:i:s'.
The following characters are recognized in the format parameter string format character Description Example returned values Day --- --- d Day of the month, 2 digits with leading zeros 01 to 31 D A textual representation of a day, three letters Mon through Sun j Day of the month without leading zeros 1 to 31 l (lowercase 'L') A full textual representation of the day of the week Sunday through Saturday N ISO-8601 numeric representation of the day of the week (added in PHP 5.1.0) 1 (for Monday) through 7 (for Sunday) S English ordinal suffix for the day of the month, 2 characters st, nd, rd or th. Works well with j w Numeric representation of the day of the week 0 (for Sunday) through 6 (for Saturday) z The day of the year (starting from 0) 0 through 365 Week --- --- W ISO-8601 week number of year, weeks starting on Monday (added in PHP 4.1.0) Example: 42 (the 42nd week in the year) Month --- --- F A full textual representation of a month, such as January or March January through December m Numeric representation of a month, with leading zeros 01 through 12 M A short textual representation of a month, three letters Jan through Dec n Numeric representation of a month, without leading zeros 1 through 12 t Number of days in the given month 28 through 31 Year --- --- L Whether it's a leap year 1 if it is a leap year, 0 otherwise. o ISO-8601 year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in PHP 5.1.0) Examples: 1999 or 2003 Y A full numeric representation of a year, 4 digits Examples: 1999 or 2003 y A two digit representation of a year Examples: 99 or 03 Time --- --- a Lowercase Ante meridiem and Post meridiem am or pm A Uppercase Ante meridiem and Post meridiem AM or PM B Swatch Internet time 000 through 999 g 12-hour format of an hour without leading zeros 1 through 12 G 24-hour format of an hour without leading zeros 0 through 23 h 12-hour format of an hour with leading zeros 01 through 12 H 24-hour format of an hour with leading zeros 00 through 23 i Minutes with leading zeros 00 to 59 s Seconds, with leading zeros 00 through 59 u Microseconds (added in PHP 5.2.2) Example: 654321 Timezone --- --- e Timezone identifier (added in PHP 5.1.0) Examples: UTC, GMT, Atlantic/Azores I (capital i) Whether or not the date is in daylight saving time 1 if Daylight Saving Time, 0 otherwise. O Difference to Greenwich time (GMT) in hours Example: +0200 P Difference to Greenwich time (GMT) with colon between hours and minutes (added in PHP 5.1.3) Example: +02:00 T Timezone abbreviation Examples: EST, MDT ... Z Timezone offset in seconds. The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. -43200 through 50400 Full Date/Time --- --- c ISO 8601 date (added in PHP 5) 2004-02-12T15:19:21+00:00 r » RFC 2822 formatted date Example: Thu, 21 Dec 2000 16:01:07 +0200 U Seconds since the Unix Epoch (January 1 1970 00:00:00 GMT) See also time() Unrecognized characters in the format string will be printed as-is. The Z format will always return 0 when using gmdate().
Note:
Since this function only accepts integer timestamps the u format character is only useful when using the date_format() function with user based timestamps created with date_create().
- timestamp
-
The optional timestamp parameter is an integer Unix timestamp that defaults to the current local time if a timestamp is not given. In other words, it defaults to the value of time().
Return Values
Returns a formatted date string. If a non-numeric value is used for timestamp, FALSE is returned and an E_WARNING level error is emitted.
Errors/Exceptions
Every call to a date/time function will generate a E_NOTICE if the time zone is not valid, and/or a E_STRICT or E_WARNING message if using the system settings or the TZ environment variable. See also date_default_timezone_set()
Changelog
Version | Description |
---|---|
5.1.0 | The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer). However, before PHP 5.1.0 this range was limited from 01-01-1970 to 19-01-2038 on some systems (e.g. Windows). |
5.1.0 | Now issues the E_STRICT and E_NOTICE time zone errors. |
5.1.1 | There are useful constants of standard date/time formats that can be used to specify the format parameter. |
Examples
Example #1 date() examples
<?php
// set the default timezone to use. Available since PHP 5.1
date_default_timezone_set('UTC');
// Prints something like: Monday
echo date("l");
// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* use the constants in the format parameter */
// prints something like: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// prints something like: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
You can prevent a recognized character in the format string from being expanded by escaping it with a preceding backslash. If the character with a backslash is already a special sequence, you may need to also escape the backslash.
Example #2 Escaping characters in date()
<?php
// prints something like: Wednesday the 15th
echo date('l \t\h\e jS');
?>
It is possible to use date() and mktime() together to find dates in the future or the past.
Example #3 date() and mktime() example
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Note:
This can be more reliable than simply adding or subtracting the number of seconds in a day or month to a timestamp because of daylight saving time.
Some examples of date() formatting. Note that you should escape any other characters, as any which currently have a special meaning will produce undesirable results, and other characters may be assigned meaning in future PHP versions. When escaping, be sure to use single quotes to prevent characters like \n from becoming newlines.
Example #4 date() Formatting
<?php
// Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the
// Mountain Standard Time (MST) Time Zone
$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
$today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$today = date("H:i:s"); // 17:16:18
?>
To format dates in other languages, you should use the setlocale() and strftime() functions instead of date().
Notes
Note:
To generate a timestamp from a string representation of the date, you may be able to use strtotime(). Additionally, some databases have functions to convert their date formats into timestamps (such as MySQL's » UNIX_TIMESTAMP function).
Timestamp of the start of the request is available in $_SERVER['REQUEST_TIME'] since PHP 5.1.
See Also
- gmdate() - Format a GMT/UTC date/time
- idate() - Format a local time/date as integer
- getdate() - Get date/time information
- getlastmod() - Gets time of last page modification
- mktime() - Get Unix timestamp for a date
- strftime() - Format a local time/date according to locale settings
- time() - Return current Unix timestamp
- strtotime() - Parse about any English textual datetime description into a Unix timestamp
- Predefined DateTime Constants

A smaller "time since incident" example that takes a datetime string as input :
<?php function timesince( $tsmp ) {
$diffu = array( 'seconds'=>2, 'minutes' => 120, 'hours' => 7200, 'days' => 172800, 'months' => 5259487, 'years' => 63113851 );
$diff = time() - strtotime($tsmp);
$dt = '0 seconds ago';
foreach($diffu as $u => $n){ if($diff>$n) {$dt = floor($diff/(.5*$n)).' '.$u.' ago';} }
return $dt;
}
?>
// example output: 10 seconds ago / 90 minutes ago / 16 months ago / 3 years ago
This is how you can get the week starting date and ending date by giving a week number and the year.
<?php
function week_start_date($wk_num, $yr, $first = 1, $format = 'Y-m-d')
{
$wk_ts = strtotime('+' . $wk_num . ' weeks', strtotime($yr . '0101'));
$mon_ts = strtotime('-' . date('w', $wk_ts) + $first . ' days', $wk_ts);
return date($format, $mon_ts);
}
//Get starting date of week 40 2011
$sStartDate = week_start_date(40, 2011);
//Get the ending date of the same week
$sEndDate = date('Y-m-d', strtotime('+6 days', strtotime($sStartDate)));
//Get current week and year
$week = date('w');
$year = date('Y');
?>
Here is a basic example that shows how to use times and dates with epoch and time zones.
<?PHP
echo "Current EPOCH is: ".time() .".\n";
//Changge the TZ to Los Angeles
date_default_timezone_set('America/Los_Angeles');
echo "As you can see after the TZ change to America/Los_Angeles the EPOCH is the same which is: ".time() .".\n";
//Changge the TZ to Prauge
date_default_timezone_set('Europe/Prague');
echo "As you can see after the TZ change to Europe/Prague the EPOCH is the same which is: ".time() .".\n";
//As per our last TZ change we are on Europe/Prague so if we want to get the epoch for 00:00:00 on 01-01-2012 we do:
echo "The value of 00:00:00 on 01-01-2012 for Europe/Praugue is: ".mktime('00', '00', '00', '1', '1', '2012').".\n";
//To get the epoch of 00:00:00 for today in Europe/Praugue
echo "The value of 00:00:00 for today in Europe/Praugue is: ".mktime('00', '00', '00', date("n"), date("j"), date("Y") ).".\n";
// We will now change the time zone to America/Loas_Angeles and do the same all over
//Changge the TZ to Los Angeles
date_default_timezone_set('America/Los_Angeles');
//As per our last TZ change we are on America/Los_Angeles so if we want to get the epoch for 00:00:00 on 01-01-2012 we do:
echo "The value of 00:00:00 on 01-01-2012 for America/Los_Angeles is: ".mktime('00', '00', '00', '1', '1', '2012').".\n";
//To get the epoch of 00:00:00 for today in America/Los_Angeles
echo "The value of 00:00:00 for today in America/Los_Angeles is: ".mktime('00', '00', '00', date("n"), date("j"), date("Y") ).".\n";
?>
simple calendar generator:
<?php
$dw=date(N);//this day of the week, numeric
$d=date(j);//this date
$m=date(m);//this month
$y=date(o);//this year
echo "<div id='CALENDAR DIV'><span style='font-size:20px;display:block;width:100%;text-align:center;'>";
echo date("F",mktime(0, 0, 0, $m, 1, $y));
echo "</span><table style='border:2px solid black;border-collapse:collapse;'>";
function mlength($month,$year){
return cal_days_in_month(CAL_GREGORIAN, $month, $year);//finds length of given month
}
$tml=mlength($m,$y);//this month's length
$cc=1;//day of the week counter
$day=1;
$tmd1=date("N", mktime(0, 0, 0, $m, 1, $y));//this month day 1, day of the week, numeric
//write out calendar---------------------------------------------------------------------
//days of the week
$dwcc=1;//counter for days of the week row
while($dwcc<=7){
$dwrow.="<td style='padding:15px;width:150px;height:auto;border:2px solid #333;' >".date("l", mktime(0, 0, 0, 8, $dwcc, 2011))."</td>\r\n";
$dwcc=$dwcc+1;
}
$tblrows="<tr>\r\n".$dwrow."\r\n</tr>\r\n\r\n";
//last days of last month
if($tmd1!=1){
while($cc<$tmd1){
$tblrows.=(($cc==1)?"<tr>\r\n":"")."<td style='padding:15px;width:150px;height:150px;border:2px solid black;' > </td>\r\n";
$cc=($cc==7)?1:$cc+1;
}
}
//this month
while($day<=$tml){
$tblrows.=(($cc==1)?"<tr>\r\n":"")."<td style='padding:15px;width:150px;height:150px;border:2px solid black;".(($day==$d)?"background-color:#999;":"")."' >".$day."</td>\r\n".(($cc==7)?"\r\n</tr>\r\n\r\n":"");
$cc=($cc==7)?1:$cc+1;
$day=$day+1;
}
//first days of next month
if($cc!=7){
while($cc<=7){
$tblrows.="<td style='padding:15px;width:150px;height:150px;border:2px solid black;' > </td>\r\n".(($cc==7)?"\r\n</tr>\r\n\r\n":"");
$cc=$cc+1;
}
}
echo $tblrows;
echo "</table></div>";
?>
Simple but useful function to get academic year.
<?php
function academic_year() {
$year=date(Y);
if (date(n)<8)
$year--;
return $year;
}
?>
It was oblivious and discouraging that it dont mentioned in docs. If you will use W to get week number be aware:
first days of year can be in a week of previous year, and week number always has leading zero
<?php
echo date("YW", strtotime("2011-01-07")); // gives 201101
echo date("YW", strtotime("2011-01-01")); // gives 201152
echo date("YW", strtotime("2011-12-31")); // gives 201152 too
?>
so you can`t rely on number of week given from this function inside your program if you want to use it for some logic
Convert a week number to a date:
<?php
$year = 2011;
$week_num_correction = strftime('%U', mktime(0,0,0,1,1,$year)) === '00' ? 1 : 0;
for($week = 1; $week < 54; $week++) {
$begin = strtotime("this sunday +".(($week-1)-$week_num_correction)." weeks", mktime(0,0,0,1,1,$year));
echo "week $week of $year starts on ", date('M j Y', $begin);
}
?>
The "week_number_correction" is to convert from ISO week #'s to US week numbers (weeks begin on Sunday, 1st day is first week).
Correct Polish date:
<?php
function pldate($format='j F Y',$date=False){
$date = (is_numeric($date)?$date:time());
$m=array(1=>'styczeń','luty','marzec','kwiecień','maj','czerwiec',
'lipiec','sierpień','wrzesień','październik','listopad','grudzień');
$ms=array(1=>'sty','lut','mar','kwi','maj','cze',
'lip','sie','wrz','paź','lis','gru');
$md=array(1=>'stycznia','lutego','marca','kwietnia','maja','czerwca',
'lipca','sierpnia','września','października','listopada','grudnia');
$d=array(0=>'Niedziela','Poniedziałek','Wtorek','Środa','Czwartek','Piątek','Sobota');
$ds=array(0=>'Nd','Pn','Wt','Śr','Cz','Pt','So');
$f = str_split($format);
for($i=0;$i<count($f);$i++){
if($f[$i]!="\\"){
switch($f[$i]){
case 'F':
$f[$i] = $md[date('n',$date)];
break;
case 'f':
$f[$i] = $m[date('n',$date)];
break;
case 'M':
$f[$i] = $ms[date('n',$date)];
break;
case 'l':
$f[$i] = $d[date('w',$date)];
break;
case 'D':
$f[$i] = $ds[date('w',$date)];
break;
default:
$f[$i] = date($f[$i],$date);
}
}else{
$f[$i]='';
$i++;
}
}
return implode('',$f);
}
?>
Now, this works for me, as our week starts on Fri, not Sun, and takes in account of the day light savings time issues that I was having when displaying the days in a calendar format.
This takes an array of dates from a mysql query, and displays them in a calendar style view
<?php
$cDates = count($Dates);
for($k = 1; $k <= $cDates-2; $k++)
{
$t = $k; $p = $t + 1;
$start = strtotime($Dates[$k]["DTG"]);
$stop = strtotime($Dates[$p]["DTG"]);
$dayTotal = ($stop - $start)/24/60/60;
$date = date("Y-m-d", $start); // starting date (YYYY-MM-DD)
$temp = date("Y-m-d", $stop); // ending date (YYYY-MM-DD)
$end = date("Y-m-d",strtotime("-1 day",$stop));
echo "\n<table style=\"align:center;width:100%;\">";
echo "\n <tr>";
echo "\n <th colspan=\"7\" align=\"center\"><strong>";
echo "\n </strong></th>";
echo "\n </tr>";
echo "\n <tr>";
echo "\n <th>Fri</th>";
echo "\n <th>Sat</th>";
echo "\n <th>Sun</th>";
echo "\n <th>Mon</th>";
echo "\n <th>Tue</th>";
echo "\n <th>Wed</th>";
echo "\n <th>Thu</th>";
echo "\n </tr>";
echo "\n <tr>";
$offset = date("w", strtotime($date));
if($offset <= 4) // to add spaces to beginning of row
{
for($i = 0; $i <= $offset+1; $i++){echo "\n <td><br /></td>";}
$count = $offset+2;
}
else
{
$count = 0;
}
while($date <= $end)
{
echo "\n <td>" . date("d M", strtotime($date)) ."::". date("w",strtotime($date)). "</td>";
$date = date('Y-m-d',strtotime("$date +1 day")); // get the next date
if($count >= 6) // to set next row
{
$count = 0;
echo "\n </tr><tr>";
}
else
{
$count++;
}
}
for($i = $count; $i <= 6; $i++){echo "\n <td><br /></td>";}// to add spaces at end of row
echo "\n </tr>";
echo "\n</table>";
}
?>
I needed to find out the Greater or Lesser dates for a few results sets. I'm not running 5.3 so I came up with this function to return either the greater or lesser date. The function is expecting dates in the MM/DD/YYYY format and the 3rd variable that is is looking for is either G or L so it will know whether to return the lesser or greater date.
<?php
function greater_lesser_date($date1,$date2,$gl = false){
///$gl is expecting either a G or an L to know whether you want
///greater or lesser returned
$d1m = substr($date1,0,2);
$d1d = substr($date1,3,2);
$d1y = substr($date1,6,4);
$d1 = mktime(0,0,0,$d1m,$d1d,$d1y);
$d2m = substr($date2,0,2);
$d2d = substr($date2,3,2);
$d2y = substr($date2,6,4);
$d2 = mktime(0,0,0,$d2m,$d2d,$d2y);
if( strtoupper($gl) == 'L') {
$date = ($d1>$d2?$d2:$d1);
} else {
$date = ($d1<$d2?$d2:$d1);
}
return date('m/d/Y', $date);
}
?>
<?php
/*
* Date: 29 April 2011
* Rakesh Verma
* Financial year quarter calculation
*/
// Calculation for financial year quarter(s)
$qtr1=array(04,05,06);
$qtr2=array(07,08,09);
$qtr3=array(10,11,12);
$qtr4=array(01,02,03);
$c_month=date('m');
// check for quarter number
if(in_array($c_month,$qtr1)) {
echo "Quarter I";
} else if(in_array($c_month,$qtr2)) {
echo "Quarter II";
} else if(in_array($c_month,$qtr3)) {
echo "Quarter III";
} else if(in_array($c_month,$qtr4)) {
echo "Quarter IV";
}
?>
a simple method to work out future dates from a given one.
<?php
/**
* Handles a date in the format YYYYMMDD.
*
* Doesn't take a genius to modify it to use some other format.
* We provide either of the following units:
* 'h' -> 'hour', 'i' -> 'minute', 's' -> 'second',
* 'm' -> 'month','d' -> 'day' , 'y' -> 'year'
*/
public static function getNextDate($date, $amount, $unit='d'){
$dividers = array(' ', ':', '_', '-', '/', '|');
$date = str_replace($dividers, '', $date);
$unit = strtolower($unit);
list($y, $m, $d) = array(substr($date, 0, 4), substr($date, 4, 2), substr($date, 6));
list($h, $i, $s) = array(1, 0, 0);
$x = substr($unit, 0, 1);
$$x += $amount;
return date('Ymd', mktime($h, $i, $s, $m, $d, $y));
}
?>
Spend lot of time to find correct function to calculate next invoice (billing) date, but didn't find. Make new one.
Condition:
Source date: 2011-01-31
Recurring payments each month at same day or early if source day more than end of month (31 is more than 28 Feb for example).
Here is results:
<?php
function get_next_invoice_date($source_date, $last_date)
{
if (is_null($last_date) || ($last_date == ''))
{
return $source_date;
}
$srctime = strtotime($source_date);
$lasttime = strtotime($last_date);
$source_day = date("d", $srctime);
$next_month = date("Y-m", strtotime( date("Ym", $lasttime) . '01 +1 month' ));
$next_month_time = strtotime($next_month);
$next_month_last_day = date("d", strtotime("-1 second", strtotime("+2 month", strtotime( date("Y", $lasttime) . date("m", $lasttime) . "01" ))));
if ($source_day > $next_month_last_day)
{
$new_day = $next_month_last_day;
}
else
{
$new_day = $source_day;
}
$next_invoice_date = $next_month . '-' . $new_day;
return $next_invoice_date;
} // get_next_invoice_date
// Test:
$first_invoice_date = '2011-01-31';
$last_invoice_date = '';
$list = array();
for ($i = 1; $i <= 24; $i++)
{
$last_invoice_date = get_next_invoice_date($first_invoice_date, $last_invoice_date);
$list[] = $last_invoice_date;
}
print_r($list);
?>
If you are simply trying to generate a date set in the future (for example, to setup a conditional to check if a value was created a month ago). You can use this.
<?php
print date('m-d-Y',strtotime('+1 month', '1301413787'));
// generates 04-29-2011
?>
This syntax was not noted in an easy to read place within the strtotime() or date() function pages, so just adding as note.
Here's a quick way to display the season (Winter, Spring, Summer, Autumn) from a date. Dec, Jan, Feb are Winter, etc.
<?php
$seasons = array("Winter","Spring","Summer","Autumn");
echo $seasons[(int)((date("n") %12)/3)];
?>
date("n") produces a numeric month 1..12
date("n") %12 (modulus 12) converts month 12 (Dec) to 0
Then we divide by 3 and convert to an integer to produce four groups, 0,1,2,3.
Then we display the nth array element.
Function for get date interval in Russian format
<?php
function getDateDiff($firstDate, $secondDate) {
$firstTimeStamp = strtotime($firstDate);
$secondTimeStamp = strtotime($secondDate);
$base_day = date('j', $secondTimeStamp);
$base_mon = date('n', $secondTimeStamp);
$base_yr = date('Y', $secondTimeStamp);
$current_day = date ('j', $firstTimeStamp);
$current_mon = date ("n", $firstTimeStamp);
$current_yr = date ("Y", $firstTimeStamp);
// and now .... calculate the difference! :-)
// overflow is always caused by max days of $base_mon
// so we need to know how many days $base_mon had
$base_mon_max = date ("t",mktime (0,0,0,$base_mon,$base_day,$base_yr));
// days left till the end of that month
$base_day_diff = $base_mon_max - $base_day;
// month left till end of that year
// substract one to handle overflow correctly
$base_mon_diff = 12 - $base_mon - 1;
// start on jan 1st of the next year
$start_day = 1;
$start_mon = 1;
$start_yr = $base_yr + 1;
// difference to that 1st of jan
$day_diff = ($current_day - $start_day) + 1; // add today
$mon_diff = ($current_mon - $start_mon) + 1; // add current month
$yr_diff = ($current_yr - $start_yr);
// and add the rest of $base_yr
$day_diff = $day_diff + $base_day_diff;
$mon_diff = $mon_diff + $base_mon_diff;
// handle overflow of days
if ($day_diff >= $base_mon_max) {
$day_diff = $day_diff - $base_mon_max;
$mon_diff = $mon_diff + 1;
}
// handle overflow of years
if ($mon_diff >= 12) {
$mon_diff = $mon_diff - 12;
$yr_diff = $yr_diff + 1;
}
$result = '';
if ($yr_diff > 0) {
if ($yr_diff >= 5 && $yr_diff <= 20) {
$yearLabel = 'лет';
}
elseif ($yr_diff % 10 == 1) {
$yearLabel = 'год';
}
elseif ($yr_diff % 10 <= 4) {
$yearLabel = 'года';
}
else {
$yearLabel = 'лет';
}
$result .= $yr_diff . ' ' . $yearLabel . ' ';
}
if ($mon_diff > 0) {
if ($mon_diff == 1) {
$monthLabel = 'месяц';
}
elseif ($mon_diff <= 4) {
$monthLabel = 'месяца';
}
else {
$monthLabel = 'месяцев';
}
$result .= $mon_diff . ' ' . $monthLabel . ' ';
}
if ($day_diff > 0) {
if ($day_diff >= 5 && $day_diff <= 20) {
$dayLabel = 'дней';
}
elseif ($day_diff % 10 == 1) {
$dayLabel = 'день';
}
elseif ($day_diff % 10 <= 4) {
$dayLabel = 'дня';
}
else {
$dayLabel = 'дней';
}
$result .= $day_diff . ' ' . $dayLabel . ' ';
}
return array($yr_diff, $mon_diff, $day_diff);
}
?>
<?php
// will echo all saturdays found between date range.
function getAllSaturdays($from_date, $to_date){
// getting number of days between two date range.
$number_of_days = count_days(strtotime($from_date),strtotime($to_date));
for($i = 1; $i<=$number_of_days; $i++){
$day = Date('l',mktime(0,0,0,date('m'),date('d')+$i,date('y')));
if($day == 'Saturday'){
echo Date('d-m-Y',mktime(0,0,0,date('m'),date('d')+$i,date('y'))),'<br/>';
}
}
}
// Will return the number of days between the two dates passed in
function count_days( $a, $b )
{
// First we need to break these dates into their constituent parts:
$gd_a = getdate( $a );
$gd_b = getdate( $b );
// Now recreate these timestamps, based upon noon on each day
// The specific time doesn't matter but it must be the same each day
$a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
$b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
// Subtract these two numbers and divide by the number of seconds in a
// day. Round the result since crossing over a daylight savings time
// barrier will cause this time to be off by an hour or two.
return round( abs( $a_new - $b_new ) / 86400 );
}
$from_date = Date('d-m-Y'); // todays date
$to_date = Date('d-m-Y',mktime(0,0,0,date('m'),date('d'),date('y')+1)); // date with one year difference i.e. same date of next year
getAllSaturdays($from_date,$to_date);
?>
A function to show $a days later.
<?php
function dateafter ( $a )
{
$hours = $a * 24;
$added = ($hours * 3600)+time();
$days = date("l", $added);
$month = date("F", $added);
$day = date("j", $added);
$year = date("Y", $added);
$result = "$day $month $year - $days";
return ($result);
}
echo dateafter("10");
//this will shows the data of ten days after.
// if today is 19 December 2010, Sunday, the page prints : 29 December 2010 - Wednesday.
?>
Most spreadsheet programs have a rather nice little built-in function called NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday, excluding holidays) between any two given dates. I couldn't find a simple way to do that in PHP, so I threw this together. It replicates the functionality of OpenOffice's NETWORKDAYS function - you give it a start date, an end date, and an array of any holidays you want skipped, and it'll tell you the number of business days (inclusive of the start and end days!) between them.
I've tested it pretty strenuously but date arithmetic is complicated and there's always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. "skip all Fridays and Saturdays but include Sundays") or to set up dates that should always be skipped (e.g. "skip July 4th in any year, skip the first Monday in September in any year"). But that's a project for another time.
<?php
function networkdays($s, $e, $holidays = array()) {
// If the start and end dates are given in the wrong order, flip them.
if ($s > $e)
return networkdays($e, $s, $holidays);
// Find the ISO-8601 day of the week for the two dates.
$sd = date("N", $s);
$ed = date("N", $e);
// Find the number of weeks between the dates.
$w = floor(($e - $s)/(86400*7)); # Divide the difference in the two times by seven days to get the number of weeks.
if ($ed >= $sd) { $w--; } # If the end date falls on the same day of the week or a later day of the week than the start date, subtract a week.
// Calculate net working days.
$nwd = max(6 - $sd, 0); # If the start day is Saturday or Sunday, add zero, otherewise add six minus the weekday number.
$nwd += min($ed, 5); # If the end day is Saturday or Sunday, add five, otherwise add the weekday number.
$nwd += $w * 5; # Add five days for each week in between.
// Iterate through the array of holidays. For each holiday between the start and end dates that isn't a Saturday or a Sunday, remove one day.
foreach ($holidays as $h) {
$h = strtotime($h);
if ($h > $s && $h < $e && date("N", $h) < 6)
$nwd--;
}
return $nwd;
}
$start = strtotime("1 January 2010");
$end = strtotime("13 December 2010");
// Add as many holidays as desired.
$holidays = array();
$holidays[] = "4 July 2010"; // Falls on a Sunday; doesn't affect count
$holidays[] = "6 September 2010"; // Falls on a Monday; reduces count by one
echo networkdays($start, $end, $holidays); // Returns 246
?>
Or, if you just want to know how many work days there are in any given year, here's a quick function for that one:
<?php
function workdaysinyear($y) {
$j1 = mktime(0,0,0,1,1,$y);
if (date("L", $j1)) {
if (date("N", $j1) == 6)
return 260;
elseif (date("N", $j1) == 5 or date("N", $j1) == 7)
return 261;
else
return 262;
}
else {
if (date("N", $j1) == 6 or date("N", $j1) == 7)
return 260;
else
return 261;
}
}
?>
Here is simple function to generate date selection, useful for admin panels ....
<?php
public static function dateRange($fmt = 'j-n-Y', $sep='+') {
$current_time = time();
$year = date('Y',$curr_time);
$month = date('n',$curr_time);
$day = date('j',$curr_time);
$today = date($fmt, $curr_time);
$r = array (
'all' => $sep.$sep.$sep,
'today' => $today.$sep.$today,
'yesterday' => date($fmt, strtotime('-1 day',$curr_time)).$sep.date($fmt, strtotime('-1 day',$curr_time)),
'last7days' => date($fmt, strtotime('-7 day',$curr_time)).$sep.$today,
'thismonth' => date($fmt, mktime(0,0,0,$month, 1, $year)).$sep.$today,
'thisyear' => date($fmt, mktime(0,0,0,1, 1, $year) ).$sep.$today,
);
return $r;
}
?>
this function returns the current date of server subtracted from a number of days passed as parameter
<?php
function subtractDaysFromToday($number_of_days)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$subtract = $today - (86400 * $number_of_days);
//choice a date format here
return date("Y-m-d", $subtract);
}
?>
Simple and handy function that offsets a MySQL formatted date and returns the new correctly formatted date
<?php
/**
*
* @param string $dt // MySQL formatted date (like 2010-01-01)
* @param int $year_offset // like 2 or -2, or 5 or -5 ...
* @param int $month_offset // like 2 or -2, or 5 or -5 ...
* @param in $day_offset // like 2 or -2, or 5 or -5 ...
* @return string // the new MySQL formatted date (like 2009-07-01)
*/
function MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='')
{
return ($dt=='0000-00-00') ? '' :
date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+
$day_offset,substr($dt,0,4)+$year_offset));
}
?>
Examples:
<?php
echo MySQLDateOffset('2010-06-01',2,5,15);
// will return 2012-11-16
echo MySQLDateOffset('2010-06-01',-6,5,38);
// will return 2004-12-09
?>
A really simple way to check if today's the last day of the month:
<?php
// If today is the last day of the month, do stuff
if(date('j') == date('t')) {
// Do Stuff
}
?>
Simple function to return the last business day of a given month (but this does not check holidays)
Função para retornar o último dia útil de um determinado mês (não verifica feriados)
example:
<?php echo last_business_day(2010,02); //2010-02-26 ?>
<?php
function last_business_day($year,$month)
{
$lbd = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$wday = date("N",strtotime("$year-$month-$lbd"));
if ($wday == 7) $lbd -= 2;
if ($wday == 6) $lbd--;
$lbd = date("Y-m-d",strtotime("$year-$month-$lbd"));
return $lbd;
}
?>
A function I use for 'date ago' used on message/comment boards
First, use this date('ymdHi') whenever entering the timestamp into your database.
Here's the function to retrieve how long ago it was entered. $querydate is timestamp retrieved from the database. Just call this function.
<?php
function returnDate($querydate){
$minusdate = date('ymdHi') - $querydate;
if($minusdate > 88697640 && $minusdate < 100000000){
$minusdate = $minusdate - 88697640;
}
switch ($minusdate) {
case ($minusdate < 99):
if($minusdate == 1){
$date_string = '1 minute ago';
}
elseif($minusdate > 59){
$date_string = ($minusdate - 40).' minutes ago';
}
elseif($minusdate > 1 && $minusdate < 59){
$date_string = $minusdate.' minutes ago';
}
break;
case ($minusdate > 99 && $minusdate < 2359):
$flr = floor($minusdate * .01);
if($flr == 1){
$date_string = '1 hour ago';
}
else{
$date_string = $flr.' hours ago';
}
break;
case ($minusdate > 2359 && $minusdate < 310000):
$flr = floor($minusdate * .0001);
if($flr == 1){
$date_string = '1 day ago';
}
else{
$date_string = $flr.' days ago';
}
break;
case ($minusdate > 310001 && $minusdate < 12320000):
$flr = floor($minusdate * .000001);
if($flr == 1){
$date_string = "1 month ago";
}
else{
$date_string = $flr.' months ago';
}
break;
case ($minusdate > 100000000):
$flr = floor($minusdate * .00000001);
if($flr == 1){
$date_string = '1 year ago.';
}
else{
$date_string = $flr.' years ago';
}
}
return $date_string;
}
?>
Here is a very simple function to get quarterly dates.
<?php
function quarter($month='',$day='')
{
if($month != ""){$tm = mktime(0,0,0,$month,$day-1,date('Y'));}else{$tm = date('Y-m-d H:i:s');}
$quarter = ceil(date("m", $tm)/3);
for($i=1; $i<=4; $i++)
{
$checkd = mktime(0,0,0,date('m')-$i,date('d'),date('Y'));
if(ceil(date("m", $checkd)/3) != "$quarter")
{
$meani = date("m", $checkd);
for($a=1; $a<=31; $a++)
{
$forman = mktime(0,0,0,$meani,$a,date('Y'));
if(ceil(date("m", $forman)/3) == "$quarter")
{
$first_day = date('d', $forman);
break;
}
}
break;
}
}
$current_quarter_dayone = date('Y-m-d H:i:s', mktime(0,0,0,$meani,$first_day,date('Y')));
return $current_quarter_dayone;
}
?>
To get the current quarterly start date.
$quarter_start= quarter();
**************************************
2010-09-01 00:00:00
To find the start of a particular quarter based on a date, pass the month and day.
$quarter_start = quarter('08','30');
$quarter_end = date("Y-m-d H:i:s", strtotime($barter)-86400);
Results
**********************************
2010-06-01 00:00:00
2010-08-31 00:00:00
Here is a simple function that gets all the dates between 2 given dates and returns an array (including the dates specified):
<?php
function dates_inbetween($date1, $date2){
$day = 60*60*24;
$date1 = strtotime($date1);
$date2 = strtotime($date2);
$days_diff = round(($date2 - $date1)/$day); // Unix time difference devided by 1 day to get total days in between
$dates_array = array();
$dates_array[] = date('Y-m-d',$date1);
for($x = 1; $x < $days_diff; $x++){
$dates_array[] = date('Y-m-d',($date1+($day*$x)));
}
$dates_array[] = date('Y-m-d',$date2);
return $dates_array;
}
// Usage
$dates_array = dates_inbetween('2001-12-28', '2002-01-01');
?>
Looking to output number of days left in the current year (and check if its a leap year - here it is)
<?php
$today = getdate(); // Get the current day in an array
$yday = ($today['yday']); // Extract just the number of days since January 1st current year
$leap = date('L'); // check if its a leap year
$tdl = $leap + 365; // 365 days in an average year plus 1 day if its a leap year
$dliy = $tdl - $yday; //Today number of days in the current year minus number of days since January 1st current year
// Build the output using the above variables
echo "As of today " . date('l F d, Y, ') . "We currently have " . $dliy . " days left in the year.";
?>
If you are sick of writing lots of code to format dates correctly, then I hope you find my code useful. It can def. use some work, I plan to improve it, but it passed a boring night and gave good results. enjoy! God bless!
<?php
function datefmt($date, $inFormat, $outFormat) {
/* A function to take a date in ($date) in specified inbound format (eg mm/dd/yy for 12/08/10) and
* return date in $outFormat (eg yyyymmdd for 20101208)
* datefmt (
* string $date - String containing the literal date that will be modified
* string $inFormat - String containing the format $date is in (eg. mm-dd-yyyy)
* string $outFormat - String containing the desired date output, format the same as date()
* )
*
*
* ToDo:
* - Add some error checking and the sort?
*/
$order = array('mon' => NULL, 'day' => NULL, 'year' => NULL);
for ($i=0; $i<strlen($inFormat);$i++) {
switch ($inFormat[$i]) {
case "m":
$order['mon'] .= substr($date, $i, 1);
break;
case "d":
$order['day'] .= substr($date, $i, 1);
break;
case "y":
$order['year'] .= substr($date, $i, 1);
break;
}
}
$unixtime = mktime(0, 0, 0, $order['mon'], $order['day'], $order['year']);
$outDate = date($outFormat, $unixtime);
if ($outDate == False) {
return False;
} else {
return $outDate;
}
}
?>
If you want to use HTML5's <date> tag, the following code will generate the machine-readable value for the 'datetime' attribute:
<?php
/**
* formats the date passed into format required by 'datetime' attribute of <date> tag
* if no intDate supplied, uses current date.
* @param intDate integer optional
* @return string
**/
function getDateTimeValue( $intDate = null ) {
$strFormat = 'Y-m-d\TH:i:s.uP';
$strDate = $intDate ? date( $strFormat, $intDate ) : date( $strFormat ) ;
return $strDate;
}
echo getDateTimeValue();
?>
If you want to get yesterday's date, then a single line of code is enough.
<?php
$yesterday = date("Ymd", strtotime("-1 day"));
?>
Function to return whether or not a given date falls within British Summer Time:
<?php
function is_bst($date) {
$Year = date("Y", $date);
$MarLast = $Year."-03-31";
$OctLast = $Year."-10-31";
//Find the last Sunday in March
if (date("w", strtotime($MarLast)) == 0) //Sunday
{
$LastMarSun = strtotime($MarLast);
} else {
$LastMarSun = strtotime($MarLast." last sunday");
}
//Find the last Sunday in October
if (date("w", strtotime($OctLast)) == 0) //Sunday
{
$LastOctSun = strtotime($OctLast);
} else {
$LastOctSun = strtotime($OctLast." last sunday");
}
$BSTStart = strtotime(date("Y-m-d", $LastMarSun)." 01:00:00");
$BSTEnd = strtotime(date("Y-m-d", $LastOctSun)." 01:00:00");
return (($date >= $BSTStart) && ($date <= $BSTEnd));
}
?>
Just small addition for indonesian date time..
<?php
function DateIndo($str) {
if ($str =="") {
// null
return false;
}
else {
setlocale (LC_TIME, 'id_ID');
$date = strftime( "%d-%m-%Y %H:%I:%S", strtotime($str));
return $date;
}
}
//this also works...
$date = date('Y-m-d H:i:s');
echo DateIndo($date);
?>
if you wish to output a local time, instead of using date_default_timezone_get() and date_default_timezone_set() to manipulate your current timezone, simply create a new DateTime object:
<?php
$timezone = new DateTimeZone( "Europe/London" );
$date = new DateTime();
$date->setTimezone( $timezone );
echo $date->format( 'H:i:s A / D, M jS, Y' );
?>
-> 22:59:34 PM / Sun, Jan 24th, 2010
Irrespective of current server location, this will output the local time in London, Europe.
No need to reset the server timezone back to the previous setting.
Not sure why this got ignored the first time, but this is an even simpler way to check leap year:
<?php
function isLeapYear($year)
{ return ((($year%4==0) && ($year%100)) || $year%400==0) ? (true):(false); }
?>
convert an "excel" formatted date. Example:
<?php
$excel_date = 40179;
$normal_date = date("m/d/Y", strtotime("01/01/1900 + $excel_date days - 2 days"));
echo($normal_date);
?>
result: "01/01/2010"
MS-DOS related filesystems, along with ZIP files, store date and time in four bytes (time: 2 bytes, date: 2 bytes), as described in Wikipedia: http://en.wikipedia.org/wiki/File_Allocation_Table#Directory_table
As it took me some time to not-find any functions to convert unix to ms-dos timestamps, I decided to put these simple functions here, to save somebody else's time:
<?php
// $ts - standard UNIX timestamp, as returned by mktime()
function packTimeDate($ts){
// MS-DOS can store dates ranging from 1980-01-01 up to 2107-12-31
$year=date('Y', $ts);
if(($year<1980) || ($year>2107)) return "\x00\x00";
else return packTime($ts).packDate($ts);
}
/** From Wikipedia:
* 15-11 Hours (0-23)
* 10-5 Minutes (0-59)
* 4-0 Seconds/2 (0-29)
**/
function packTime($ts){
$sec=round((('1'.date('s', $ts))-100)/2);
$min=('1'.date('i', $ts))-100;
$hour=date('G', $ts);
$dosTime=($hour<<11)+($min<<5)+$sec;
$m[0]=$dosTime%256;
$m[1]=(($dosTime-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
/** From Wikipedia:
* 15-9 Year (0 = 1980, 127 = 2107)
* 8-5 Month (1 = January, 12 = December)
* 4-0 Day (1 - 31)
**/
function packDate($ts){
$year=date('Y', $ts)-1980;
$day=date('j', $ts);
$month=date('n', $ts);
$dosDate=($year<<9)+($month<<5)+$day;
$m[0]=$dosDate%256;
$m[1]=(($dosDate-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
?>
As I didn't need to unpackTimeDate, I didn't bother to write reverse functions. Feel free to provide yours if You care.
Have fun with PHP!
To actually make use ot the "u" (microsecond) you need to use the DateTime object and not the date() function.
For example
<?php
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );
print $d->format("Y-m-d H:i:s.u");
?>
If u want to get weekday date -
30.08.2009 weekdays are 24-30
i want to get 5-th day of that week - 28.08.2009
<?PHP
function week_day($month, $year, $current_day, $week_day_number=1){
$loop_start = $current_day-(date('N', mktime(0, 0, 0, $month, $current_day, $year))-1);//lets start loop from first day of week
$loop_end = $current_day+(7-(date('N', mktime(0, 0, 0, $month, $current_day, $year))));//lets end loop to last day of week
for($i = $loop_start; $i<=$loop_end; $i++){
$day_of_the_week = date('N', mktime(0, 0, 0, $month, $i, $year));//current day number 1-7 of week
$loop_date = date('d', mktime(0, 0, 0, $month, $i, $year));//current day in calendar
if($day_of_the_week == $week_day_number){//if weekday number equals day number then lets return date
return $loop_date;
}
}
}
echo week_day(8, 2009, 30, 1);//returns (24).08.2009
echo '<br>';
echo week_day(8, 2009, 30, 5);//returns (28).08.2009
?>
Easy way to numeric representation of a quarter from passed as parametr date.
<?php
/**
* quarterByDate()
*
* Return numeric representation of a quarter from passed free-form date.
*
* @param mixed $date
* @return integer
*/
function quarterByDate($date)
{
return (int)floor(date('m', strtotime($date)) / 3.1) + 1;
}
?>
Example:
<?php
$quarter = quarterByDate(date('Y-m-d')); // current quarter. For 2009-08-29 will be "3"
$quarter = quarterByDate('2009-12'); // will be "4"
$quarter = quarterByDate('March'); // will be "1"
?>
I hope it will be useful.
Best regards,
S_P_E_C
This function behaves like date, but allows you to output the date in a given time zone locale.
<?php
function date_at_timezone($format, $locale, $timestamp=null){
if(is_null($timestamp)) $timestamp = time();
//Prepare to calculate the time zone offset
$current = time();
//Switch to new time zone locale
$tz = date_default_timezone_get();
date_default_timezone_set($locale);
//Calculate the offset
$offset = time() - $current;
//Get the date in the new locale
$output = date($format, $timestamp - $offset);
//Restore the previous time zone
date_default_timezone_set($tz);
return $output;
}
//Examples
$t = time();
print date("g:i A T", $t); //4:16 PM PDT
print date_at_timezone("g:i A T", "America/New_York", $t); //7:16 PM EDT
print date_at_timezone("g:i A T", "Pacific/Samoa", $t); //12:16 PM SST
print date("g:i A T", $t); //4:16 PM PDT
?>
Get names of days:
<?php
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
for($i=0; $i<7; $i++)
echo date('D', mktime(12, 0, 0, 1, $i+4, 1970)) . '<br />';
date_default_timezone_set($tz);
?>
Change 'D' to 'l' (lowercase 'L') for full names. Change $i+4 to $i+5 if you want Monday to be the first day of the week.
I couldn't find a function to do this properly. All functions I could find would use the current month as an argument.
Anyway, this function will find the occurence of a particular weekday in a particular month. For instance, the second wednesday in june 2009 would be called by:
<?php
echo findFirstDayofWeek(6,2009, "Wednesday", 2);
?>
Where 6 is "June", 2009 is the year, Wednesday is the weekday we want and 2 is the 2nd occurence.
<?php
function findFirstDayOfWeek($month, $year, $day, $offset){ // supply the month, year, day and offset
$FirstDay = mktime(0, 0, 0, $month, 1, $year); // Get the first day of the month in question
$DayName = date("l", $FirstDay); //set the name of the first day for the while loop
$CurrentStamp = $FirstDay; // set a disposable variable for use in the while loop
$Results = 0; //set the number of results (for use with the offset argument)
While($Results != $offset){ //while the number of results does not equal the offset we are looking for
$CurrentStamp = $CurrentStamp + 86400; // add a day
if(date("l", $CurrentStamp) == $day){ // if the name of the weekday we are currently looping at is the same name as the argument supplied, set the date variable to that weekday and increment the results variable by 1
$Date = date("Y-m-d", $CurrentStamp);
$Results++;
}
}
if(date("n", $CurrentStamp) != $month){ // this line checks whether or not the date that the while loop has found is in the same month we are asking form otherwise, there must be no "3rd friday in august"
return "No weekday at this offset";
} else {
return $Date; //send back the date
}
}
echo findFirstDayofWeek(9,2009, "Friday", 5); // returns a formatted date for the first instance of a certain day in the argumental month
?>
Haven't really tested it performance-wise vs. other methods, but I thought I'd post this anyways...
Here's a nifty way to exploit date()'s built-in ordinal suffix calculator to append the proper ordinal suffix to an arbitrary number:
<?php
function addOrdinal($num=0){
return $num.(((strlen($num)>1)&&(substr($num,-2,1)=='1'))?
'th' : date("S",mktime(0,0,0,0,substr($num,-1),0)));
} // end function addOrdinal
?>
In order to determine if a year is a leap year an earlier poster suggested simply checking to see if the year is a multiple of four:
<?php
function is_leapyear_broken($year = 2004) {
return ($year%4)==0;
}
?>
While this will work for the majority of years it will not work on years that are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this small anomaly in leap years:
<?php
function is_leapyear_working($year = 2004) {
if((($year%4==0) && ($year%100!=0)) || $year%400==0) {
return true;
}
return false;
}
?>
While is_leapyear_working will not return true for the few non-leap years divisible by four I couldn't tell you if this is more or less efficient than using php's date() as an even earlier poster suggested:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
An earlier user posted a script to detect whether or not a given year is a leap year:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
You're thinking too hard! Just check to see if the year is a multiple of four:
<?php
function is_leapyear($year = 2004) {
return ($year%4)==0;
}
?>
or better yet, just use that single line in your code.
Slightly modified earlier written function for formatting date in russian.
<?php
/*
these are the russian additional format characters
д: full textual representation of the day of the week
Д: full textual representation of the day of the week (first character is uppercase),
к: short textual representation of the day of the week,
К: short textual representation of the day of the week (first character is uppercase),
м: full textual representation of a month
М: full textual representation of a month (first character is uppercase),
л: short textual representation of a month
Л: short textual representation of a month (first character is uppercase),
*/
function date_ru($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['д'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота');
$q['Д'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
$q['к'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб');
$q['К'] = array(-1 => 'w', 'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
$q['м'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
$q['М'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май', 'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря');
$q['л'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');
$q['Л'] = array(-1 => 'n', '', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'д', $i) !== FALSE) || (strpos($formatum, 'Д', $i) !== FALSE) ||
(strpos($formatum, 'к', $i) !== FALSE) || (strpos($formatum, 'К', $i) !== FALSE) ||
(strpos($formatum, 'м', $i) !== FALSE) || (strpos($formatum, 'М', $i) !== FALSE) ||
(strpos($formatum, 'л', $i) !== FALSE) || (strpos($formatum, 'Л', $i) !== FALSE)) {
$ch['д']=strpos($formatum, 'д', $i);
$ch['Д']=strpos($formatum, 'Д', $i);
$ch['к']=strpos($formatum, 'к', $i);
$ch['К']=strpos($formatum, 'К', $i);
$ch['м']=strpos($formatum, 'м', $i);
$ch['М']=strpos($formatum, 'М', $i);
$ch['л']=strpos($formatum, 'л', $i);
$ch['Л']=strpos($formatum, 'Л', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
echo 'Сегодня '.date_ru('Д, d л Y');
?>
A quick note about DATE_RSS and daylight savings...
DATE_RSS will return the timezone that your server is in as part of the format, which is normally correct when formatting a date for an RSS feed (RFC-822).
However, if you're in the UK and it's the summer, your timezone is set as "BST". This is not actually a valid RFC-822 timezone, thereby rendering DATE_RSS a bit useless for six months of the year.
The valid extension would actually be GMT. You should therefore adjust the time back by 1 hour and substitute the BST for GMT.
<?php
//for Indonesian get return today
echo returnDate(date("N"), "day") . ", " . date("j") . " " . returnDate(date("n"), "month") . " " . date("Y");
function returnDate($num, $tipe){
$str;
switch($tipe){
case "month":
$month_name = array("", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
$str = $month_name[floor($num)];
break;
case "day":
$day_name = array("", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu");
$str = $day_name[floor($num)];
break;
}
return $str;
}
?>
// showing how to detect a leap year
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
<?php
$answer = is_leapyear(2000);
if($answer) {
echo "2000 is a leap year<BR>";
} else {
echo "2000 is not a leap year.<BR>";
}
/* Use default for the parameter */
$yy="2003";
$answer = is_leapyear(2003);
if($answer) {
echo "$yy is a leap year.<BR>";
} else {
echo "$yy is not a leap year.<BR>";
}
?>
Function to obtain last week timestamps.
<?php
function LastWeek(){
$week = date('W');
$year = date('Y');
$lastweek=$week-1;
if ($lastweek==0){
$week = 52;
$year--;
}
$lastweek=sprintf("%02d", $lastweek);
for ($i=1;$i<=7;$i++){
$arrdays[] = strtotime("$year". "W$lastweek"."$i");
}
return $arrdays;
}
$days = LastWeek();
echo "last week between " . date('Ymd000000',$days[0]) . " and " . date('Ymd235959', $days[6]) . "\n";
?>
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful for someone. Hope you don't mind changing your code tcasparr at gmail dot com.
<?php
/*******************************************************
* Simple function to take in a date format and return array of associated
* formats for each date element
*
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*
* This function is needed for PHP < 5.3.0
********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
$aDataRet = array();
$aPieces = split('[:/.\ \-]', $stFormat);
$aDatePart = split('[:/.\ \-]', $stData);
foreach($aPieces as $key=>$chPiece)
{
switch ($chPiece)
{
case 'd':
case 'j':
$aDataRet['day'] = $aDatePart[$key];
break;
case 'F':
case 'M':
case 'm':
case 'n':
$aDataRet['month'] = $aDatePart[$key];
break;
case 'o':
case 'Y':
case 'y':
$aDataRet['year'] = $aDatePart[$key];
break;
case 'g':
case 'G':
case 'h':
case 'H':
$aDataRet['hour'] = $aDatePart[$key];
break;
case 'i':
$aDataRet['minute'] = $aDatePart[$key];
break;
case 's':
$aDataRet['second'] = $aDatePart[$key];
break;
}
}
return $aDataRet;
}
?>
Also, if you need to change the format of dates:
<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
// When PHP 5.3.0 becomes available to me
//$date = date_parse_from_format($stFormatFrom,$stDate);
//For now I use the function above
$date = dateParseFromFormat($stFormatFrom,$stDate);
return date($stFormatTo,mktime($date['hour'],
$date['minute'],
$date['second'],
$date['month'],
$date['day'],
$date['year']));
}
?>
Heads up: The date('W') week number of the year is computed based on Monday, and may not be exactly what you expect. What is "Week 01" of year 2008? This is different from the date('z') day number of the year which is computed from January 1 == day zero.
<?php // RAY_date_W.php
echo "<br/>" . date('W', strtotime("December 28, 2008")); // 52
echo "<br/>" . date('W', strtotime("December 29, 2008")); // 01
echo "<br/>" . date('W', strtotime("January 2, 2009")); // 01
if (!date('z', strtotime("January 1"))) echo "<br/>FALSE"; // FALSE
?>
<?php
/**
* Simple function to take in a date format and return array of associated formats for each date element
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*/
function extract_date_format($strFormat)
{
$format_array = array();
$pieces = split('[:/.\ \-]', $strFormat);
foreach($pieces as $piece)
{
switch ($piece)
{
case 'd':
case 'j':
$format_array['day'] = $piece;
break;
case 'F':
case 'M':
case 'm':
case 'n':
$format_array['month'] = $piece;
break;
case 'o':
case 'Y':
case 'y':
$format_array['year'] = $piece;
break;
case 'g':
case 'G':
case 'h':
case 'H':
$format_array['hour'] = $piece;
break;
case 'i':
$format_array['minute'] = $piece;
break;
case 's':
$format_array['second'] = $piece;
break;
}
}
return $format_array;
}
?>
It seems to me that you can reliably get the week range of a certain numeric week like so:
<?php
// 2009 is the year
// W01 is week number 1
// 1 is the day number (Monday), 7 would be Sunday
strtotime("2009W011");
// Example 1 (These return the days for Week 1 or 2009
Mon_timestamp = strtotime("2009W011");
Tue_timestamp = strtotime("2009W012");
Wed_timestamp = strtotime("2009W013");
Thu_timestamp = strtotime("2009W014");
Fri_timestamp = strtotime("2009W015");
Sat_timestamp = strtotime("2009W016");
Sun_timestamp = strtotime("2009W017");
// Example 2 (more dynamic)
// set the 7 dates of the week
for($i=1; $i<=7; $i++) {
$dates[$i] = strtotime($year.'W'.$week.$i);
}
?>
Just remember you must pad the week number if it's under 10. 1 won't work, it should be 01.
In a refreshing change, this code snippet is *not* about calculating date differences or anything like that.
<background-story>
I've always preferred date() over strftime() because of what each offers. For example, date has an st/nd/rd for the day number (S) while strftime does not. It also has an unpadded day number (j) that strftime doesn't (%e pads it with a space).
On the other hand, each character in the format string for date() is translated unless you prepend a backslash...
Recently I've wanted to create links with date information in it. Like with "January 21st 2009" each part would be a link (January => /2009/01, 21st => /2009/01/21, 2009 => /2009). date() makes this difficult because the HTML markup gets the treatment as well as the Y/m/d characters. Escaping all of those is ugly, not to mention annoying.
</background-story>
Here's my combination of date's placeholders and strftime's % markers. It's the best solution I could think of (at 5am mind you) but I'm open to suggestions.
Lots of comments because the code is rather tricky.
<?php
/**
* Combines placeholders from date() with the % marker from strftime()
*
* Like strftime, use %% for a literal %.
*
* @see date, strftime
* @param string $format The format of the outputted date string
* @param int $timestamp An integer Unix timestamp that defaults to the current local time
* @return A formatted date string
*/
function strfdate($format, $timestamp = null) {
// look for tokens
if (preg_match_all('/(?<!%)(%%)*%(.)/', $format, $matches)) {
// passing false or null as the timestamp doesn't work so we
// have to generate the default ourselves
if ($timestamp === null) $timestamp = time();
// run each token through date - all at once
// combines them into a "a!b!c!d" list, runs it through date,
// and splits it apart again
$parts = explode("!", date(implode("!", $matches[2]), $timestamp));
// (! should never show up in date() output so this works)
// a second function is used sequentially:
// the Xth time this function is called it will replace the Xth token
// with the corresponding element in $parts (which is passed through as $a)
//
// @param array $a Meant to be $parts as defined above
// @return $a[X] where X is how many times this function has been called
$replace = create_function('$a', 'static $i = 0; return $a[$i++];');
// find each token and get the replacement data from the $replace function
// note how the text being replaced isn't used anywhere: we already know
// what it is as it was used to create the $parts array
$result = preg_replace('/(%*)%./e', '"$1" . $replace($parts)', $format);
// finally "unescape" any %s
$result = str_replace("%%", "%", $result);
return $result;
}
return $format;
}
?>
Just in case anyone else is looking for an easy-to-find equivalent for W3C Datetime or date("c") in a previous version of php, here's one I did. Hope it helps someone.
<?php
function w3cDate($time=NULL)
{
if (empty($time))
$time = time();
$offset = date("O",$time);
return date("Y-m-d\TH:i:s",$time).substr($offset,0,3).":".substr($offset,-2);
}
?>
Examples:
echo w3cDate(); //2008-11-18T12:15:18-07:00
echo w3cDate(mktime(2,3,4,5,6,2007)); //2007-05-06T02:03:04-06:00
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/
//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;
$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");
echo date('m-d-Y',$ts_start); //start date
echo '<br>';
echo date('m-d-Y',$ts_end); //end date
/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
date(DATE_RFC822) and date(DATE_RFC2822) both work. note that RFC 822 is obsoleted by RFC 2822. The main difference is the year being 08 in RFC 822 and is 2008 in RFC 2822.
To use date(DATE_RFC2822), a short form is date('r').
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
a date function supporting the milliseconds format character
<?php
function udate($format, $utimestamp = null)
{
if (is_null($utimestamp))
$utimestamp = microtime(true);
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}
echo udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
here is the simpliest way to get the start and end date of the week;
<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));
$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>
the format is for the string in strtotime is;
2008W200
this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....
so 2008W200 stands for the sunday of the 20th week of 2008.
This will only work in php 5 or better
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.
So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00
I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.
<?php
/**
* Finds the difference in days between two calendar dates.
*
* @param Date $startDate
* @param Date $endDate
* @return Int
*/
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
?>
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
$format='F j, Y';
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
?>
Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
<?php
}
?></div>
<div style='float:left;'>
<h3>NEW DateTime Class (v 5.2+)</h3><?php
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
$date = new DateTime($datep);
?>
Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
<?php
}
?></div>
Quick function for returning the names of the next 7 days of the week starting with today.
Returns an array that can be formatted to your liking.
<?php
/**
* Returns array of next 7 days starting with today
*
*/
function next_7_days() {
// create array of day names. You can change these to whatever you want
$days = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
$today = date('N');
for ($i=1;$i<$today;$i++) {
// take the first element off the array
$shift = array_shift($days);
// ... and add it to the end of the array
array_push($days,$shift);
}
// returns the sorted array
return $days;
}
?>
It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast. He/she uses $w as a key for the $weeks array. "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended. For May, 2008, I get 5 weeks as expected...
Array
(
[1] => Array
(
[4] => 1
[5] => 2
[6] => 3
)
[2] => Array
(
[0] => 4
[1] => 5
------------OMITTED-----------------
[4] => 22
[5] => 23
[6] => 24
)
[5] => Array
(
[0] => 25
[1] => 26
[2] => 27
[3] => 28
[4] => 29
[5] => 30
[6] => 31
)
)
I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).
I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).
<?php
$m = date('m');
$Y = date('Y');
// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
$weeks = array();
for($i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
$weeks[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
$months[$month]['WEEKS'] = $weeks;
}
?>
Enjoy!
Weeks and days for any month/year combo:
<?php
$m = 2; // February
$Y = 2008;
// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));
for($i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
$week[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
?>
print_r($week):
-----------------------
Array
(
[1] => Array
(
[5] => 1
[6] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 9
)
[3] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
[6] => 16
)
[4] => Array
(
[0] => 17
[1] => 18
[2] => 19
[3] => 20
[4] => 21
[5] => 22
[6] => 23
)
[5] => Array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
[4] => 28
[5] => 29
)
)
[EDIT BY danbrown AT php DOT net: In a note dated 03-JUL-08, (dmagick AT gmail DOT com) offered the following amendment to this note.]
[I've updated this] code as it doesn't take into account when a month finishes on a Saturday (eg May 2008).
<?php
$start_date = mktime(0, 0, 0,$start_month, 1, $start_year);
$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);
$j = $month_first_day;
$num_weeks = 1;
for($i = 1; $i <= $days_in_month; $i++) {
$j++;
if($j == 7) {
$j = 0;
$num_weeks++;
}
}
// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
$num_weeks--;
}
?>
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.
<?php
function chooseDate($timestamp = ""){
if($timestamp == ""){
$timestamp = time();
}
$months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
unset($months[0]);
print_r($months);
$out = '<select name="month">';
foreach($months as $key => $month){
if($month == date('M', $timestamp)){
$out .= '<option value="'.$key.'" selected="selected">'.$month.'</option>';
}else{
$out .= '<option value="'.$key.'">'.$month.'</option>';
}
}
$out .= '</select><select name="days">';
for($i = 1; $i <= 32; $i++){
if($i == date('j', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select><select name='year'>";
for($i = date('Y'); $i >= 1970; $i--){
if($i == date('Y', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select>";
return $out;
}
?>
Usage is simple:
<?php
echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
?>
to get the week of the month simply use:
ceil( date("j") / 7 );
I made a small code to get the last working day of the month:
<?php
$times = strtotime(date("Y")."-".date("m")."-".date("t"));
for ($lastworkingday=0;$lastworkingday==0;$times-=86400)
if (date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",$times);
print $lastworkingday;
?>
Found this helpful when converting unix dates for use with the ical file format.
<?php
// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10
function unixToiCal($uStamp = 0, $tzone = 0.0) {
$uStampUTC = $uStamp + ($tzone * 3600);
$stamp = date("Ymd\THis\Z", $uStampUTC);
return $stamp;
}
?>
<?php
/**
* Checks wether a date is between an interval
*
* Usage:
*
* // check if today is older than 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/31'));
* // check if today is younger than 2008/12/31
* var_dump(currentDayIsInInterval(null,'2008/12/31'));
* // check if today is between 2008/12/01 and 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/01','2008/12/31'));
*
* Will trigger errors if date is in wrong format, notices if $begin > $end
*
* @param string $begin Date string as YYYY/mm/dd
* @param string $end Date string as YYYY/mm/dd
* @return bool
*/
function currentDayIsInInterval($begin = '',$end = '')
{
$preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
$preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' : Invalide date
format. Please use YYYY/mm/dd.';
$interval_error = 'First parameter in '.__FUNCTION__.' should be smaller than
second.';
if(empty($begin))
{
$begin = 0;
}
else
{
if(preg_match($preg_exp,$begin))
{
$begin = (int)str_replace('/','',$begin);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if(empty($end))
{
$end = 99999999;
}
else
{
if(preg_match($preg_exp,$end))
{
$end = (int)str_replace('/','',$end);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if($end < $begin)
{
trigger_error($interval_error,E_USER_WARNING);
}
$time = time();
$now = (int)(date('Y',$time).date('m',$time).date('j',$time));
if($now > $end or $now < $begin)
{
return false;
}
return true;
}
?>
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.
<?php
function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
//extract the format
$i = 0;
$aFieldOrder = array();
$nFields = 0;
$strExtraction = "";
while(isset($strFormat[$i]))
{
$strField = $strFormat[$i];
switch ( strtolower($strField) )
{
case "D";
case "d";
$aFieldOrder[$nFields] = "d";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "M";
case "m";
$aFieldOrder[$nFields] = "m";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "y";
case "Y";
$aFieldOrder[$nFields] = "y";
$nFields++;
$strExtraction .= "%4d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "h";
case "H";
$aFieldOrder[$nFields] = "h";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "i";
$aFieldOrder[$nFields] = "i";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "S";
case "s";
$aFieldOrder[$nFields] = "s";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
}
$i++;
}
$aValues = array();
$aValues = sscanf($strDateTime,$strExtraction);
return array_combine($aFieldOrder,$aValues);
}
?>
For output formatting of a SAMP based seminar announcement system, i had to fetch the date of every friday of a given month in a given year. Here's what i did:
<?php
$givenYear = $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"
if ($givenMonth != '12') {
$nextGivenMonth = "1";
$nextGivenYear = $givenYear + 1;}
else {
$nextGivenMonth = $givenMonth + 1;
$nextGivenYear = $givenYear;}
# Get the first weekday of the month
$firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
$firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
# Count days to first Friday
switch ($firstWeekDayOfMonth) {
case 'Monday': $numOfDaysToFirstFriday = "4"; break;
case 'Tuesday': $numOfDaysToFirstFriday = "3"; break;
case 'Wednesday': $numOfDaysToFirstFriday = "2"; break;
case 'Thursday': $numOfDaysToFirstFriday = "1"; break;
case 'Friday': $numOfDaysToFirstFriday = "0"; break;
case 'Saturday': $numOfDaysToFirstFriday = "6"; break;
case 'Sunday': $numOfDaysToFirstFriday = "5"; break;}
# Get first Friday's date
$numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
$firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
# Get the last weekday of the month
$lastDayOfMonth = date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
$lastWeekDayOfMonth = date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
# Count days to last Friday
switch ($lastWeekDayOfMonth) {
case 'Monday': $numOfDaysToLastFriday = "3"; break;
case 'Tuesday': $numOfDaysToLastFriday = "4"; break;
case 'Wednesday': $numOfDaysToLastFriday = "5"; break;
case 'Thursday': $numOfDaysToLastFriday = "6"; break;
case 'Friday': $numOfDaysToLastFriday = "0"; break;
case 'Saturday': $numOfDaysToLastFriday = "1"; break;
case 'Sunday': $numOfDaysToLastFriday = "2"; break;}
# Get last Friday's date
$numOfDaysToLastFriday = $lastDayOfMonth - $numOfDaysToLastFriday;
$lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
$lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
$divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
$divisor = $divisor / 7;
global $divisor;
# Get the dates of all Fridays in the given Month (can be either 4 or 5)
if ($divisor=='3') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
else if ($divisor=='4') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
?>
Comments, suggestions and bugfixes are welcome ;-))
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.
So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").
For most cases strftime("%W") should be a safe replacement.
[edit: Much easier is to use "o" (lower case O) instead of "Y"]
I wanted to get the number of weeks for particular year.
Example with date():
<?php
$weeks_in_year = date("W", strtotime("12/31/2007"));
?>
It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.
So the workaround was using different function.
Example with strftime():
<?php
$weeks_in_year = strftime("%W",strtotime("12/31/2007"));
?>
Now it works as a charm.
PHP v.4.4.7
[EDIT BY danbrown AT php DOT net: In a note dated 25-JAN-09, "Juan Paredes" offered the following information as an amendment.]
Complementing the information [in this note], if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:
date('W', mktime(0,0,0,12,28,$year) );
(the last week on a give year always contains 28-Dec)
This function is like date, but it "speaks" Hungarian (or an other language)
<?php
/*
these are the hungarian additional format characters
ö: full textual representation of the day of the week
Ö: full textual representation of the day of the week (first character is uppercase),
ő: short textual representation of the day of the week,
Ő: short textual representation of the day of the week (first character is uppercase),
ü: full textual representation of a month
Ü: full textual representation of a month (first character is uppercase),
ű: short textual representation of a month
Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat');
$q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat');
$q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
$q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
$q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december');
$q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December');
$q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö', $i) !== FALSE) ||
(strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő', $i) !== FALSE) ||
(strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü', $i) !== FALSE) ||
(strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
$ch['ö']=strpos($formatum, 'ö', $i);
$ch['Ö']=strpos($formatum, 'Ö', $i);
$ch['ő']=strpos($formatum, 'ő', $i);
$ch['Ő']=strpos($formatum, 'Ő', $i);
$ch['ü']=strpos($formatum, 'ü', $i);
$ch['Ü']=strpos($formatum, 'Ü', $i);
$ch['ű']=strpos($formatum, 'ű', $i);
$ch['Ű']=strpos($formatum, 'Ű', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
echo date_hu('Y. ü j. (ö) G:i');
?>
For those of us who don't have 5.x installed (that puts a colon in the time zone)...
<?php
$timezone = date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
For people who used "z" format...
The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :
<?php
define ("\n" , NL );
print '<pre>';
print '"z" format interpretation:' . NL . NL;
print 'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"
print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"
print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"
print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"
print '</pre>';
?>
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>
Hope it helps, BigJonMX
<?php
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* @param integer $timestamp
* @return string date in RFC3339
* @author Boris Korobkov
* @see http://tools.ietf.org/html/rfc3339
*/
function date3339($timestamp=0) {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
?>
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).
If you want a whole number of days use the following instead:
<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:
<?php
function week_limits($weekNumber, $year, $pattern)
{
$pattern = ($pattern) ? $pattern : "m/d";
$stday = 7 * $weekNumber - 7;
$stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
$stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
$start_time = date($pattern, $stUtime);
$end_time = date($pattern, $stUtime+6*24*60*60);
return array($start_time, $end_time);
}//week_limits()
?>
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.
<?php
function sql_date_shift($date, $shift)
{
return date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}
// example usage
$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage
echo sql_date_shift($date, $shift);
// will output: 2007-01-01 03:00:00
?>
Hope it is of use,
Ashley
if you are sending your data to a database, you can just send time() and then use strftime() to turn the time() string into readable time format.
check both time() and strftime() functions both offer more or less same functionality as date(). date() can also be used with time() strings to display time in the past.
more or less with something like:
date("j F, Y - g:ia", $data['date_quoted'])
where time() = $data['date_quoted'] and time() is the exact time date when the string is executed. if this is done towards a database, the time() stored is the actual server time upon script execution, no matter the time set in the individual computer, this will record server time, unless a gmt is set in newer versions of php (5 and up).
<?php
/**
* Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv( $date_format1, $date_format2, $date_str )
{
$base_struc = split('[/.-]', $date_format1);
$date_str_parts = split('[/.-]', $date_str );
print_r( $base_struc ); echo "<br>";
print_r( $date_str_parts ); echo "<br>";
$date_elements = array();
$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}
$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);
return date( $date_format2, $dummy_ts );
}
$df_src = 'd/m/Y';
$df_des = 'Y-m-d';
$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>
output:
2005-12-25
If you want to use the date function to fix the RFC-822 format from an allready made RSS 2.0 feed you can do it like this..
Maybe getting an external feed from another asp or php file that you cannot change, but want to have the correct dateformat for anyway.
<?php
header('Content-type: application/rss+xml; charset=iso-8859-1');
$xmlfile = simplexml_load_file($_GET[feedURL]);
for ( $i = 0; $i < count($xmlfile->channel->item); $i++ )
$xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)($xmlfile->channel->item[$i]->pubDate)));
echo $xmlfile->asXML();
?>
Then simply link to your rss feed like this
filename.php?feedURL=http://www.example.com/rss.asp
filename.php?feedURL=http://www.example.com/rss.xml
filename.php?feedURL=http://www.example.com/rss.php
or what you want. Hope anyone can take advantage of this, I wrote it to help a friend which had date stored in database only by yyyy-mm-dd hh:mm:ss and retrieved via asp from another script.
To use the date("N") function in PHP < 5.1.0 use:
<?php
function dayofweek() {
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
return array_search(date("D"), $days) + 1;
}
?>
If you want to count quarters between dates you can use the following:
<?php
function countQuarters($begindate, $enddate)
{
if (!isset($begindate) || empty($begindate) || !isset($enddate) || empty($enddate))
return -1;
$countyears = date("Y", strtotime($enddate)) - date("Y", strtotime($begindate));
$quarters = 0;
if (date("Y", strtotime($enddate)) == date("Y", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
return -1;
}
}
}
else
{
$quarters = (int) $countyears * 4;
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
$afterbegin = 12 - (int) date("m", strtotime($begindate));
$untilend = date("m", strtotime($enddate));
$quarters = ($quarters - 4) + ceil(($afterbegin + $untilend) / 4);
}
}
}
return $quarters;
}
?>
Easy way of switching between mysql and "normal" dates (english, not american)...
<?php
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
return implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
?>
Slightly modified the code provided by "martin at smttuk dot com" so that you can give the function a date and/or time that you choose;
<?php
function zonedate($layout, $countryzone, $daylightsaving, $time)
{
if($daylightsaving) {
$daylight_saving = date('I');
if($daylight_saving){ $zone=3600*($countryzone+1); }
}
else {
if( $countryzone>>0){ $zone=3600*$countryzone; }
else { $zone=0; }
}
if(!$time) { $time = time(); }
$date = gmdate($layout, $time + $zone);
return $date;
}
?>
For example if I wanted the time and date of my birthday in New Zealand time;
<?php
echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986));
?>
It's pretty simple, but in case anybody else is having problems getting the exact time they need because of DST (ex: on a Windows box in an area without DST), you can fix it all in a single line. Example...
<?php
echo "The time is " . date((date("I") ? intval(date("g")) - 1 : date("g")) . ":i m/d/y") . ".";
?>
<?php
/* Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time, FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time, Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time
* How to use
$layout =
Same function as date : http://php.net/manual/en/function.date.php
$countryzone =
Country Zone from Above Eg: 0 ,for Greenwich Mean Time
$daylightsaving =
Set true if the Country has daylight saving it will auto change.
Set false if the Country dose not have daylight saving or wish to it Disabled.
(About Daylight Saving go here : http://www.timeanddate.com/time/aboutdst.html)
Call Function:
zonedate($layout, $countryzone, $daylightsaving);
E.g.
If GMT = Friday 25th of August 2006 10:23:17 AM
When Function called:
// West Asia Standard Time (Country Uses daylight saving)
echo zonedate("l dS \of F Y h:i:s A", 5, true);
//Output : Friday 25th of August 2006 03:23:17 PM
*/
function zonedate($layout, $countryzone, $daylightsaving)
{
if ($daylightsaving){
$daylight_saving = date('I');
if ($daylight_saving){$zone=3600*($countryzone+1);}
}
else {
if ($countryzone>>0){$zone=3600*$countryzone;}
else {$zone=0;}
}
$date=gmdate($layout, time() + $zone);
return $date;
}
?>
Number of weeks per month
I was trying to do a monthly calendar and required the number of weeks in a month, running from Monday to Sunday. Since PHP doesn't have this in its date() parameters I had to calculate it in a roundabout manner. By subtracting the week numbers away from each other we SHOULD get the number of weeks, since it is calculated on Mondays.
<?php
$year = date("Y", $date);
$month = date("m", $date);
if( (isset($_GET['year'])) && (intval($_GET['year']) > 1582) )
{
$year = intval($_GET['year']);
}
if( (isset($_GET['month'])) && (intval($_GET['month']) >= 1) && (intval($_GET['month']) <= 12) )
{
$month = intval($_GET['month']);
}
$date = mktime(1, 1, 1, $month, date("d"), $year);
$first_day_of_month = strtotime("-" . (date("d", $date)-1) . " days", $date);
$last_day_of_month = strtotime("+" . (date("t", $first_day_of_month)-1) . " days", $first_day_of_month);
$first_week_no = date("W", $first_day_of_month);
$last_week_no = date("W", $last_day_of_month);
if($last_week_no < $first_week_no) $last_week_no=date("W", strtotime("-1 week",$last_week_no)) + 1;
$weeks_of_month = $last_week_no - $first_week_no + 1;
?>
The check for weeknumber of the end of the month being smaller than the beginning of the month, is because of December. Where Monday 31st is actually in the first week of the following year.
The +1 adjustment is for the number of weeks, inclusive. ie if January had five week, then 5-1=4, so we need to add an extra one to make it 5.
I simplified this after I figured it out based upon Mel Boyce's simple solution. Thanks Mel!
I wanted to calculate dates based upon any given date and not just todays date which is what the hundreds of examples on the Internet use. I created a simple function and then just call the function with 2 parameters.. the date (string) to test and the number of days that I want to add (positive #) or subtract (negative #) My intended use is to retrieve dates from the database and perform the date calculations. This makes it simple. I hope this helps someone as frustrated as I was. Enjoy.
******************************************
<?php
// date calculation function
// adds or subtracts a date based upon the input.
// $this_date is a string format of a valid date ie.. "2006/08/11"
// $num_days is the number of days that you would like to add (positive number) or subtract (negative number)
function fnc_date_calc($this_date,$num_days){
$my_time = strtotime ($this_date); //converts date string to UNIX timestamp
$timestamp = $my_time + ($num_days * 86400); //calculates # of days passed ($num_days) * # seconds in a day (86400)
$return_date = date("Y/m/d",$timestamp); //puts the UNIX timestamp back into string format
return $return_date;//exit function and return string
}//end of function
$date_to_test = "2006/08/11";
$days_to_add = 7;
$past_date = fnc_date_calc($date_to_test,(($days_to_add)*-1));
$future_date = fnc_date_calc($date_to_test,$days_to_add);
echo "Test Date is: ".$date_to_test;
echo "<br>";
echo "Number of days to Calculate is: ".$days_to_add;
echo "<br>";
echo "Past date is: ".$past_date;
echo "<br>";
echo "Future date is: ".$future_date;
?>
For PHP 4 users wanting a format similar to ISO 8601 (http://www.w3.org/TR/NOTE-datetime):
echo date('Y-m-d H:i:s.0T');
returns something like 2006-07-27 16:54:14.0EDT
Here's a function that takes the year as input and returns an array or dates that are mondays. (It can be used for generating weekly reports just like I did)
<?php
function getMondays($year) {
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$mondays = array();
$i = 1;
while ($week != 1) {
$day++;
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
}
array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
while ($newyear == $year) {
$test = strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
$i++;
if ($year == date("Y",$test)) {
array_push($mondays,date("r", $test));
}
$newyear = date("Y",$test);
}
return $mondays;
}
?>
If You are looking for some simple date calculations:
<?php
function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday)
{
return abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
}
function day_before($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-1,$fyear));
}
function next_day($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday+1,$fyear));
}
function weekday($fyear, $fmonth, $fday) //0 is monday
{
return (((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, 7, 17, 2006))/(60*60*24))+700000) % 7;
}
function prior_monday($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-weekday($fyear, $fmonth, $fday),$fyear));
}
?>
If you do not PHP5 yet but want a week day to be in ISO format: 1 (for Monday) through 7 (for Sunday), you can use this:
<?php
//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );
$corrected_week_day = 7 - ( (7-$x) % (7+$x) );
?>
I've been flicking through the comments looking for some succinct date code and have noticed an alarming number of questions and over-burdened examples related to date mathematics. One of the most useful skills you can utilize when performing date math is taking full advantage of the UNIX timestamp. The UNIX timestamp was built for this kind of work.
An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days = floor((time() - strtotime("01-Jan-2006"))/86400);
print("$days days have passed.\n");
?>
Another usage could find itself in a class submitted by Kyle M Hall which aids in the creation of timestamps from the recent past for use with MySQL. Rather than the looping and fine tuning of a date, Kyle can use the raw UNIX timestamps (this is untested code):
<?php
$ago = 14; // days
$timestamp = time() - ($ago * 86400);
?>
Hopefully these two examples of "UNIX-style" timestamp usage will help those finding date mathematics more elusive than it should be.
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at calendar at this very site:
http://www.php.net/calendar
Users in GMT may find some information on British Summer Time useful. Personally I was confused that date() for a timestamp of 0 was returning 1am, until I found about the all-year BST from 1968-71.
http://wwp.greenwichmeantime.com/info/bst2.htm
The examples for getting a date in the past or future is simply not the best way to do it. Especially if you are doing it dynamically.
I find the best way to get a date in the past or future is like this:
<?php
//get timestamp for past/future date I want
$pf_time = strtotime("-3 days");
//format the date using the timestamp generated
$pf_date = date("Y-m-d", $pf_time);
?>
There is a mistaken impression that the maximum difference between UTC and localtime is +/- 12 hours. Right now it is summer here in New Zealand, and we're 13 hours ahead of UTC, and further east in the Chatham Islands it's UTC+13:45.
Consequently, the range for the "Z" conversion is at least -43200 ... +49500
Using 'B' for the Swatch Internet Time (i.Beats) can still lead to misunderstandings, because the date given in the resulting string is the local date, not the date of the BMT (Biel Mean Time / UTC+0100) after which the i.Beats are counted. So while @000 is equal all around the globe, October 25th 2005 @000 in Chicago is really October 24th, 06:00 PM local time.
Otherwise, if you use date('d M Y @B') in Chicago on that day at 6pm, it will return "24 Oct 2005 @000" although it should be "25 Oct 2005 @000".
So it may happen that you miss an appointment by 24 hours (or 1000 Beats ;-)
Here's a way to return the Internet Time with correct date:
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
$ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime); // seconds since midnight (BMT)
$ibeats = $ssm/86.4; // 86400 seconds = 1000 beats, so 1 beat = 86.4 seconds
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . $ibeats;
?>
Note: If you would try date('D, d M Y @B', $bmttime), the resulting beats would be wrong because the timezone used for calculation of the beats within the date() function is still your local one but the timestamp is UTC+0100. Another working way would be:
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . date('B', $curtime);
?>
But this way there are no floating-point beats possible, which may be handy sometimes.
I created a routine that fills an array with the dates in the current week. For example $WeekDays[0] is sunday's date, $WeekDays[1] is monday's date and so on no matter what day of the week it is today.
<?php
$lowEnd=date("w");
$lowEnd=-$lowEnd;
$highEnd=$lowEnd + 6;
$weekday=0;
for ($i=$lowEnd; $i<=$highEnd; $i++) {
$WeekDate[$weekday]=date("m/d",mktime(0, 0, 0, date("m") , date("d")+$i, date("Y")));
$weekday++;
}
?>
For users who want a different language than english, you can user strftime() function in combination with setlocale() instead of date():
e.g. for german language:
With date you would write:
<?php
echo date('l, d. F Y'); //Output: Wednesday, 07. September 2005
?>
With strftime() you can output it in german like this:
<?php
// Set the gloabal LC_TIME constant to german
setlocale(LC_TIME, 'de_DE');
// Little bit other Syntax but better effect
echo strftime('%A, %d. %B %Y'); //Output: Mittwoch, 07. September 2005
?>
Greetings, Andy!
Don't forget that months start on the 1st day, and not a zero date. Might seem obvious but:
<?php $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); ?>
Will return November 2005, not December.
<?php $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); ?>
The 1st is needed to get the right month.
Calculus of weeks in a year.
Since there is date("W") many still seem to have a problem regarding how many weeks there are in an year. Some rather complex solutions have been shown here.
It's defined, that a week which begins in december and ends in january the following year belongs to the year where most of its days lie. Therefore a week with at least 4 days in december is the last week of that year and a week with at least 4 days in january is the first week in the new year.
This concludes, that the last week of a year always contains the 28th day of december. So if you take date("W") on that day of a given year you always get the correct number of weeks for that year.
The other end of that definition is that the 4th day of january always lies in the first week of a year.
I hope this solves a lot of confusion.
(For those asking what all this fuzz about counting weeks is about: normally theres 52 weeks in a year but sometimes its 53 weeks in a year)
I wrote it down as a function, but as this is rather trivial one might consider using the date(...) only.
<?php
function weeks($year) {
return date("W",mktime(0,0,0,12,28,$year));
}
?>
To convert an unix timestamp to suite the syntax of a GeneralizedTime attribute for OpenLDAP, you can use
date ('YmdHiZO'). Note that this conversion uses local time, the recommended way is to store dates in UTC.
If your date is in UTC, just use
date ('YmdHiZ').'Z' to convert it ("Z" stands for "Zulu", which is UTC).
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>