There are a ton of snippets here and elsewhere on the Internet that are supposed to calculate time between two dates (or more precisely, between two UNIX timestamps), but none of them take leap years into account.
I wrote this snippet as a means of accurately calculating someone's age relative to the current time. This could be easily expanded to factor in months and days, but I will leave that as an exercise for the reader.
<?php
/*
* getAge() by Nathan Strong
* $start_ts is a UNIX timestamp sometime in the past.
* This function will not work with dates prior to epoch (EPOCH FAIL!)
*/
function getAge($start_ts)
{
$end_ts = time();
$anniversary = date('z', $start_ts);
$days_in_year = date('L', $start_ts) ? 366 : 365;
$sec_per_day = 86400; // 60 * 60 * 24
$diff = $end_ts - $start_ts;
$diff -= $diff % $sec_per_day; // discard misc seconds
$days = $diff / $sec_per_day; // number of days to iterate through;
if( $diff < 0 )
return false; // $start_ts is in the future!
if( $days < $days_in_year ) // less than 1 year old; don't need to loop
return 0;
$years = 0;
do {
// add the remaining days left in the current year first.
$left_in_year = $days_in_year - $anniversary;
if( $days < $left_in_year )
$left_in_year = $days;
$start_ts += $sec_per_day * $left_in_year;
$days -= $left_in_year;
// are there enough days remaining to make it to the next birthday?
if( $days > $anniversary )
{
$years++; // increment years;
$to_anniv = $anniversary;
} else {
$to_anniv = $days;
}
// add the days remaining to either the next birthday, or today's date, whichever
// is closer.
$start_ts += $sec_per_day * $to_anniv;
$days -= $to_anniv;
// reevaluate $days_in_year so that leap year is taken into account.
$days_in_year = date('L', $start_ts) ? 366 : 365;
} while( $days > 0 );
// return the result.
return $years;
}
?>
date
(PHP 4, PHP 5)
date — Formate une date/heure locale
Description
Retourne une date sous forme d'une chaîne, au format donné par le paramètre format , fournie par le paramètre timestamp ou la date et l'heure courantes si aucun timestamp n'est fourni. En d'autres termes, le paramètre timestamp est optionnel et vaut par défaut la valeur de la fonction time().
Liste de paramètres
- format
-
Le format de la date désirée. Voir les options de formatage ci-dessous.
Les caractères suivants sont reconnus dans le paramètre format . Caractères pour le paramètre format Description Exemple de valeurs retournées Jour --- --- d Jour du mois, sur deux chiffres (avec un zéro initial) 01 à 31 D Jour de la semaine, en trois lettres (et en anglais) Mon à Sun j Jour du mois sans les zéros initiaux 1 à 31 l ('L' minuscule) Jour de la semaine, textuel, version longue, en anglais Sunday à Saturday N Représentation numérique ISO-8601 du jour de la semaine (ajouté en PHP 5.1.0) 1 (pour Lundi) à 7 (pour Dimanche) S Suffixe ordinal d'un nombre pour le jour du mois, en anglais, sur deux lettres st, nd, rd ou th. Fonctionne bien avec j w Jour de la semaine au format numérique 0 (pour dimanche) à 6 (pour samedi) z Jour de l'année 0 à 366 Semaine --- --- W Numéro de semaine dans l'année ISO-8601, les semaines commencent le lundi (ajouté en PHP 4.1.0) Exemple : 42 (la 42ème semaine de l'année) Mois --- --- F Mois, textuel, version longue; en anglais, comme January ou December January à December m Mois au format numérique, avec zéros initiaux 01 à 12 M Mois, en trois lettres, en anglais Jan à Dec n Mois sans les zéros initiaux 1 à 12 t Nombre de jours dans le mois 28 à 31 Année --- --- L Est ce que l'année est bissextile 1 si bissextile, 0 sinon. o L'année ISO-8601. C'est la même valeur que Y, excepté que si le numéro de la semaine ISO (W) appartient à l'année précédente ou suivante, cette année sera utilisé à la place. (ajouté en PHP 5.1.0) Exemples : 1999 ou 2003 Y Année sur 4 chiffres Exemples : 1999 ou 2003 y Année sur 2 chiffres Exemples : 99 ou 03 Heure --- --- a Ante meridiem et Post meridiem en minuscules am ou pm A Ante meridiem et Post meridiem en majuscules AM ou PM B Heure Internet Swatch 000 à 999 g Heure, au format 12h, sans les zéros initiaux 1 à 12 G Heure, au format 24h, sans les zéros initiaux 0 à 23 h Heure, au format 12h, avec les zéros initiaux 01 à 12 H Heure, au format 24h, avec les zéros initiaux 00 à 23 i Minutes avec les zéros initiaux 00 à 59 s Secondes, avec zéros initiaux 00 à 59 u Microsecondes (ajouté en PHP 5.2.2) Exemple : 54321 Fuseau horaire --- --- e L'identifiant du fuseau horaire (ajouté en PHP 5.1.0) Exemples : UTC, GMT, Atlantic/Azores I (i majuscule) L'heure d'été est activée ou pas 1 si oui, 0 sinon. O Différence d'heures avec l'heure de Greenwich (GMT), exprimée en heures Exemple : +0200 P Différence avec l'heure Greenwich (GMT) avec un deux-points entre les heures et les minutes (ajouté dans PHP 5.1.3) Exemple : +02:00 T Abréviation du fuseau horaire Exemples : EST, MDT ... Z Décalage horaire en secondes. Le décalage des zones à l'ouest de la zone UTC est négative, et à l'est, il est positif. -43200 à 50400 Date et Heure complète --- --- c Date au format ISO 8601 (ajouté en PHP 5) 2004-02-12T15:19:21+00:00 r Format de date » RFC 2822 Exemple : Thu, 21 Dec 2000 16:01:07 +0200 U Secondes depuis l'époque Unix (1er Janvier 1970, 0h00 00s GMT) Voir aussi time() Les caractères non reconnus seront imprimés tels quel. "Z" retournera toujours 0 lorsqu'il est utilisé avec gmdate().
Note: Sachant que cette fonction n'accepte que des entiers sous la forme de timestamp, le caractère u n'est utile que lors de l'utilisation de la fonction date_format() avec un timestamp utilisateur créé avec la fonction date_create().
- timestamp
-
Le paramètre optionnel timestamp est un timestamp Unix de type entier qui vaut par défaut l'heure courante locale si le paramètre timestamp n'est pas fourni. En d'autres termes, il faut par défaut la valeur de la fonction time().
Valeurs de retour
Retourne une date formatée. Si une valeur non-numérique est utilisée dans le paramètre timestamp , FALSE sera retourné et une erreur de niveau E_WARNING est émise.
Erreurs / Exceptions
Chaque appel à une fonction date/heure générera un message de type E_NOTICE si le fuseau horaire n'est pas valide., et/ou un message de type E_STRICT si vous utilisez la configuration du système ou la variable d'environnement TZ. Voir aussi date_default_timezone_set()
Historique
| Version | Description |
|---|---|
| 5.1.0 | L'intervalle de validité d'un timestamp va généralement du Vendredi 13 Décembre 1901 20:45:54 GMT au Mardi 19 Janvier 2038 03:14:07 GMT. (Ces dates correspondent aux valeurs minimales et maximales des entiers 32 bits non-signés). Cependant, avant PHP 5.1.0, cette intervalle va du 01-01-1970 au 19-01-2038 sur quelques systèmes (e.g. Windows). |
| 5.1.0 | Émet un message de type E_STRICT et E_NOTICE lors d'erreurs de fuseaux horaires. |
| 5.1.1 | Il y a plusieurs constantes utiles de formats date/heure standards qui peuvent être utilisées pour spécifier le paramètre format . |
Exemples
Exemple #1 Exemple avec date()
<?php
// Définit le fuseau horaire par défaut à utiliser. Disponible depuis PHP 5.1
date_default_timezone_set('UTC');
// Affichage de quelque chose comme : Monday
echo date("l");
// Affichage de quelque chose comme : Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Affiche : July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* utilise les constantes dans le paramètre format */
// Affichage de quelque chose comme : Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// Affichage de quelque chose comme : 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
Vous pouvez faire afficher un caractère spécial dans la chaîne de format en le protégeant par un antislash. Si le caractère est lui-même une séquence incluant un antislash, vous devrez protéger aussi l'antislash.
Exemple #2 Protection des caractères dans la fonction date()
<?php
// Affichage de quelque chose comme : Wednesday the 15th
echo date("l \\t\h\e jS");
?>
Il est possible d'utiliser date() et mktime() ensemble pour générer des dates dans le futur ou dans le passé.
Exemple #3 Exemple avec date() et mktime()
<?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: Cette méthode est plus sûre que simplement ajouter ou retrancher le nombre de secondes dans une journée ou un mois à un timestamp, à cause des heures d'hiver et d'été.
Voici maintenant quelques exemples de formatage avec date(). Notez que vous devriez échapper tous les autres caractères, car s'ils ont une signification spéciale, ils risquent de produire des effets secondaires indésirables. Notez aussi que les versions futures de PHP peuvent attribuer une signification à des lettres qui sont actuellement inertes. Lorsque vous échappez les caractères, pensez à utiliser des guillemets simples, pour que les séquences \n ne deviennent pas des nouvelles lignes.
Exemple #4 Exemple avec date()
<?php
// Aujourd'hui, le 12 Mars 2001, 10:16:18 pm
$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 z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // C'est le 12th jour.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m est le mois
$today = date("H:i:s"); // 17:16:17
?>
Pour formater des dates dans d'autres langues, utilisez les fonctions setlocale() et strftime() au lieu de la fonction date().
Notes
Note: Pour générer un timestamp à partir d'une représentation de date, vous pouvez utiliser la fonction strtotime(). De plus, certaines bases de données disposent de fonctions pour convertir leurs propres formats de date en timestamps (par exemple, MySQL et sa fonction » UNIX_TIMESTAMP()).
Un timestamp représentant le début de la requête est disponible dans la variable $_SERVER['REQUEST_TIME'] depuis PHP 5.1.
date
06-Jan-2009 09:37
03-Jan-2009 09:31
This is adapted from sourabhshankar AT gmail DOT com
to allow you to get the week beginning and end from any day you give it.
$user_date = '2008-12-31';
$sun = 0; //sunday = start of week
$sat = 6; //saturday = end of week
$user_date = strtotime($user_date);
$dayOfWeek = date('w', $user_date); // get day number
$days_until_sat = $sat - $dayOfWeek;
$days_from_sun = $dayOfWeek - $sun;
$week_start = strtotime(" - $days_from_sun days", $user_date);
$week_end = strtotime(" + $days_until_sat days", $user_date);
29-Dec-2008 09:36
a while back i grabbed some code from this page that would generate the range of the current week, called getWeekRange...
well this week spans 2 years, and it breaks the code... so i re-wrote it. enjoy
<?php
#-----------------------------------------------------------------#
# getWeekRange:
function getWeekRange(&$start_date, &$end_date, $week_offset=0) {
$start_date = '';
$end_date = '';
// todays information
list($yr, $mo, $da, $word)
= explode('-', date("Y-m-d-l", strtotime("+".abs($week_offset)." week")));
// 0 (for Sunday) through 6 (for Saturday)
$day_of_current_week = date('w', strtotime("+".abs($week_offset)." week"));
// on sunday, they want last week through today.
if ($day_of_current_week == 0){
$day_of_current_week = 7;
}
// calculate day offset to monday and sunday
$days_to_monday = 1 - $day_of_current_week;
$days_to_sunday = 7 - $day_of_current_week;
// set the start and end dates for this week
$start_date = date('Y-m-d', mktime(0, 0, 0, $mo, ($da + ($days_to_monday)), $yr));
$end_date = date('Y-m-d', mktime(0, 0, 0, $mo, ($da + ($days_to_sunday)), $yr));
}
#-----------------------------------------------------------------#
// test it
echo "<pre>";
for ($i=0;$i<=52;$i++){
getWeekRange($start,$end,$i);
echo "[".date("Y-m-d-l",strtotime($start))."] [".date("Y-m-d-l",strtotime($end))."]\n";
}
echo "</pre>";
#-----------------------------------------------------------------#
?>
outputs:
[2008-12-29-Monday][2009-01-04-Sunday]
[2009-01-05-Monday][2009-01-11-Sunday]
[2009-01-12-Monday][2009-01-18-Sunday]
26-Dec-2008 02:16
A comment about the code from tchapin at gmail dot com:
Many scripts calculate dates as the difference in days between two dates, and then divide by 365 to get years. This of course is inaccurate without considering leap years. If the purpose is to find a person's age or current birthday, being off a few days is important. The following approach corrects for this.
<?php
/*
* finds & returns the age of a person given their birth_date
* $birth_date is assumed be a string in the format yyyy-mm-dd
*/
function age_now($birth_date) {
list($year,$mon,$day) = explode("-",$birth_date);
$today = getdate(time());
// find the difference in the years of the two dates
$yeardiff = $today['year'] - $year;
// if the current date occurs before the birthday, subtract one
$birth_jd = gregoriantojd($mon,$day,$today['year']);
$today_jd = gregoriantojd($today['mon'],$today['mday'],$today['year']);
if ($today_jd < $birth_jd) {
$yeardiff--;
}
return($yeardiff);
}
?>
05-Dec-2008 07:38
<?php
function getNoWorkingDays()
{
$days_in_month = date('t');
$noofwokingdays=0;
for ($j=0; $j<$days_in_month; $j++)
{
$d = $j + 1;
$my = date('m-Y');
$day_of_week = date('w', strtotime("$d-$my", 0));
if ( $day_of_week == 6 || $day_of_week == 0)
{
$noofwokingdays=$noofwokingdays;
}
else
{
$noofwokingdays++;
}
}
return $noofwokingdays;
}
?>
27-Nov-2008 10:59
Reverse of getWorkingDays() function.
<?php
function getTargetWorkingDate($startDate, $days, $holidays = null) {
$the_first_day_of_week = date("N",strtotime($startDate));
if($the_first_day_of_week == 6) $b_extra+=2;
if($the_first_day_of_week == 7) $b_extra++;
$startDate = getdate((($b_extra) * 86400) + strtotime($startDate));
$startDate = $startDate['year'] . "-" . $startDate['mon'] . "-" . $startDate['mday'];
$no_weeks = floor($days / 5);
$extra_days = $no_weeks * 2;
$endDate = getdate((($days+$extra_days) * 86400) + strtotime($startDate));
$endDate = $endDate['year'] . "-" . $endDate['mon'] . "-" . $endDate['mday'];
if($holidays) {
foreach($holidays as $holiday){
$time_stamp = strtotime($holiday);
if (strtotime($startDate) <= $time_stamp && $time_stamp <= strtotime($endDate) && date("N",$time_stamp) != 6 && date("N",$time_stamp) != 7)
$extra_days++;
}
}
$endDate = getdate((($days+$extra_days) * 86400) + strtotime($startDate));
$endDate = $endDate['year'] . "-" . $endDate['mon'] . "-" . $endDate['mday'];
$the_last_day_of_week = date("N",strtotime($endDate));
if($the_last_day_of_week == 6) $e_extra+=2;
if($the_last_day_of_week == 7) $e_extra++;
$endDate = getdate((($e_extra) * 86400) + strtotime($endDate));
$endDate = $endDate['year'] . "-" . $endDate['mon'] . "-" . $endDate['mday'];
return $endDate;
}
?>
18-Nov-2008 08:33
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
14-Nov-2008 09:43
<?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
*/
?>
10-Nov-2008 07:26
<?php
// Function used to take two date strings, and returns an associative array
// with different formats for the difference between the dates.
// --------------------
// Variables:
// StartDateString (String - MM/DD/YYYY)
// EndDateString (String - MM/DD/YYYY)
// --------------------
// Example: $DateDiffAry = GetDateDifference('01/09/2008', '02/11/2009');
// print_r($DateDiffAry);
// --------------------
// Returns Something Like:
/*
Array
(
[YearsSince] => 1.0931506849315
[MonthsSince] => 13.117808219178
[DaysSince] => 399
[HoursSince] => 9576
[MinutesSince] => 574560
[SecondsSince] => 34473600
[NiceString] => 1 year, 1 month, and 2 days
[NiceString2] => Years: 1, Months: 1, Days: 2
)
*/
function GetDateDifference($StartDateString=NULL, $EndDateString=NULL) {
$ReturnArray = array();
$SDSplit = explode('/',$StartDateString);
$StartDate = mktime(0,0,0,$SDSplit[0],$SDSplit[1],$SDSplit[2]);
$EDSplit = explode('/',$EndDateString);
$EndDate = mktime(0,0,0,$EDSplit[0],$EDSplit[1],$EDSplit[2]);
$DateDifference = $EndDate-$StartDate;
$ReturnArray['YearsSince'] = $DateDifference/60/60/24/365;
$ReturnArray['MonthsSince'] = $DateDifference/60/60/24/365*12;
$ReturnArray['DaysSince'] = $DateDifference/60/60/24;
$ReturnArray['HoursSince'] = $DateDifference/60/60;
$ReturnArray['MinutesSince'] = $DateDifference/60;
$ReturnArray['SecondsSince'] = $DateDifference;
$y1 = date("Y", $StartDate);
$m1 = date("m", $StartDate);
$d1 = date("d", $StartDate);
$y2 = date("Y", $EndDate);
$m2 = date("m", $EndDate);
$d2 = date("d", $EndDate);
$diff = '';
$diff2 = '';
if (($EndDate - $StartDate)<=0) {
// Start date is before or equal to end date!
$diff = "0 days";
$diff2 = "Days: 0";
} else {
$y = $y2 - $y1;
$m = $m2 - $m1;
$d = $d2 - $d1;
$daysInMonth = date("t",$StartDate);
if ($d<0) {$m--;$d=$daysInMonth+$d;}
if ($m<0) {$y--;$m=12+$m;}
$daysInMonth = date("t",$m2);
// Nicestring ("1 year, 1 month, and 5 days")
if ($y>0) $diff .= $y==1 ? "1 year" : "$y years";
if ($y>0 && $m>0) $diff .= ", ";
if ($m>0) $diff .= $m==1? "1 month" : "$m months";
if (($m>0||$y>0) && $d>0) $diff .= ", and ";
if ($d>0) $diff .= $d==1 ? "1 day" : "$d days";
// Nicestring 2 ("Years: 1, Months: 1, Days: 1")
if ($y>0) $diff2 .= $y==1 ? "Years: 1" : "Years: $y";
if ($y>0 && $m>0) $diff2 .= ", ";
if ($m>0) $diff2 .= $m==1? "Months: 1" : "Months: $m";
if (($m>0||$y>0) && $d>0) $diff2 .= ", ";
if ($d>0) $diff2 .= $d==1 ? "Days: 1" : "Days: $d";
}
$ReturnArray['NiceString'] = $diff;
$ReturnArray['NiceString2'] = $diff2;
return $ReturnArray;
}
// Example:
$DateDiffAry = GetDateDifference('01/09/2008', '02/11/2009');
print_r($DateDiffAry);
?>
03-Nov-2008 12:38
Here's a small function which returns TRUE if European Summer Time is used (now or at a given date) :
<?php
if(!function_exists('estdst'))
{
function estdst($ts=false)
{
$ts = $ts?$ts:time();
$year = gmdate('Y', $ts);
$end = gmmktime(1, 0, 0, 3, 31 - ((5 * $year) / 4 + 4)%7, $year);
$start = gmmktime(1, 0, 0, 10, 31 - ((5 * $year) / 4 + 1)%7, $year);
return $ts < $end || $ts > $start;
}
}
?>
Calculation formula taken from here : http://en.wikipedia.org/wiki/European_Summer_Time
31-Oct-2008 09:46
I need to display graphic-A during hours 1-9 and graphic-B during hours 10-24. Anybody know of a simple way to do this? Better yet, if we can select times based upon the day of the week, it would be even better!
I tried searching, but didn't inf anything resembling this. The coding will be added to a product description in osCommerce, which accepts html coding easily but other scripting types may or may not work. I want an OPEN graphic to display during normal business hours, and CLOSED when outside these hours.
Thanks in advance!
22-Oct-2008 03:41
i figured i would post this, it's only useful for systems dealing with UTC and EST, but could easily be modified to support multiple timezones. this function will tell you whether it's daylight saving time for the eastern timezone using UTC localtime:
<?php
//checks whether DST in EST using UTC
//can pass $time in unix timestamp, otherwise uses time()
function est_isdst($time=NULL){
if(!$time) { $now = time(); }else { $now = $time; }
if (
$now > strtotime(date('Y-m-d 6:59:59', strtotime('next Sunday', strtotime(date('Y', $now).'-3-7')))) &&
$now < strtotime(date('Y-m-d 6:00', strtotime('first Sunday', strtotime(date('Y', $now).'-11-0'))))
) { return true; }else { return false; }
}
?>
USAGE:
<?php
if(est_isdst()) { echo 'Its DST in EST Timezone!'; }
?>
07-Oct-2008 11:56
Aditya Bhatt (adityabhai [at] gmail [dot] com):
I have one date, and i want the next day of that date:
<?php
echo date("D F d Y",strtotime("+1 days")); // Same applies for months e.g. "+1 months"
?>
I have one date, and i want the previous day of that date:
<?php
echo date("D F d Y",strtotime("-1 days")); // Same applies for months e.g. "-1 months"
?>
03-Oct-2008 12:52
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').
25-Sep-2008 05:48
RE: wulf dot kaiser at mpimf-heidelberg dot mpg dot de code to work out fridays in a month. I noticed one small error. It looks like the
<?php
if ($givenMonth != '12') {
$nextGivenMonth = "1";
$nextGivenYear = $givenYear + 1;}
?>
block was setting every month to 1 because it was not equal to 12. I changed that to <?php if ($givenMonth == '12') { ?>and now all is fine!
Now - to refine it so that it only shows Fridays on the 5th or after, until the 4th of the next month.. Damm UK tax stuff!
=)
N
25-Sep-2008 01:35
MySQL 5 will accept ISO_8601 encoded time, so it is acceptable to use date(ISO_8601)
12-Sep-2008 03:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
27-Aug-2008 08:47
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
?>
26-Aug-2008 02:32
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
15-Aug-2008 12:53
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.
06-Aug-2008 08:25
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);
}
?>
25-Jul-2008 10:22
<?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>
<?
}
?></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>
<?
}
?></div>
10-Jul-2008 06:38
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.
10-Jul-2008 05:46
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(