|
date
Format a local time/date
(PHP 4, PHP 5)
Example 445. date() examples<?php Example 446. Escaping characters in date()<?php Example 447. date() and mktime() example<?php Example 448. date() Formatting<?php Related Examples ( Source code ) » date Examples ( Source code ) » Form Data Validation With Error Count Examples ( Source code ) » Get Text Field value Examples ( Source code ) » Cookie based login form and get last login time Examples ( Source code ) » Login form with Error Messages and Preserving User Input Examples ( Source code ) » Generating Tables from XML Examples ( Source code ) » Transforming XML into Basic HTML Examples ( Source code ) » Get affected rows for an update Examples ( Source code ) » Update Employee table Examples ( Source code ) » Update data record and get the affected rows Examples ( Source code ) » Table-Creation Script Examples ( Source code ) » Initiate session and create a few session variables Examples ( Source code ) » File changed time Examples ( Source code ) » File modified time Examples ( Source code ) » File accessed time Examples ( Source code ) » File last changed time Code Examples / Notes » datewitcho
When using 'z' it should be used as how many days have passed since the beginning of the year; not as the day of the year. "January 1" is the day 1 of the year not the day 0. Better to add 1 when using 'z' if you really want to know the day of the year. wes.wysoft.com
Well I looked all over the place for this and couldn't find it so I made my own. Hopefully it saves someone else some time. It will give you the occurances of a day in a month. For example if you want to get the date of the 2 Tuesday in a month. <?php function weekDayOf($year,$month,$dayoftheweek=null,$occurance=null) { /* * returns the # occurance of the day of the week. Such as the 3rd sunday * if occurance is null it will return the whole array. for the week days in that month * it can be accessed by $date[$dayoftheweek][$occurance]=date; */ $mdays=date("t",mktime(0,0,0,$month,1,$year)); //days in the current month $first_day = date('w',mktime(0,0,0,$month,1,$year)); // day of the week the month started with $day_oc = array(); // occurances of each day of the week for($i=0;$i<$mdays;++$i){ $dayofweek = ($i+$first_day)%7; if(!is_array($day_oc[$dayofweek])) { $day_oc[$dayofweek] = array(); } $day_oc[$dayofweek][]=$i+1; } return $dayoftheweek ? $day_oc[$dayofweek][$occurance] : $day_oc; } ?> soreenpk
we can find the different in days between two date e.g now and some past date from db throught the following simple line of code; $digest_date = "2007-03-15"; $date_diff = date("d",strtotime(date('y-m-d'))) - date("d",strtotime($digest_date)); mbirth
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. nick h
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 david dot scourfield
Two comments below give us superfluous code. Firstly, arkin AT REMOVESPAM DOT arkinex DOT com has posted a function that "takes 2007-09-19 21:05:23 and turns it into a unix timestamp." The built-in PHP function strtotime() can do this, so defining another function is unnecessary: <?php $timestamp = strtotime("2007-09-19 21:05:23"); ?> And secondly, vikram dot dhanjal at gmail dot com gives us "Code for generating time stamp for current time." Again, strtotime() can do this, but PHP also has a built-in function for that very purpose: time(). <?php $timestampRightNow = strtotime("Now"); // or simpler still: $timestampRightNow = time(); ?> time() is quicker than strtotime("Now") as PHP does not need to parse the string provided. emailfire
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; } ?> rodflash.com
To make date comparison, don't use date() function. Use strtotime //Check earlier date $date=strtotime("$month/$day/$year"); $today=strtotime("now"); if ($date> $today) { //Early date } else { //Old date } You can also put another input formats: http://www.gnu.org/software/tar/manual/html_node/tar_109.html jonbarnett
To everyone who is posting functions to parse date strings and turn them into time stamps - please look at the strtotime() function. It probably already does whatever you're writing a function to do. To the person right below me: while your function might be an extremely small bit more efficient, strtotime() will work just fine. php
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). bartlomiej b dot berdzii
To calculate current quarter of the year we can use this simple function: function quarter() { return ceil(date("m")/3); } robert
This will show the day (Monday, Tuesday, etc) for any given date. <?php $mon = 12; $day = 31; $year = 1980; $stamp = mktime(0,0,0,$mon,$day,$year); echo date('l',$stamp); ?> me
This will calculate the 'SPOT' date for FX trades (two working days hence) <?php // get the day $d=date("D"); // if today is Thu or Friday add 4 days to today if ($d=="Thu" || $d=="Fri") { $spot = time() + (4 * 24 * 60 * 60); echo " "; echo date("d/m/Y", $spot); echo ""; } // else just add two days to today else { $spot = time() + (2 * 24 * 60 * 60); echo " "; echo date("d/m/Y", $spot); echo ""; } ?> arkin
This snippet takes 2007-09-19 21:05:23 and turns it into a unix timestamp, created and found very useful on a project i just did. <?php function make_timestamp($date) { list($year, $month, $day, $hour, $minute, $second) = split('[-: ]', $date); return mktime($hour, $minute, $second, $month, $day, $year); } ?> pburlandoa_remove_tgmaildotcom
This is an implementation for days360 formula used in financial calc software, this asumes year with 360 days and months with 30 days. I am looking for a reliable function to add days to a date using 30[E]/360 format. <?php /* Calc days between two dates using the financial calendar 30/360 (usa) or 30E/360(european)<-default $fecha1 and $fecha2 in format: aaaa-mm-dd return days or -1 in case of error. based on cost_analysis.py module Ver. 0.1 public domain, no license required by Harm Kirchhoff */ function days_360($fecha1,$fecha2,$europeo=true) { //try switch dates: min to max if( $fecha1 > $fecha2 ) { $temf = $fecha1; $fecha1 = $fecha2; $fecha2 = $temf; } // get day month year... list($yy1, $mm1, $dd1) = explode('-', $fecha1); list($yy2, $mm2, $dd2) = explode('-', $fecha2); if( $dd1==31) { $dd1 = 30; } //checks according standars: 30E/360 or 30/360. if(!$europeo) { if( ($dd1==30) and ($dd2==31) ) { $dd2=30; } else { if( $dd2==31 ) { $dd2=30; } } } //check for invalid date if( ($dd1<1) or ($dd2<1) or ($dd1>30) or ($dd2>31) or ($mm1<1) or ($mm2<1) or ($mm1>12) or ($mm2>12) or ($yy1>$yy2) ) { return(-1); } if( ($yy1==$yy2) and ($mm1>$mm2) ) { return(-1); } if( ($yy1==$yy2) and ($mm1==$mm2) and ($dd1>$dd2) ) { return(-1); } //Calc $yy = $yy2-$yy1; $mm = $mm2-$mm1; $dd = $dd2-$dd1; return( ($yy*360)+($mm*30)+$dd ); } // usage: echo days_360("2007-01-13","2007-05-20"); ?> cj
This is a very simple few lines of code to display dates that arrive in various formats: $dateArray=explode('-','2007-02-05'); // $dateArray[0]= 2007 // $dateArray[1] = 02 // $dateArray[2] = 05 echo date('M j, Y', mktime(0, 0, 0, $dateArray[1], $dateArray[2], $dateArray[0])); // result: Feb 2, 2007 alter your explode characters and dateArray positions to suit. Chris thomasedison
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'); ?> martin
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 dragon
The function posted by mybenchmarkid down is great, but I would suggest a slight change. The "$days" line should be without the "+1" at the end: $days = (strtotime($endDate) - strtotime($startDate)) / 86400; and the "for" line should be with "<=" instead of "<": for($i=0; $i<=$days; $i++) This way you can use a specific endDate or just use today: $days = (time() - strtotime($startDate)) / 86400; It will work both ways. Bobby spikedacruz
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. <? 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"); } ?> daniel
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. <? 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"); } ?> vernon
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); ?> rev
the CORRECT MySQl datetime format is <?php $date = "Last Saturday"; date("Y-m-d H:i:s",strtotime($date)); $sql = "INSERT INTO pictureusageindex (`subject`,`date`) VALUES ('$subject','$date')"; echo "$sql "; ?> a person who posted above is wrong. leaving out the "-" matt_wbdi
The below code doesn't work. The $next_month variable, for instance, right now, will be March, even though today is January 30th. The reason is because one month from Jan. 30th is March. But that's not the next month. I would suggest using an array of Month names instead, with their respective number as the key.
dmitriy dot yakovlev
soreenpk - the code snippet you posted will not find the day difference between two days that are not in the same month. This will: <?php $digest_date = "2007-06-01"; $date_diff = abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400; ?> 86400 is the number of seconds in a day, so finding the date difference in seconds and converting to days will give true day difference between dates. Cheers. bandit
So I wanted a little function to output an easy to read but inaccurate date. I came up with the following (probably very inefficient) little function; <?php function ezDate($d) { $ts = time() - strtotime(str_replace("-","/",$d)); if($ts>31536000) $val = round($ts/31536000,0).' year'; else if($ts>2419200) $val = round($ts/2419200,0).' month'; else if($ts>604800) $val = round($ts/604800,0).' week'; else if($ts>86400) $val = round($ts/86400,0).' day'; else if($ts>3600) $val = round($ts/3600,0).' hour'; else if($ts>60) $val = round($ts/60,0).' minute'; else $val = $ts.' second'; if($val>1) $val .= 's'; return $val; } ?> Then I use it as follows; <?php echo ucwords(ezDate('2006-09-07 18:42:00')).' Ago'; ?> Which would output; 2 Months Ago I add an acronym tag around the output also, so my users can mouse-over for the exact date. Hope it helps someone! james
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)); ?> marius
Re: steve at somejunkwelike dot com I think this is a better function to find the business days between two dates. This function requires PHP 5.1.0. <?php //The function returns the no. of business days between two dates and it skeeps the holidays function getWorkingDays($startDate,$endDate,$holidays){ //The total number of days between the two dates. We compute the no. of seconds and divide it to 60*60*24 //We add one to inlude both dates in the interval. $days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1; $no_full_weeks = floor($days / 7); $no_remaining_days = fmod($days, 7); //It will return 1 if it's Monday,.. ,7 for Sunday $the_first_day_of_week = date("N",strtotime($startDate)); $the_last_day_of_week = date("N",strtotime($endDate)); //The two can't be equal because the $no_remaining_days (the interval between $the_first_day_of_week and $the_last_day_of_week) is at most 6 //In the first case the whole interval is within a week, in the second case the interval falls in two weeks. if ($the_first_day_of_week < $the_last_day_of_week){ if ($the_first_day_of_week <= 6 && 6 <= $the_last_day_of_week) $no_remaining_days--; if ($the_first_day_of_week <= 7 && 7 <= $the_last_day_of_week) $no_remaining_days--; } else{ if ($the_first_day_of_week <= 6) $no_remaining_days--; //In the case when the interval falls in two weeks, there will be a Sunday for sure $no_remaining_days--; } //The no. of business days is: (number of weeks between the two dates) * (5 working days) + the remainder $workingDays = $no_full_weeks * 5 + $no_remaining_days; //We subtract the holidays foreach($holidays as $holiday){ $time_stamp=strtotime($holiday); //If the holiday doesn't fall in weekend if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7) $workingDays--; } return $workingDays; } //Example: $holidays=array("2006-12-25","2006-12-26","2007-01-01"); echo getWorkingDays("2006-12-22","2007-01-06",$holidays) // => will return 8 ?> steve
re: Paul_liversidge... This is a way to get the next 10 business days, by comparing the day of the week to not be saturday or sunday. change the top two variables to get various different results... if you want to get the next 10 business days, starting in two days from today, change the first variable to 2, and the second to 14. This should yield the next 10 working days. <?php $how_many_business_days_ahead = 0; $how_many_business_days_to_count = 7; for ($i=0;$i<$how_many_business_days_to_count;$i++) { $jump=$i+$how_many_business_days_ahead; $evalday = mktime(strftime ("%d/%m/%Y", strtotime("+$jump days"))); $theday = strftime("%A", strtotime("+$jump days")); if($theday != "Saturday" and $theday != "Sunday") { $days = $how_many_business_days_ahead+$i; $the_days[$j] = strftime("%A, %B %d, %Y", strtotime("+$jump days")); $j++; } } $k = $how_many_business_days_ahead; foreach($the_days as $eachday) { echo "$k business days from now = $eachday<br />"; $k++; } ?> results: 0 business days from now = Tuesday, August 16, 2005 1 business days from now = Wednesday, August 17, 2005 2 business days from now = Thursday, August 18, 2005 3 business days from now = Friday, August 19, 2005 4 business days from now = Monday, August 22, 2005 mwwaygoo
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. dmitrid
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: 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() s.koch
mysql date format: <? $mysq_format_date = date("Y-m-d H:i:s"); ?> lcapt
my quick and dirty code to find the season of the date <?php function season() { $limits=array('/12/21'=>'Winter','/09/21'=>'Autumn', '/06/21'=>'Summer','/03/21'=>'Spring','/12/31'=>'Winter'); foreach ($limits AS $key => $value) { $limit=date("Y").$key; if (strtotime("now")>strtotime($limit)) { return $value; } } } echo season(); ?> PS: the 21th is a good approach but not the real day. lionel
my quick and dirty code to find the season of the current date <?php function season() { $limits=array('/12/21'=>'Winter', '/09/21'=>'Autumn', '/06/21'=>'Summer', '/03/21'=>'Spring', '/01/01'=>'Winter'); foreach ($limits AS $key => $value) { $limit=date("Y").$key; if (strtotime($adate)>=strtotime($limit)) { return $value; } } } echo season(); ?> PS: the 21th is a good approach but not the real day. john
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 ); ?> kangaroo232002
Just a quick note on Josh L's implementation, switch doesn't pick up differences of '0' (or false) so if you are sending an email out at the same time as posting something, it will give you just a date (in the default) rather than a cute string. So, just add a catch at the top like <?php if($diff === 0) { return "just now"; } else { <do everything else> } ?> otherwise thanks josh for a v useful function :) corey
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") . "."; ?> stuff
ISO 8601:2000 defines: [...] day of the year is represented by three decimal digits. The first day of any year is represented by [001] and subsequent days are numbered in ascending sequence [...] So don't forget increasing the return value of date("z") by one to be ISO conform, if you use this, for instance, on presentation level. matt_b
In response to the getLastWeekDay() function: ***^ EDITOR NOTE: Referred to note was removed 2006-09-07. Changing dates for any reason by adding/subtracting secret is a really bad idea. Daylight savings will totally screw up the calculations. Your best bets are the awesome strtotime features. To get last monday for example: $var = strtotime('last monday'); Strtotime can do all sorts of funky stuff like this. bakadesu
In reply to josh's suggestion, you can achieve the same thing by doing: <?php $date = date($syntax, strtotime($datetime)); ?> luis dot sv
In relation to soreenpk at yahoo dot com's message: That code doesn't work for two dates with a difference larger than a year, for example: $digest_date = "2006-04-14"; $date2="2007-04-15"; $date_diff = date("d",strtotime($date2)) - date("d",strtotime($digest_date));//$date_diff = 1 sea
in PHP and MySQL,the day of year is different: <?php echo date('z',strtotime('2006-01-01')); // print: 0 ?> mysql > SELECT DAYOFYEAR('2006-01-01'); // print: 1 wcc
In example 3, <?php date("m") ?> is passed to mktime() for the month argument. I believe <?php date("n") ?> should be used instead so that the leading 0's don't make PHP think the arguments are octal values. The same goes for <?php date("j") ?> instead off <?php date("d") ?>. <?php echo mktime(0, 0, 0, 09, 09, 2006); echo "\n"; echo mktime(0, 0, 0, 9, 9, 2006); ?> 1133326800 1157774400 john
If you're wanting to increment a date, add twenty-FIVE hours (yes, one day per year may last 25 hours...), and the additional hour won't impact other days, as it's converted to a Y-m-d string: $date=date('Y-m-d', strtotime($date)+(25*3600)); Try this for october 28, 2007... admin
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. Article at http://www.xorath.com/articles/?article=2 eves1985
If you want to define your own time without having trouble with the server time you could do this; <? $timeZoneOffset = +1; //timezone where the user is (use an additional script to determine this variable) $H = (date('H')+date('O'))+$timeZoneOffset; //hour $i = date('i'); //minutes $s = date('s'); //seconds $m = date('m'); //month $d = date('d') //day $Y = date('Y') //year $date = date('Y-m-d, H:i:s',mktime($H,$i,$s,$m,$d,$Y)); // will output somthing like 2007-09-13, 03:52:05 ?> michiel
If you want to count quarters between dates you can use the following: 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; } erwinmoller
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 haqpunk
If you have a unix time stamp value in your DB that you would like to see the elapsed time for this might save you some time: <?php if(mysql_result($result, 0, "Time_Stamp")){ $Now=strtotime(date('Y-m-d H:i:s')); $Action=strtotime(mysql_result($result, 0, "Time_Stamp")); ## Calculate time past since status change $dateDiff = $Now - $Action; $Days = floor($dateDiff/(60*60*24)); $Hours = floor(($dateDiff-($Days*60*60*24))/(60*60)); $Minutes = floor(($dateDiff-($Days*60*60*24)-($Hours*60*60))/60); $Seconds = floor($dateDiff-($Days*60*60*24)-($Hours*60*60)-($Minutes*60)); ## Display in unix like time stamp format echo str_pad($Days, 2, "0", STR_PAD_LEFT)." ".str_pad($Hours, 2, "0", STR_PAD_LEFT).":".str_pad($Minutes, 2, "0", STR_PAD_LEFT).":".str_pad($Seconds, 2, "0", STR_PAD_LEFT);} ?> mandi tek shqiperia.com
If you have a date in the english format"Thu Sep 07 23:59:35 CEST 2006" (some times generated from logs or other systems) and you need to translate it in mm/dd/yyyy you can use the following function! //$data="Thu Sep 07 23:59:35 CEST 2006"; function formadatedb($data) { $dt=explode(" ", $data); $year=array ("Jan"=>1, "Feb"=>2, "Mar"=>3, "Apr"=>4, "May"=>5, "Jun"=>6, "Jul"=>7, "Aug"=>8, "Sep"=>9,"Oct"=>10,"Nov"=>11,"Dec"=>12); return $year[$dt[1]]."/".$dt[2]."/".$dt[5]; } elena s.
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: <? //GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY $x = date( "w" ); $corrected_week_day = 7 - ( (7-$x) % (7+$x) ); ?> 28-nov-2006 07:26
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). dulare
If You are looking for some simple date calculations: <? 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)); } ?> jasonlfunk
If there is an easier way to find the week of the month, let me know. Here is how I figured out how to do it; date("W") - date("W",strtotime(date("F") . " 1st " . date("Y"))) + 1; mel dot boyce
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. new_age
I was searching to change order within the date. Instead of YYYY-mm-dd, to get different order. One query is simple: "SELECT place, DATE_FORMAT(event_date,'%d.%m.%Y.') AS event_date FROM table"; The date comes out as d.m.YYYY. as this is usual in my country. kirti dot contact
I was looking for a function to find the week range for a particular week. But now I have developed by own. This function takes three arguments all optional 1. Week - This value ranges from 1- 52 or 53. It needs a correct value. If no value is provided, it then uses the current week. 2. Year - If none is provided, then the current year. 3. Format - defaults to d/M/Y It returns an array containing the 'start date' and the 'end date' Imp. Week starts from Sunday. function getWeekDateRange($week="",$year="",$format="d/M/Y"){ if($year=="" || !is_numeric($year)) $year=date("Y"); if($week=="" || !is_numeric($week)) $week=date("W"); $week--; $first_day=date("w",mktime(0,0,0,1,1,$year)); $first_day_tstamp=mktime(0,0,0,1,1,$year); $first_sunday=($first_day==0?0:(6-$first_day+1)); $first_sunday_tstamp=$first_sunday*24*3600+$first_day_tstamp; if($first_sunday!=0){ $week_cal=$week-1; }else{ $week_cal=$week; } $tw_start_tstamp=$first_sunday_tstamp+$week_cal*7*24*3600; $tw_end_tstamp=$first_sunday_tstamp+($week_cal+1)*7*24*3600-1; $yy=date("Y",$tw_end_tstamp); if($yy>$year) $tw_end_tstamp=mktime(23,59,59,12,31,$year); if($week==0 && $first_sunday!=0){ $tw_start_tstamp=$first_day_tstamp; $tw_end_tstamp=$first_sunday_tstamp-1; } $start_date=date($format,$tw_start_tstamp); $end_date=date($format,$tw_end_tstamp); return array($start_date,$end_date); } code
I wanted to shift an sql date forward by a set time period. This is how I achived it... well handy. <? 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 phil sylvia
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 " "; echo "Number of days to Calculate is: ".$days_to_add; echo " "; echo "Past date is: ".$past_date; echo " "; echo "Future date is: ".$future_date; ?> ove
I seems to me that we're rapidly apporaching another Y2K event. The date-function only handles dates up to 2038, and this is only some 30 years away. Even today is it impossible to use date() to represent my children's 50 years birthday. Just think about it, when you're designing your code. [ed.: This limitation is gone in PHP 5.1 and higher, although PHP itself limits integers still to 32bit] jcwebb
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 snobord787
I modified (erenezgu at gmail.com)'s code so you don't have to redirect but is stored in cookies. <?php if(empty($_COOKIE['offset'])) { // Javascript is our friend! $header=' <script type="text/javascript"> document.cookie="offset=" + ( (new Date()).getTimezoneOffset()*60)*(-1)-'.abs(date('Z')).'; </script> '; } // Example Usage echo date('d/m/Y H:i:s', time()+$_COOKIE['offset'] ); ?> davedx
I made a minor modification to wes.wysoft.com's "nth day of the month" function. I was attempting to convert Windows registry TIME_ZONE_INFORMATION structs to PHP dates to do timezone + DST conversions, and the registry entries don't seem to be quite right - for GMT, the correct end of DST is "the last Sunday in October", but the windows registry stores it as "the 5th Sunday in October"... but in 2007 there are only 4 Sundays! To protect from further craziness, I do this: function weekDayOf($year,$month,$dayoftheweek,$occurance) { /* * returns the # occurance of the day of the week. Such as the 3rd sunday * if occurance is null it will return the whole array. for the week days in that month * it can be accessed by $date[$dayoftheweek][$occurance]=date; */ $mdays=date("t",mktime(0,0,0,$month,1,$year)); //days in the current month $first_day = date('w',mktime(0,0,0,$month,1,$year)); // day of the week the month started with $day_oc = array(); // occurances of each day of the week for($i=0;$i<$mdays;++$i){ $dayofweek = ($i+$first_day)%7; if(!is_array($day_oc[$dayofweek])) { $day_oc[$dayofweek] = array(); } $day_oc[$dayofweek][]=$i+1; } $n = $occurance; while($n > 0 && !isset($day_oc[$dayoftheweek][$n])) $n--; return $day_oc[$dayoftheweek][$n]; } sheldon
I have to work out the day before an event to send an email notification. But if the day before was on a weekend I had to make sure the email was send on the Friday before the weekend. I didn't see anything like this around so here is what i wrote. Hope it helps some one else. <?php $dates = explode("/", "09/22/2007"); $month = $dates['0']; $day = $dates['1']; $year = $dates['2']; $yesterday = mktime(0,0,0,$month,$day-1,$year); $notification = date('l',$yesterday); if(in_array($notification, array("Saturday", "Sunday"))){ $notification = "Friday"; } echo(" {$notification}"); ?> david dot scourfield
I created this function a while ago and needed it again recently, so had to trawl through some old files to find it. Thought I'd post it here in case anyone else finds it useful. <?php /* * Function to calculate which days are British bank holidays (England & Wales) for a given year. * * Created by David Scourfield, 07 August 2006, and released into the public domain. * Anybody may use and/or modify this code. * * USAGE: * * array calculateBankHolidays(int $yr) * * ARGUMENTS * * $yr = 4 digit numeric representation of the year (eg 1997). * * RETURN VALUE * * Returns an array of strings where each string is a date of a bank holiday in the format "yyyy-mm-dd". * * See example below * */ function calculateBankHolidays($yr) { $bankHols = Array(); // New year's: switch ( date("w", strtotime("$yr-01-01 12:00:00")) ) { case 6: $bankHols[] = "$yr-01-03"; break; case 0: $bankHols[] = "$yr-01-02"; break; default: $bankHols[] = "$yr-01-01"; } // Good friday: $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) - 2)." days", strtotime("$yr-03-21 12:00:00") )); // Easter Monday: $bankHols[] = date("Y-m-d", strtotime( "+".(easter_days($yr) + 1)." days", strtotime("$yr-03-21 12:00:00") )); // May Day: if ($yr == 1995) { $bankHols[] = "1995-05-08"; // VE day 50th anniversary year exception } else { switch (date("w", strtotime("$yr-05-01 12:00:00"))) { case 0: $bankHols[] = "$yr-05-02"; break; case 1: $bankHols[] = "$yr-05-01"; break; case 2: $bankHols[] = "$yr-05-07"; break; case 3: $bankHols[] = "$yr-05-06"; break; case 4: $bankHols[] = "$yr-05-05"; break; case 5: $bankHols[] = "$yr-05-04"; break; case 6: $bankHols[] = "$yr-05-03"; break; } } // Whitsun: if ($yr == 2002) { // exception year $bankHols[] = "2002-06-03"; $bankHols[] = "2002-06-04"; } else { switch (date("w", strtotime("$yr-05-31 12:00:00"))) { case 0: $bankHols[] = "$yr-05-25"; break; case 1: $bankHols[] = "$yr-05-31"; break; case 2: $bankHols[] = "$yr-05-30"; break; case 3: $bankHols[] = "$yr-05-29"; break; case 4: $bankHols[] = "$yr-05-28"; break; case 5: $bankHols[] = "$yr-05-27"; break; case 6: $bankHols[] = "$yr-05-26"; break; } } // Summer Bank Holiday: switch (date("w", strtotime("$yr-08-31 12:00:00"))) { case 0: $bankHols[] = "$yr-08-25"; break; case 1: $bankHols[] = "$yr-08-31"; break; case 2: $bankHols[] = "$yr-08-30"; break; case 3: $bankHols[] = "$yr-08-29"; break; case 4: $bankHols[] = "$yr-08-28"; break; case 5: $bankHols[] = "$yr-08-27"; break; case 6: $bankHols[] = "$yr-08-26"; break; } // Christmas: switch ( date("w", strtotime("$yr-12-25 12:00:00")) ) { case 5: $bankHols[] = "$yr-12-25"; $bankHols[] = "$yr-12-28"; break; case 6: $bankHols[] = "$yr-12-27"; $bankHols[] = "$yr-12-28"; break; case 0: $bankHols[] = "$yr-12-26"; $bankHols[] = "$yr-12-27"; break; default: $bankHols[] = "$yr-12-25"; $bankHols[] = "$yr-12-26"; } // Millenium eve if ($yr == 1999) { $bankHols[] = "1999-12-31"; } return $bankHols; } /* * EXAMPLE: * */ header("Content-type: text/plain"); $bankHolsThisYear = calculateBankHolidays(2007); print_r($bankHolsThisYear); ?> Will output this result: Array ( [0] => 2007-01-01 [1] => 2007-04-06 [2] => 2007-04-09 [3] => 2007-05-07 [4] => 2007-05-28 [5] => 2007-08-27 [6] => 2007-12-25 [7] => 2007-12-26 ) kbrill
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++; } ?> mushy
Heres a basic print out of a calender: <? $date_month = 7; $date_year = 2006; $theday = date(w, mktime(0, 0, 0, $date_month, 1, $date_year)); $daysinmonth = date("t", mktime(0, 0, 0, $date_month, 1, $date_year)); echo "<table border=1>"; echo "<tr>"; echo "<td>Sunday</td>"; echo "<td>Monday</td>"; echo "<td>Tuesday</td>"; echo "<td>Wednesday</td>"; echo "<td>Thursday</td>"; echo "<td>Friday</td>"; echo "<td>Saturday</td>"; echo "</tr>"; echo "<tr>"; for ($i=0;$i<$theday;$i++) { echo "<td> </td>"; } for ($list_day=1;$list_day<=$daysinmonth;$list_day++) { echo "<td>" . $list_day . "</td>"; if ($theday == 6) { echo "</tr>"; echo "<tr>"; $theday = -1; } $theday++; } echo "</tr>"; echo "</table>"; ?> kriswarner
Here's a useful bit of code - I took Mushy's code for displaying a calendar, and added links for viewing previous and next months, so you can go ahead or backwards as many months as you like, one month at a time. Basically the top row is changed, and looks like: December (prev) January February (next) Here it is: <? //determining action, current month and year $action = $_REQUEST['action']; if (!$action) //first page, set current_month variable = current month { $current_month = date("m"); //value will change if the user changes the month they are viewing $current_year = date('Y'); } else //if user selected to go to previous or next month, reset current_month variable { $current_month = $_REQUEST['current_month']; $current_year = $_REQUEST['current_year']; if ($action == 'prev') { $current_month = date('m', mktime(0, 0, 0, $current_month-1)); //if going from january to december, change year as well if ($current_month == '12') { $current_year = date('Y', mktime(0, 0, 0, $current_month, 1, $current_year-1)); } } if ($action == 'next') { $current_month = date('m', mktime(0, 0, 0, $current_month+1)); //if going from december to january, change year as well if ($current_month == '01') { $current_year = date('Y', mktime(0, 0, 0, $current_month, 1, $current_year+1)); } } } $previous_month = date('F', mktime(0, 0, 0, $current_month-1, date("d"), date("Y"))); $next_month = date('F', mktime(0, 0, 0, $current_month+1, date("d"), date("Y"))); $theday = date(w, mktime(0, 0, 0, $current_month, 1, $current_year)); $daysinmonth = date("t", mktime(0, 0, 0, $current_month, 1, $current_year)); echo "<table border=1 width=90%>"; echo "<tr><td><a href=$PHP_SELF?action=prev¤t_month=".$current_month." ¤t_year=".$current_year.">$previous_month</a></td> <td colspan=5 align=center>".date('F Y', mktime(0, 0, 0, $current_month, 1, $current_year))."</td> <td><a href=$PHP_SELF?action=next¤t_month=".$current_month." ¤t_year=".$current_year.">$next_month</a></td></tr>"; echo "<tr>"; echo "<td>Sunday</td>"; echo "<td>Monday</td>"; echo "<td>Tuesday</td>"; echo "<td>Wednesday</td>"; echo "<td>Thursday</td>"; echo "<td>Friday</td>"; echo "<td>Saturday</td>"; echo "</tr>"; echo "<tr>"; for ($i=0;$i<$theday;$i++) { echo "<td> </td>"; } for ($list_day=1;$list_day<=$daysinmonth;$list_day++) { echo "<td>" . $list_day . "</td>"; if ($theday == 6) { echo "</tr>"; echo "<tr>"; $theday = -1; } $theday++; } echo "</tr>"; echo "</table>"; ?> alvin delagon
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) 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; } llewellyntd
Here is a very easy way to get the difference, in days, between two dates: $days = (strtotime("2005-12-31") - strtotime(date("Y-m-d"))) / (60 * 60 * 24); print $days; eren - erenezgu
here is a simple code to print the time according to the clients timezone offset. This code gets the clients timezone with javascript and redirects the page to itself with timezone offset as a parameter. clienttime.php : <?php if ( isset($_GET['clientGMT']) ){ $clientGMT=intval( $_GET['clientGMT'] ); $serverGMT=intval( date('Z') ); echo date('H:i:s',time()+$clientGMT-$serverGMT); } else { ?> <SCRIPT TYPE="text/javascript"> <!-- var clientGMT=( (new Date()).getTimezoneOffset()*60)*(-1) ;//client timezone offset in seconds document.location='clienttime.php?clientGMT='+clientGMT ; //-> </SCRIPT> <?php } ?> mybenchmarkid
here is a function I wrote that was useful for a calendar application I was using. It returns an array of the valid dates between two parameter dates. enjoy. <? function DatesBetween($startDate, $endDate){ // get the number of days between the two given dates. $days = (strtotime($endDate) - strtotime($startDate)) / 86400 + 1; $startMonth = date("m", strtotime($startDate)); $startDay = date("d", strtotime($startDate)); $startYear = date("Y", strtotime($startDate)); $dates;//the array of dates to be passed back for($i=0; $i<$days; $i++){ $dates[$i] = date("n/j/Y", mktime(0, 0, 0, $startMonth , ($startDay+$i), $startYear)); } return $dates; } ?> example: $dates = DatesBetween("2/27/2007","3/3/2007") Array ( [0] => 2/27/2007 [1] => 2/28/2007 [2] => 3/1/2007 [3] => 3/2/2007 [4] => 3/3/2007 ) samuel
Here is a backward compatible version of dates_interconv http://www.php.net/manual/en/function.date.php#71397 which also works with time (hours, minutes and seconds) and months in "M" format (three letters): <?php /** mod of http://www.php.net/manual/en/function.date.php#71397 * Converts a date and time 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 "\n"; // for testing // print_r( $date_str_parts ); echo "\n"; // for testing $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; } // print_r($date_elements); // for testing if (array_key_exists('M', $date_elements)) { $Mtom=array( "Jan"=>"01", "Feb"=>"02", "Mar"=>"03", "Apr"=>"04", "May"=>"05", "Jun"=>"06", "Jul"=>"07", "Aug"=>"08", "Sep"=>"09", "Oct"=>"10", "Nov"=>"11", "Dec"=>"12", ); $date_elements['m']=$Mtom[$date_elements['M']]; } // print_r($date_elements); // for testing $dummy_ts = mktime( $date_elements['H'], $date_elements['i'], $date_elements['s'], $date_elements['m'], $date_elements['d'], $date_elements['Y'] ); return date( $date_format2, $dummy_ts ); } ?> Usage: <?php $df_src = 'd/m/Y H:i:s'; $df_des = 'Y-m-d H:i:s'; echo dates_interconv( $df_src, $df_des, '25/12/2005 23:59:59'); ?> Output: 2005-12-25 23:59:59 info
Hello, these notes have been very helpful and help me solve the following problem. I have a db with scheduled items that contain a start date, a day to occur on and how many weeks from the next closest day to happen again. I wrote the following script to do the following 1. Accept : starting date, the current date, the number of weeks between occurances and the day of the week it is to occur on. 2. Find the closest future day of the week argument from the start date. 3. Find out when the next time the item should happen via the weeks inbetween and the closest day of the week to the start date. The result could be compared with your current date to trigger your periodical item or simply to find out when the next occurances will happen. // $startDate:Date // $todayDate:Date // $weeks:Int - number of weeks in between // $wantDay:String - full day of the week function getWeekPeriodDate($startDate,$todayDate,$weeks,$wantDay){ $startDate = date("Y-m-d", strtotime("next $wantDay" ,strtotime($startDate))); $dayDiff = round((strtotime($startDate)-strtotime($todayDate))/(24*60*60),0); $weekPeriodDiff = abs(round($dayDiff/7/$weeks)*$weeks); return date("Y-m-d",strtotime($startDate . " + " . $weekPeriodDiff . " weeks")); } Usage :getWeekPeriodDate("2006-July-1","2007-Nov-5",8,"Tuesday") returns : 2007-11-20 (which is the next Tuesday based on 8 week periods since the next Tuesday closest to the start date) www.globalprompt.net
function dateDiff($dformat, $endDate, $beginDate) { $date_parts1=explode($dformat, $beginDate); $date_parts2=explode($dformat, $endDate); $start_date=gregoriantojd($date_parts1[0], $date_parts1[1], $date_parts1[2]); $end_date=gregoriantojd($date_parts2[0], $date_parts2[1], $date_parts2[2]); return $end_date - $start_date; } Now let us see how we use this function: $date1="07/11/2003"; $date2="09/04/2004"; print "If we minus " . $date1 . " from " . $date2 . " we get " . dateDiff("/", $date2, $date1) . "."; webmaster
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! 27-jul-2006 10:03
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 tszming
for performance wise, don't call too many date() unless you really need it i.e. don't: $tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y")); but: list($mon, $day, $year) = split("-", date("m-d-Y")); $tomorrow = mktime(0, 0, 0, $mon , $day+1, $year); pierrotevrard
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>'; ?> ben78
Find on the web. Diff between date seconds, minutes, hours, month, days and years! Very usefull and so simple :-) $d1=mktime(22,0,0,1,1,2007); $d2=mktime(0,0,0,1,2,2007); echo "Hours difference = ".floor(($d2-$d1)/3600) . " "; echo "Minutes difference = ".floor(($d2-$d1)/60) . " "; echo "Seconds difference = " .($d2-$d1). " "; echo "Month difference = ".floor(($d2-$d1)/2628000) . " "; echo "Days difference = ".floor(($d2-$d1)/86400) . " "; echo "Year difference = ".floor(($d2-$d1)/31536000) . " "; ron
Example 3 is really very bad programming practice. Calling date() more than once and putting the results together, can cause you to have a date or time that is inconsistent, or just plain invalid, because the system clock could easily change between the calls. Instead, call time() once up front to get the timestamp, then pass that into each call to date() like this: <?php $now = time(); $tomorrow = mktime(0, 0, 0, date("m", $now) , date("d", $now)+1, date("Y", $now)); $lastmonth = mktime(0, 0, 0, date("m", $now)-1, date("d", $now), date("Y", $now)); $nextyear = mktime(0, 0, 0, date("m", $now), date("d", $now), date("Y", $now)+1); ?> By doing this, we ensure that we're using the same system clock sampling for all date/time field formatting, thereby ensuring the results are consistent. josh
Ever had a DATETIME in a database and want to format it using the date() function? Me too. Here you go. <? // format MySQL DateTime (YYYY-MM-DD hh:mm:ss) using date() function datetime($syntax,$datetime) { $year = substr($datetime,0,4); $month = substr($datetime,5,2); $day = substr($datetime,8,2); $hour = substr($datetime,11,2); $min = substr($datetime,14,2); $sec = substr($datetime,17,2); return date($syntax,mktime($hour,$min,$sec,$month,$day,$year)); } ?> russ
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))); } ?> mg_peter
easy way - to convert a "datetime" form mySQL into php date format.... first - get the array form mySQL, then use <?php date("d M Y H:i:s", strtotime($your_row['lastlogin_date'])) ?> strtotime - easy converts a datetime timestamp into time ( time() or date("U")). jon
Don't forget that months start on the 1st day, and not a zero date. Might seem obvious but: $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); Will return November 2005, not December. $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); The 1st is needed to get the right month. mtphotographer
Determine what is next month: I Had the same issue as matt_wbdi at hotmail dot com Simple solution is use 1 for the day instead of date("d"), it didnt seem to matter if I use "m", or "n" for the month. // eg: // if today is 2007-01-30 the following: $datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, date("d"), date("Y")); echo date("Y-m", $datePlusoneMonth); //returns 2007-03 which is not next month // this worked for me: $datePlusoneMonth = mktime(0, 0, 0, date("m")+ 1, 1, date("Y")); echo date("Y-m", $datePlusoneMonth); // returns 2007-02, which IS next month batman
date("W") will not take into account US-system of weeks (it starts on Sunday). Example: According to ISO 8601, 1 Jan 2006 is on Sunday therefore in US-system 1 -- 7 January will be 52 week and not 1st! But date() will print 1 and not 52. hunterd1972
concatenate the values of each select statement to form the date into a month day, year format (i.e. January 1, 2007) and then use the strtotime function. <?php $timestamp = strtotime($month . " " . $day . ", " . $year); ?> vikram dot dhanjal
Code for generating time stamp for current time. May be useful for someone working on date and time things. /*Full right to modify and use it.*/ list($ch,$ci,$cs,$cm,$cd,$cy)=explode(",",date("H,i,s,m,d,y")); $now=mktime($ch,$ci,$cs,$cm,$cd,$cy); echo $now; eamon straughn eamon
Check this out this is a class i made last year for Gizzle.co.uk but sinced used on other projects and is quite a treat. It checks for a absolute valid date or datetime type. returns booleen. Disclaimer I do not take responsibility for the use of this class. I guarantees it works. <?php #Created By Eamon Straughn, Class extends Date() informally class isDate { private $arg; private $return = false; private $stack; private $stacks; private $pos = array(); private $poss = array(); public function __construct($arg) { $this->arg = trim($arg); } private function DateType() { //if length is more than 10 then it is not a date if(($n = strlen($this->arg)) > 10) return false; //if length is less than 6 then it is not a date elseif($n < 6) return false; //get values into arrays for processing for($i = 0; $i < $n; $i ++) { if(is_numeric($this->arg[$i])) $this->stack .= (isset($this->arg[$i])) ? $this->arg[$i] : null; elseif(($this->arg[$i] == "-") || ($this->arg[$i] == "/") || ($this->arg[$i] == "\\")) $this->pos[$i] = (isset($i)) ? $i : null; } //strip values to be checked if(is_numeric($c = substr($this->stack, 0, current($this->pos)))) $d = (strlen($c) > 2) ? substr($this->stack, current($this->pos), current($this->pos)/2) : substr($this->stack, current($this->pos), current($this->pos)); else return false; if(is_numeric($d)) if(is_numeric($e = substr($this->stack, end($this->pos)-1, end($this->pos)-1))); //convert string to integer $c = (int) $c; $d = (int) $d; $e = (int) $e; //check if it is a valid date if((checkdate($d,$c,$e)) || (checkdate($d,$e,$c))) return true; return false; } private function DateTimeType() { //if length is more than 10 then it is not a datetime if(($n = strlen($this->arg)) < 10) return false; //if length is less than 19 then it is not a datetime elseif($n < 19) return false; //get values into arrays for processing for($i = 0; $i < $n; $i ++) { if(is_numeric($this->arg[$i])) $this->stacks .= (isset($this->arg[$i])) ? $this->arg[$i] : null; elseif(($this->arg[$i] == "-") || ($this->arg[$i] == "/") || ($this->arg[$i] == "\\") || ($this->arg[$i] == " ") || ($this->arg[$i] == ":")) $this->poss[$i] = (isset($i)) ? $i : null; } //strip values to be checked if(is_numeric($c = substr($this->stacks, 0, current($this->poss)))) $d = (strlen($c) > 2) ? substr($this->stacks, current($this->poss), current($this->poss)/2) : substr($this->stacks, current($this->poss), current($this->poss)); else return false; if(is_numeric($d)) $e = (strlen($c) > 2) ? substr($this->stacks, next($this->poss)-1, (next($this->poss)-1)/4) : substr($this->stacks, next($this->poss)-1, (next($this->poss)-1)/2); if(is_numeric($e)) if(is_numeric($f = substr($this->stacks, (next($this->poss)/2)+2, 2))); if(is_numeric($g = substr($this->stacks, (next($this->poss)/2)+2, 2))); if(is_numeric($h = substr($this->stacks, (end($this->poss)/2)+4, 2))); //convert string to integer $c = (int) $c; $d = (int) $d; $e = (int) $e; $f = (int) $f; $g = (int) $g; $h = (int) $h; //check if the time is valid if($f > 24) return false; if($g > 60) return false; if($h > 60) return false; //check if it is a valid date if((checkdate($d,$c,$e)) || (checkdate($d,$e,$c))) return true; return false; } public function DateCheck() { if($this->DateTimeType()) $this->return = true; elseif($this->DateType()) $this->return = true; else $this->return = false; return $this->return; } } ?> example of use <?php //assign a date $d = "2006-12-12 10:15:00"; $t = "12-12-2006"; $f = "1-1-2001 10:23:09"; //the above can be used regardless if it is shortdate or long date but remember the year must always be 4 integers. $c = new isDate($d); if($c->CheckDate() !== false) echo $d; ?> if anyone wants to extend it to check time and posibly do more feel free to. Eamon.. itsacon
Caveat when using the 'W' and 'w' options together: The 'W' option uses the ISO-8601 standard (week ends on sunday), whereas the 'w' option has the week _start_ on sunday (sunday == 0). ag nodot nospam
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. function weeks($year) { return date("W",mktime(0,0,0,12,28,$year)); } mendoza
At "daykay at pdsoftware dot de": 09 != 9 so there's nothing wrong about European vs. American formats. $ php -r 'print 09; print "\n"; print 9; print "\n";' 0 9 09 is treated as octal and since octal numbers only use the 0-7 digits, it evaluates to 0. All numbers prefixed with 0 are considered octal just as 0x are considered hexadecimal. http://en.wikipedia.org/wiki/Computer_numbering_formats fokeyjoe
Another method for getting close to ISO8601 using PHP4 (should cover all versions). This format gets you compliant RDF/RSS feed dates: $sISO8601=date('Y-m-d\Th:i:s',$nTimestamp). substr_replace(date('O',$nTimestamp),':',3,0); The main limitation I'm aware of is the non-compliant year around new year. rob muhlestein
All functions that have anything to do with the internal 32-bit constrained time() system call will have this same limitation. Hopefully we'll be 64 bit by long before then, although this already creating problems with UNIX internals.
eves1985
A refinement on my last post is this one. It will output the current date and time of the user... just one simple line of code! <? $date = date('d-m-Y, H:i',(time()-date('Z'))); ?> Kind regards, Ewald wips
/** * Defines week limits. * Week numbers in [1..54]. First week is from 1st of Jan till first Sunday in year, last week is from last monday * in year till 31st of Dec. * * @param int $weekNumber - Week number * @param int $year - Year * @return array - array($start_time, $end_time). $start_time - begin of week, $end_time - end of week in Unix timestamp. * Precition is +-24 hours. */ function week_limits($weekNumber, $year) { // begin datetime $time = mktime(1, 1, 1, 1, 1, $year); // Aassuring that $weekNumber is number $weekNumber--; // If first week of year starts not from monday, date() will return "not correct" result (in this case first week is 0) if (date('w', $time) == 1) $weekNumber++; $start_time = false; $end_time = false; for ($day = 1; $day <= 380; $day++) { if (date('W', $time) == $weekNumber && !$start_time) $start_time = $time; if (date('W', $time - 24*60*60) == $weekNumber && !$end_time && date('W', $time) != $weekNumber) $end_time = $time - 24*60*60; if ($start_time && $end_time) break; $time += 24*60*60; } return array($start_time, $end_time); }//week_limits() jack
/** * 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 " "; print_r( $date_str_parts ); echo " "; $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 martin
/* 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://uk2.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; } josue resende
... class CalendarFunction { function holidays($year) { $return = array(); $return[ 1] = array(1); $return[12] = array(25); // feriados moveis return $return; } function qtDaysPerMonth($year, $month) { return intval(date('t', mktime(0, 0, 0, intval($month), 1, intval($year)))); } function daysPerMonth($year) { $return = array(); $weekday = date('w', mktime(0, 0, 0, 1, 1, intval($year))); $holidays = CalendarFunction::holidays($year); for ($month = 0; $month < 12; $month++) { $qt = CalendarFunction::qtDaysPerMonth($year, $month+1); $holidays_month = (isset($holidays[$month+1]) ? $holidays[$month+1] : array()); for($day = 1; $day <= $qt; $day++) { if (($weekday > 0 and $weekday < 6) and !in_array($day, $holidays_month)) { $return[$month+1][] = $day; } $weekday = ($weekday == 6 ? 0 : $weekday + 1); } } return $return; } } ... michiel
***EDITOR NOTE: Referred to note has been removed. The calculation function of the number of days between 2 dates by zzzdobr at gmai dot com could be done much easier: <? function getdays($day1,$day2) { return round((strtotime($day2)-strtotime($day1))/(24*60*60),0); } $begin = date("Y/m/d"); // we set today as an example $end = "2006/11/27"; getdays($begin,$end); ?> So now all of you know how many days you have left to buy me a birthday present ;) dwdaddhp
<?php function isago($hour, $min){ $difference=($hour*60+$min)-(date("H")*60+date("i")); if($difference<=0) return true; else if($difference>0) return false; } if(isago(20,0)) echo "after eight"; else echo "befor eight"; ?> boris
<?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; } ?> minterior
<?php /** * Calculate how old is a person with the birth date given */ function calculateYearsOld($bday, $bmonth, $byear) { $years = date("Y") - intval($byear); //If birthday is after today, he/she has one year old less $day = str_pad(intval($bday), 2, "0", STR_PAD_LEFT); $month = str_pad(intval($bmonth), 2, "0", STR_PAD_LEFT); if(intval("$month$day") > intval(date("md"))) $years -= 1; return $years; } ?> martin dot m
"It worked ok, except I noticed it had some trouble if you were spanning months, (i.e. 03-29-2005 to 04-10-2005)" this is the (Daylight Saving Time ) problem. you can check if the start date and the end date are whether or not in daylights savings time by using date('I',$your_date) and to add or decrease with one hour. |
Change Languagecheckdate date_create date_date_set date_default_timezone_get date_default_timezone_set date_format date_isodate_set date_modify date_offset_get date_parse date_sun_info date_sunrise date_sunset date_time_set date_timezone_get date_timezone_set date getdate gettimeofday gmdate gmmktime gmstrftime idate localtime microtime mktime strftime strptime strtotime time timezone_abbreviations_list timezone_identifiers_list timezone_name_from_abbr timezone_name_get timezone_offset_get timezone_open timezone_transitions_get |