(PHP 4, PHP 5)
date — Formatiert ein(e) angegebene(s) Ortszeit/Datum
Gibt einen formatierten String anhand eines vorzugebenden Musters zurück. Dabei wird entweder der angegebene Timestamp oder die gegenwärtige lokale Zeit berücksichtigt, wenn kein Timestamp angegegeben wird. Mit anderen Worten ausgedrückt: der Parameter Timestamp ist optional und falls dieser nicht angegeben wird, wird der Wert der Funktion time() angenommen.
Das Muster des auszugebenden Datums-/Zeit-String. Unten sind die verfügbaren Formatierungsoptionen angegeben. Es gibt auch verschiedene vordefinierte Konstanten, die verwendet werden können, z.B. enthält DATE_RSS das Formatierungsmuster 'D, d M Y H:i:s'.
Format-Zeichen | Beschreibung | Beispiel für Rückgabewerte |
---|---|---|
Tag | --- | --- |
d | Tag des Monats, 2-stellig mit führender Null | 01 bis 31 |
D | Wochentag, gekürzt auf drei Buchstaben | Mon bis Sun |
j | Tag des Monats ohne führende Nullen | 1 bis 31 |
l (kleines 'L') | Ausgeschriebener Wochentags | Sunday bis Saturday |
N | Numerische Repräsentation des Wochentages gemäß ISO-8601 (in PHP 5.1.0 hinzugefügt) | 1 (für Montag) bis 7 (für Sonntag) |
S | Anhang der englischen Aufzählung für einen Monatstag, zwei Zeichen | st, nd, rd oder th. Zur Verwendung mit j empfohlen. |
w | Numerischer Tag einer Woche | 0 (für Sonntag) bis 6 (für Samstag) |
z | Der Tag des Jahres (von 0 beginnend) | 0 bis365 |
Woche | --- | --- |
W | ISO-8601 Wochennummer des Jahres, die Woche beginnt am Montag (hinzugefügt in PHP 4.1.0) | Beispiel: 42 (die 42. Woche im Jahr) |
Monat | --- | --- |
F | Monat als ganzes Wort, wie January oder March | January bis December |
m | Monat als Zahl, mit führenden Nullen | 01 bis 12 |
M | Monatsname mit drei Buchstaben | Jan bis Dec |
n | Monatszahl, ohne führende Nullen | 1 bis 12 |
t | Anzahl der Tage des angegebenen Monats | 28 bis 31 |
Jahr | --- | --- |
L | Schaltjahr oder nicht | 1 für ein Schaltjahr, ansonsten 0 |
o | Jahreszahl gemäß ISO-8601. Dies ergibt den gleichen Wert wie Y, außer wenn die ISO-Kalenderwoche (W) zum vorhergehenden oder nächsten Jahr gehört, wobei dann jenes Jahr verwendet wird (in PHP 5.1.0 hinzugefügt). | Beispiele: 1999 oder 2003 |
Y | Vierstellige Jahreszahl | Beispiele: 1999 oder 2003 |
y | Jahreszahl, zweistellig | Beispiele: 99 oder 03 |
Uhrzeit | --- | --- |
a | Kleingeschrieben: Ante meridiem (Vormittag) und Post meridiem (Nachmittag) | am oder pm |
A | Großgeschrieben: Ante meridiem (Vormittag) und Post meridiem (Nachmittag) | AM oder PM |
B | Swatch-Internet-Zeit | 000 bis 999 |
g | Stunde im 12-Stunden-Format, ohne führende Nullen | 1 bis 12 |
G | Stunde im 24-Stunden-Format, ohne führende Nullen | 0 bis 23 |
h | Stunde im 12-Stunden-Format, mit führenden Nullen | 01 bis 12 |
H | Stunde im 24-Stunden-Format, mit führenden Nullen | 00 bis 23 |
i | Minuten, mit führenden Nullen | 00 bis 59 |
s | Sekunden, mit führenden Nullen | 00 bis 59 |
u | Mikrosekunden (hinzugefügt in PHP 5.2.2) | Beispiel: 654321 |
Zeitzone | --- | --- |
e | Zeitzonen-Bezeichner (hinzugefügt in PHP 5.1.0) | Beispiele: UTC, GMT, Atlantic/Azores |
I (großes 'i') | Fällt ein Datum in die Sommerzeit | 1 bei Sommerzeit, ansonsten 0. |
O | Zeitunterschied zur Greenwich time (GMT) in Stunden | Beispiel: +0200 |
P | Zeitunterschied zur Greenwich time (GMT) in Stunden mit Doppelpunkt zwischen Stunden und Minuten (hinzugefügt in PHP 5.1.3) | Beispiel: +02:00 |
T | Abkürzung der Zeitzone | Beispiele: EST, MDT ... |
Z | Offset der Zeitzone in Sekunden. Der Offset für Zeitzonen westlich von UTC ist immer negativ und für Zeitzonen östlich von UTC immer positiv. | -43200 bis 50400 |
Vollständige(s) Datum/Uhrzeit | --- | --- |
c | ISO 8601 Datum (hinzugefügt in PHP 5) | 2004-02-12T15:19:21+00:00 |
r | Gemäß » RFC 2822 formatiertes Datum | Beispiel: Thu, 21 Dec 2000 16:01:07 +0200 |
U | Sekunden seit Beginn der UNIX-Epoche (January 1 1970 00:00:00 GMT) | Siehe auch time() |
Nicht erkannte Zeichen werden unverändert ausgegeben. Das Z-Format gibt beim Gebrauch von gmdate() immer 0 zurück.
Hinweis:
Weil diese Funktion nur Integer-Zeitstempel akzeptiert, ist die Formatanweisung u nur nützlich, wenn man die Funktion date_format() mit von Benutzern angegebenen Timestamps aus der Funktion date_create() verwendet.
Der optionale Parameter timestamp ist ein Unix Timestamp als integer oder die aktuelle lokale Zeit wenn kein timestamp übergeben wurde. Er entspricht dann also dem Ergebnis der Funktion time().
Gibt eine formatierte Datums-Zeichenkette zurück. Falls ein nicht numerischer Wert als timestamp übergeben wird, wird FALSE zurückgegeben und ein Fehler der Stufe E_WARNING erzeugt.
Jeder Aufruf der Datums- und Zeitfunktionen generiert eine E_NOTICE-Warnung, wenn die Zeitzone ungültig ist und eine E_STRICT-Nachricht oder eine E_WARNING-Warnung, wenn die Systemeinstellung oder die TZ-Umgebungsvariable genutzt wird. Siehe auch date_default_timezone_set()
Version | Beschreibung |
---|---|
5.1.0 | Der gültige Bereich eines Timestamp liegt typischerweise zwischen Fri, 13 Dec 1901 20:45:54 GMT und Tue, 19 Jan 2038 03:14:07 GMT. (Das entspricht den minimalen und maximalen Werten für einen vorzeichenbehafteten 32-Bit Integer). Vor PHP 5.1.0 war dieser Bereich auf manchen Systemen (z.B. Windows) eingeschränkt auf 01.01.1971 bis 19.01.2038. |
5.1.0 | Erzeugt nun E_STRICT- und E_NOTICE-Zeitzonenfehler. |
5.1.1 | Es gibt nützliche Konstanten von üblichen Datums-/Zeitformaten, die als Format-Parameter übergeben werden können. |
Beispiel #1 date()-Beispiele
<?php
// Die Standard-Zeitzone, die verwendet werden soll, setzen.
// Verfügbar seit PHP 5.1
date_default_timezone_set('UTC');
// Gibt etwas aus wie: 'Monday'
echo date("l");
// Gibt etwas aus wie: 'Monday 8th of August 2005 03:12:46 PM'
echo date('l jS \of F Y h:i:s A');
// Gibt aus: 'July 1, 2000 ist ein Saturday'
echo "July 1, 2000 ist ein " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* Verwende die Konstanten im Format-Parameter */
// Gibt etwas aus wie 'Mon, 15 Aug 2005 15:12:46 UTC'
echo date(DATE_RFC822);
// Gibt etwas aus wie '2000-07-01T00:00:00+00:00'
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
Möchten Sie verhindern, dass ein erkanntes Zeichen im Formatstring ersetzt wird, sollten Sie dieses Zeichen mit einem vorangestellten Backslash escapen. Ist das Zeichen mit dem Backslash bereits eine spezielle Zeichenfolge, müssen Sie diesen Backslash ebenso escapen.
Beispiel #2 Escaping von Zeichen in date()
<?php
// Gibt etwas ähnliches aus wie 'Wednesday the 15th'
echo date("l \\t\h\e jS");
?>
Es ist möglich, date() und mktime() gleichzeitig zu verwenden, um Datumsangaben in der Zukunft oder Vergangenheit zu bestimmen.
Beispiel #3 date() und mktime()-Beispiele
<?php
$morgen = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$letztermonat = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$naechstesjahr = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Hinweis:
Dieses Vorgehen kann zu verlässlicheren Ergebnissen führen, als simples addieren oder subtrahieren der Anzahl von Sekunden in Tagen oder Monaten zu einem Timestamp, da Sommer- und Winterzeit berücksichtigt werden.
Es folgen einige Beispiele zur date()-Formatierung. Beachten Sie, dass Sie alle anderen Zeichen escapen sollten, da alle Zeichen, die im Augenblick eine spezielle Bedeutung haben, unerwünschte Resultate liefern. Bei allen weiteren Zeichen kann es durchaus möglich sein, dass diesen in zukünftigen PHP-Versionen eine Bedeutung zukommt. Beim Escapen sollten Sie darauf achten, einfache Anführungszeichen zu benutzen, damit Zeichenfolgen wie zum Beispiel \n zu keinem Zeilenumbruch führen.
Beispiel #4 date()-Formatierungen
<?php
// ANgenommen, heute ist der 10. März 2001, 17:16:18 Uhr und wir
// befinden uns in der Zeitzone Mountain Standard Time (MST)
$heute = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$heute = date("m.d.y"); // 03.10.01
$heute = date("j, n, Y"); // 10, 3, 2001
$heute = date("Ymd"); // 20010310
$heute = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$heute = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day.
$heute = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$heute = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month
$heute = date("H:i:s"); // 17:16:18
?>
Um Datumsangaben in anderen Sprachen auszugeben, sollten Sie die Funktionen setlocale() und strftime() statt date() verwendet werden.
Hinweis:
Um einen Zeitstempel aus einer Textrepräsentation eines Datums zu erzeugen, kann die Funktion strtotime() verwendet werden. Einige Datenbanken haben außerdem Funktionen, mit denen ihre Datumsformate in Zeitstempel konvertiert werden können (wie z.B. die Funktion » UNIX_TIMESTAMP von MySQL).
Der Zeitstempel des Verarbeitungsbeginns der HTTP-Anfrage wird seit PHP 5.1 in $_SERVER['REQUEST_TIME'] bereitgestellt.
convert an SQL datetime field to a unixtimestamp to set a new format in the output
<?php $time_output=date("d-m-Y H:i",strtotime ($datetime_fromSQL)); ?>
A function to show $a days later.
<?php
function dateafter ( $a )
{
$hours = $a * 24;
$added = ($hours * 3600)+time();
$days = date("l", $added);
$month = date("F", $added);
$day = date("j", $added);
$year = date("Y", $added);
$result = "$day $month $year - $days";
return ($result);
}
echo dateafter("10");
//this will shows the data of ten days after.
// if today is 19 December 2010, Sunday, the page prints : 29 December 2010 - Wednesday.
?>
Most spreadsheet programs have a rather nice little built-in function called NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday, excluding holidays) between any two given dates. I couldn't find a simple way to do that in PHP, so I threw this together. It replicates the functionality of OpenOffice's NETWORKDAYS function - you give it a start date, an end date, and an array of any holidays you want skipped, and it'll tell you the number of business days (inclusive of the start and end days!) between them.
I've tested it pretty strenuously but date arithmetic is complicated and there's always the possibility I missed something, so please feel free to check my math.
The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. "skip all Fridays and Saturdays but include Sundays") or to set up dates that should always be skipped (e.g. "skip July 4th in any year, skip the first Monday in September in any year"). But that's a project for another time.
<?php
function networkdays($s, $e, $holidays = array()) {
// If the start and end dates are given in the wrong order, flip them.
if ($s > $e)
return networkdays($e, $s, $holidays);
// Find the ISO-8601 day of the week for the two dates.
$sd = date("N", $s);
$ed = date("N", $e);
// Find the number of weeks between the dates.
$w = floor(($e - $s)/(86400*7)); # Divide the difference in the two times by seven days to get the number of weeks.
if ($ed >= $sd) { $w--; } # If the end date falls on the same day of the week or a later day of the week than the start date, subtract a week.
// Calculate net working days.
$nwd = max(6 - $sd, 0); # If the start day is Saturday or Sunday, add zero, otherewise add six minus the weekday number.
$nwd += min($ed, 5); # If the end day is Saturday or Sunday, add five, otherwise add the weekday number.
$nwd += $w * 5; # Add five days for each week in between.
// Iterate through the array of holidays. For each holiday between the start and end dates that isn't a Saturday or a Sunday, remove one day.
foreach ($holidays as $h) {
$h = strtotime($h);
if ($h > $s && $h < $e && date("N", $h) < 6)
$nwd--;
}
return $nwd;
}
$start = strtotime("1 January 2010");
$end = strtotime("13 December 2010");
// Add as many holidays as desired.
$holidays = array();
$holidays[] = "4 July 2010"; // Falls on a Sunday; doesn't affect count
$holidays[] = "6 September 2010"; // Falls on a Monday; reduces count by one
echo networkdays($start, $end, $holidays); // Returns 246
?>
Or, if you just want to know how many work days there are in any given year, here's a quick function for that one:
<?php
function workdaysinyear($y) {
$j1 = mktime(0,0,0,1,1,$y);
if (date("L", $j1)) {
if (date("N", $j1) == 6)
return 260;
elseif (date("N", $j1) == 5 or date("N", $j1) == 7)
return 261;
else
return 262;
}
else {
if (date("N", $j1) == 6 or date("N", $j1) == 7)
return 260;
else
return 261;
}
}
?>
Here is simple function to generate date selection, useful for admin panels ....
<?php
public static function dateRange($fmt = 'j-n-Y', $sep='+') {
$current_time = time();
$year = date('Y',$curr_time);
$month = date('n',$curr_time);
$day = date('j',$curr_time);
$today = date($fmt, $curr_time);
$r = array (
'all' => $sep.$sep.$sep,
'today' => $today.$sep.$today,
'yesterday' => date($fmt, strtotime('-1 day',$curr_time)).$sep.date($fmt, strtotime('-1 day',$curr_time)),
'last7days' => date($fmt, strtotime('-7 day',$curr_time)).$sep.$today,
'thismonth' => date($fmt, mktime(0,0,0,$month, 1, $year)).$sep.$today,
'thisyear' => date($fmt, mktime(0,0,0,1, 1, $year) ).$sep.$today,
);
return $r;
}
?>
this function returns the current date of server subtracted from a number of days passed as parameter
<?php
function subtractDaysFromToday($number_of_days)
{
$today = mktime(0, 0, 0, date('m'), date('d'), date('Y'));
$subtract = $today - (86400 * $number_of_days);
//choice a date format here
return date("Y-m-d", $subtract);
}
?>
Simple and handy function that offsets a MySQL formatted date and returns the new correctly formatted date
<?php
/**
*
* @param string $dt // MySQL formatted date (like 2010-01-01)
* @param int $year_offset // like 2 or -2, or 5 or -5 ...
* @param int $month_offset // like 2 or -2, or 5 or -5 ...
* @param in $day_offset // like 2 or -2, or 5 or -5 ...
* @return string // the new MySQL formatted date (like 2009-07-01)
*/
function MySQLDateOffset($dt,$year_offset='',$month_offset='',$day_offset='')
{
return ($dt=='0000-00-00') ? '' :
date ("Y-m-d", mktime(0,0,0,substr($dt,5,2)+$month_offset,substr($dt,8,2)+
$day_offset,substr($dt,0,4)+$year_offset));
}
?>
Examples:
<?php
echo MySQLDateOffset('2010-06-01',2,5,15);
// will return 2012-11-16
echo MySQLDateOffset('2010-06-01',-6,5,38);
// will return 2004-12-09
?>
A really simple way to check if today's the last day of the month:
<?php
// If today is the last day of the month, do stuff
if(date('j') == date('t')) {
// Do Stuff
}
?>
Simple function to return the last business day of a given month (but this does not check holidays)
Função para retornar o último dia útil de um determinado mês (não verifica feriados)
example:
<?php echo last_business_day(2010,02); //2010-02-26 ?>
<?php
function last_business_day($year,$month)
{
$lbd = cal_days_in_month(CAL_GREGORIAN, $month, $year);
$wday = date("N",strtotime("$year-$month-$lbd"));
if ($wday == 7) $lbd -= 2;
if ($wday == 6) $lbd--;
$lbd = date("Y-m-d",strtotime("$year-$month-$lbd"));
return $lbd;
}
?>
A function I use for 'date ago' used on message/comment boards
First, use this date('ymdHi') whenever entering the timestamp into your database.
Here's the function to retrieve how long ago it was entered. $querydate is timestamp retrieved from the database. Just call this function.
<?php
function returnDate($querydate){
$minusdate = date('ymdHi') - $querydate;
if($minusdate > 88697640 && $minusdate < 100000000){
$minusdate = $minusdate - 88697640;
}
switch ($minusdate) {
case ($minusdate < 99):
if($minusdate == 1){
$date_string = '1 minute ago';
}
elseif($minusdate > 59){
$date_string = ($minusdate - 40).' minutes ago';
}
elseif($minusdate > 1 && $minusdate < 59){
$date_string = $minusdate.' minutes ago';
}
break;
case ($minusdate > 99 && $minusdate < 2359):
$flr = floor($minusdate * .01);
if($flr == 1){
$date_string = '1 hour ago';
}
else{
$date_string = $flr.' hours ago';
}
break;
case ($minusdate > 2359 && $minusdate < 310000):
$flr = floor($minusdate * .0001);
if($flr == 1){
$date_string = '1 day ago';
}
else{
$date_string = $flr.' days ago';
}
break;
case ($minusdate > 310001 && $minusdate < 12320000):
$flr = floor($minusdate * .000001);
if($flr == 1){
$date_string = "1 month ago";
}
else{
$date_string = $flr.' months ago';
}
break;
case ($minusdate > 100000000):
$flr = floor($minusdate * .00000001);
if($flr == 1){
$date_string = '1 year ago.';
}
else{
$date_string = $flr.' years ago';
}
}
return $date_string;
}
?>
Here is a very simple function to get quarterly dates.
<?php
function quarter($month='',$day='')
{
if($month != ""){$tm = mktime(0,0,0,$month,$day-1,date('Y'));}else{$tm = date('Y-m-d H:i:s');}
$quarter = ceil(date("m", $tm)/3);
for($i=1; $i<=4; $i++)
{
$checkd = mktime(0,0,0,date('m')-$i,date('d'),date('Y'));
if(ceil(date("m", $checkd)/3) != "$quarter")
{
$meani = date("m", $checkd);
for($a=1; $a<=31; $a++)
{
$forman = mktime(0,0,0,$meani,$a,date('Y'));
if(ceil(date("m", $forman)/3) == "$quarter")
{
$first_day = date('d', $forman);
break;
}
}
break;
}
}
$current_quarter_dayone = date('Y-m-d H:i:s', mktime(0,0,0,$meani,$first_day,date('Y')));
return $current_quarter_dayone;
}
?>
To get the current quarterly start date.
$quarter_start= quarter();
**************************************
2010-09-01 00:00:00
To find the start of a particular quarter based on a date, pass the month and day.
$quarter_start = quarter('08','30');
$quarter_end = date("Y-m-d H:i:s", strtotime($barter)-86400);
Results
**********************************
2010-06-01 00:00:00
2010-08-31 00:00:00
Here is a simple function that gets all the dates between 2 given dates and returns an array (including the dates specified):
<?php
function dates_inbetween($date1, $date2){
$day = 60*60*24;
$date1 = strtotime($date1);
$date2 = strtotime($date2);
$days_diff = round(($date2 - $date1)/$day); // Unix time difference devided by 1 day to get total days in between
$dates_array = array();
$dates_array[] = date('Y-m-d',$date1);
for($x = 1; $x < $days_diff; $x++){
$dates_array[] = date('Y-m-d',($date1+($day*$x)));
}
$dates_array[] = date('Y-m-d',$date2);
return $dates_array;
}
// Usage
$dates_array = dates_inbetween('2001-12-28', '2002-01-01');
?>
Looking to output number of days left in the current year (and check if its a leap year - here it is)
<?php
$today = getdate(); // Get the current day in an array
$yday = ($today['yday']); // Extract just the number of days since January 1st current year
$leap = date('L'); // check if its a leap year
$tdl = $leap + 365; // 365 days in an average year plus 1 day if its a leap year
$dliy = $tdl - $yday; //Today number of days in the current year minus number of days since January 1st current year
// Build the output using the above variables
echo "As of today " . date('l F d, Y, ') . "We currently have " . $dliy . " days left in the year.";
?>
If you are sick of writing lots of code to format dates correctly, then I hope you find my code useful. It can def. use some work, I plan to improve it, but it passed a boring night and gave good results. enjoy! God bless!
<?php
function datefmt($date, $inFormat, $outFormat) {
/* A function to take a date in ($date) in specified inbound format (eg mm/dd/yy for 12/08/10) and
* return date in $outFormat (eg yyyymmdd for 20101208)
* datefmt (
* string $date - String containing the literal date that will be modified
* string $inFormat - String containing the format $date is in (eg. mm-dd-yyyy)
* string $outFormat - String containing the desired date output, format the same as date()
* )
*
*
* ToDo:
* - Add some error checking and the sort?
*/
$order = array('mon' => NULL, 'day' => NULL, 'year' => NULL);
for ($i=0; $i<strlen($inFormat);$i++) {
switch ($inFormat[$i]) {
case "m":
$order['mon'] .= substr($date, $i, 1);
break;
case "d":
$order['day'] .= substr($date, $i, 1);
break;
case "y":
$order['year'] .= substr($date, $i, 1);
break;
}
}
$unixtime = mktime(0, 0, 0, $order['mon'], $order['day'], $order['year']);
$outDate = date($outFormat, $unixtime);
if ($outDate == False) {
return False;
} else {
return $outDate;
}
}
?>
If you want to use HTML5's <date> tag, the following code will generate the machine-readable value for the 'datetime' attribute:
<?php
/**
* formats the date passed into format required by 'datetime' attribute of <date> tag
* if no intDate supplied, uses current date.
* @param intDate integer optional
* @return string
**/
function getDateTimeValue( $intDate = null ) {
$strFormat = 'Y-m-d\TH:i:s.uP';
$strDate = $intDate ? date( $strFormat, $intDate ) : date( $strFormat ) ;
return $strDate;
}
echo getDateTimeValue();
?>
If you want to get yesterday's date, then a single line of code is enough.
<?php
$yesterday = date("Ymd", strtotime("-1 day"));
?>
Function to return whether or not a given date falls within British Summer Time:
<?php
function is_bst($date) {
$Year = date("Y", $date);
$MarLast = $Year."-03-31";
$OctLast = $Year."-10-31";
//Find the last Sunday in March
if (date("w", strtotime($MarLast)) == 0) //Sunday
{
$LastMarSun = strtotime($MarLast);
} else {
$LastMarSun = strtotime($MarLast." last sunday");
}
//Find the last Sunday in October
if (date("w", strtotime($OctLast)) == 0) //Sunday
{
$LastOctSun = strtotime($OctLast);
} else {
$LastOctSun = strtotime($OctLast." last sunday");
}
$BSTStart = strtotime(date("Y-m-d", $LastMarSun)." 01:00:00");
$BSTEnd = strtotime(date("Y-m-d", $LastOctSun)." 01:00:00");
return (($date >= $BSTStart) && ($date <= $BSTEnd));
}
?>
Just small addition for indonesian date time..
<?php
function DateIndo($str) {
if ($str =="") {
// null
return false;
}
else {
setlocale (LC_TIME, 'id_ID');
$date = strftime( "%d-%m-%Y %H:%I:%S", strtotime($str));
return $date;
}
}
//this also works...
$date = date('Y-m-d H:i:s');
echo DateIndo($date);
?>
if you wish to output a local time, instead of using date_default_timezone_get() and date_default_timezone_set() to manipulate your current timezone, simply create a new DateTime object:
<?php
$timezone = new DateTimeZone( "Europe/London" );
$date = new DateTime();
$date->setTimezone( $timezone );
echo $date->format( 'H:i:s A / D, M jS, Y' );
?>
-> 22:59:34 PM / Sun, Jan 24th, 2010
Irrespective of current server location, this will output the local time in London, Europe.
No need to reset the server timezone back to the previous setting.
Not sure why this got ignored the first time, but this is an even simpler way to check leap year:
<?php
function isLeapYear($year)
{ return ((($year%4==0) && ($year%100)) || $year%400==0) ? (true):(false); }
?>
convert an "excel" formatted date. Example:
<?php
$excel_date = 40179;
$normal_date = date("m/d/Y", strtotime("01/01/1900 + $excel_date days - 2 days"));
echo($normal_date);
?>
result: "01/01/2010"
MS-DOS related filesystems, along with ZIP files, store date and time in four bytes (time: 2 bytes, date: 2 bytes), as described in Wikipedia: http://en.wikipedia.org/wiki/File_Allocation_Table#Directory_table
As it took me some time to not-find any functions to convert unix to ms-dos timestamps, I decided to put these simple functions here, to save somebody else's time:
<?php
// $ts - standard UNIX timestamp, as returned by mktime()
function packTimeDate($ts){
// MS-DOS can store dates ranging from 1980-01-01 up to 2107-12-31
$year=date('Y', $ts);
if(($year<1980) || ($year>2107)) return "\x00\x00";
else return packTime($ts).packDate($ts);
}
/** From Wikipedia:
* 15-11 Hours (0-23)
* 10-5 Minutes (0-59)
* 4-0 Seconds/2 (0-29)
**/
function packTime($ts){
$sec=round((('1'.date('s', $ts))-100)/2);
$min=('1'.date('i', $ts))-100;
$hour=date('G', $ts);
$dosTime=($hour<<11)+($min<<5)+$sec;
$m[0]=$dosTime%256;
$m[1]=(($dosTime-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
/** From Wikipedia:
* 15-9 Year (0 = 1980, 127 = 2107)
* 8-5 Month (1 = January, 12 = December)
* 4-0 Day (1 - 31)
**/
function packDate($ts){
$year=date('Y', $ts)-1980;
$day=date('j', $ts);
$month=date('n', $ts);
$dosDate=($year<<9)+($month<<5)+$day;
$m[0]=$dosDate%256;
$m[1]=(($dosDate-$m[0])/256)%256;
return sprintf('%c%c', $m[0], $m[1]);
}
?>
As I didn't need to unpackTimeDate, I didn't bother to write reverse functions. Feel free to provide yours if You care.
Have fun with PHP!
To actually make use ot the "u" (microsecond) you need to use the DateTime object and not the date() function.
For example
<?php
$t = microtime(true);
$micro = sprintf("%06d",($t - floor($t)) * 1000000);
$d = new DateTime( date('Y-m-d H:i:s.'.$micro,$t) );
print $d->format("Y-m-d H:i:s.u");
?>
If u want to get weekday date -
30.08.2009 weekdays are 24-30
i want to get 5-th day of that week - 28.08.2009
<?PHP
function week_day($month, $year, $current_day, $week_day_number=1){
$loop_start = $current_day-(date('N', mktime(0, 0, 0, $month, $current_day, $year))-1);//lets start loop from first day of week
$loop_end = $current_day+(7-(date('N', mktime(0, 0, 0, $month, $current_day, $year))));//lets end loop to last day of week
for($i = $loop_start; $i<=$loop_end; $i++){
$day_of_the_week = date('N', mktime(0, 0, 0, $month, $i, $year));//current day number 1-7 of week
$loop_date = date('d', mktime(0, 0, 0, $month, $i, $year));//current day in calendar
if($day_of_the_week == $week_day_number){//if weekday number equals day number then lets return date
return $loop_date;
}
}
}
echo week_day(8, 2009, 30, 1);//returns (24).08.2009
echo '<br>';
echo week_day(8, 2009, 30, 5);//returns (28).08.2009
?>
Easy way to numeric representation of a quarter from passed as parametr date.
<?php
/**
* quarterByDate()
*
* Return numeric representation of a quarter from passed free-form date.
*
* @param mixed $date
* @return integer
*/
function quarterByDate($date)
{
return (int)floor(date('m', strtotime($date)) / 3.1) + 1;
}
?>
Example:
<?php
$quarter = quarterByDate(date('Y-m-d')); // current quarter. For 2009-08-29 will be "3"
$quarter = quarterByDate('2009-12'); // will be "4"
$quarter = quarterByDate('March'); // will be "1"
?>
I hope it will be useful.
Best regards,
S_P_E_C
This function behaves like date, but allows you to output the date in a given time zone locale.
<?php
function date_at_timezone($format, $locale, $timestamp=null){
if(is_null($timestamp)) $timestamp = time();
//Prepare to calculate the time zone offset
$current = time();
//Switch to new time zone locale
$tz = date_default_timezone_get();
date_default_timezone_set($locale);
//Calculate the offset
$offset = time() - $current;
//Get the date in the new locale
$output = date($format, $timestamp - $offset);
//Restore the previous time zone
date_default_timezone_set($tz);
return $output;
}
//Examples
$t = time();
print date("g:i A T", $t); //4:16 PM PDT
print date_at_timezone("g:i A T", "America/New_York", $t); //7:16 PM EDT
print date_at_timezone("g:i A T", "Pacific/Samoa", $t); //12:16 PM SST
print date("g:i A T", $t); //4:16 PM PDT
?>
Get names of days:
<?php
$tz = date_default_timezone_get();
date_default_timezone_set('UTC');
for($i=0; $i<7; $i++)
echo date('D', mktime(12, 0, 0, 1, $i+4, 1970)) . '<br />';
date_default_timezone_set($tz);
?>
Change 'D' to 'l' (lowercase 'L') for full names. Change $i+4 to $i+5 if you want Monday to be the first day of the week.
I couldn't find a function to do this properly. All functions I could find would use the current month as an argument.
Anyway, this function will find the occurence of a particular weekday in a particular month. For instance, the second wednesday in june 2009 would be called by:
<?php
echo findFirstDayofWeek(6,2009, "Wednesday", 2);
?>
Where 6 is "June", 2009 is the year, Wednesday is the weekday we want and 2 is the 2nd occurence.
<?php
function findFirstDayOfWeek($month, $year, $day, $offset){ // supply the month, year, day and offset
$FirstDay = mktime(0, 0, 0, $month, 1, $year); // Get the first day of the month in question
$DayName = date("l", $FirstDay); //set the name of the first day for the while loop
$CurrentStamp = $FirstDay; // set a disposable variable for use in the while loop
$Results = 0; //set the number of results (for use with the offset argument)
While($Results != $offset){ //while the number of results does not equal the offset we are looking for
$CurrentStamp = $CurrentStamp + 86400; // add a day
if(date("l", $CurrentStamp) == $day){ // if the name of the weekday we are currently looping at is the same name as the argument supplied, set the date variable to that weekday and increment the results variable by 1
$Date = date("Y-m-d", $CurrentStamp);
$Results++;
}
}
if(date("n", $CurrentStamp) != $month){ // this line checks whether or not the date that the while loop has found is in the same month we are asking form otherwise, there must be no "3rd friday in august"
return "No weekday at this offset";
} else {
return $Date; //send back the date
}
}
echo findFirstDayofWeek(9,2009, "Friday", 5); // returns a formatted date for the first instance of a certain day in the argumental month
?>
Haven't really tested it performance-wise vs. other methods, but I thought I'd post this anyways...
Here's a nifty way to exploit date()'s built-in ordinal suffix calculator to append the proper ordinal suffix to an arbitrary number:
<?php
function addOrdinal($num=0){
return $num.(((strlen($num)>1)&&(substr($num,-2,1)=='1'))?
'th' : date("S",mktime(0,0,0,0,substr($num,-1),0)));
} // end function addOrdinal
?>
In order to determine if a year is a leap year an earlier poster suggested simply checking to see if the year is a multiple of four:
<?php
function is_leapyear_broken($year = 2004) {
return ($year%4)==0;
}
?>
While this will work for the majority of years it will not work on years that are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this small anomaly in leap years:
<?php
function is_leapyear_working($year = 2004) {
if((($year%4==0) && ($year%100!=0)) || $year%400==0) {
return true;
}
return false;
}
?>
While is_leapyear_working will not return true for the few non-leap years divisible by four I couldn't tell you if this is more or less efficient than using php's date() as an even earlier poster suggested:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
(Referring to the leap year posts)
Not every year that is divisible by 4 is a leap year. There are other conditions. Here's the complete list:
1. Every year that is evenly divisible by four is a leap year;
2. of those years, if it can be evenly divided by 100, it is NOT a leap year, unless
3. the year is evenly divisible by 400. Then it is a leap year.
<?php
function is_leapyear($year) {
if ( ($year%4) != 0 )
{ return false; }
if ( ($year%100)==0 )
{
if ( ($year%400) == 0 )
{ return true; }
else
{ return false; }
}
else
{ return true; }
}
?>
An earlier user posted a script to detect whether or not a given year is a leap year:
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
You're thinking too hard! Just check to see if the year is a multiple of four:
<?php
function is_leapyear($year = 2004) {
return ($year%4)==0;
}
?>
or better yet, just use that single line in your code.
Slightly modified earlier written function for formatting date in russian.
<?php
/*
these are the russian additional format characters
д: full textual representation of the day of the week
Д: full textual representation of the day of the week (first character is uppercase),
к: short textual representation of the day of the week,
К: short textual representation of the day of the week (first character is uppercase),
м: full textual representation of a month
М: full textual representation of a month (first character is uppercase),
л: short textual representation of a month
Л: short textual representation of a month (first character is uppercase),
*/
function date_ru($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['д'] = array(-1 => 'w', 'воскресенье','понедельник', 'вторник', 'среда', 'четверг', 'пятница', 'суббота');
$q['Д'] = array(-1 => 'w', 'Воскресенье','Понедельник', 'Вторник', 'Среда', 'Четверг', 'Пятница', 'Суббота');
$q['к'] = array(-1 => 'w', 'вс','пн', 'вт', 'ср', 'чт', 'пт', 'сб');
$q['К'] = array(-1 => 'w', 'Вс','Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб');
$q['м'] = array(-1 => 'n', '', 'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря');
$q['М'] = array(-1 => 'n', '', 'Января', 'Февраля', 'Март', 'Апреля', 'Май', 'Июня', 'Июля', 'Август', 'Сентября', 'Октября', 'Ноября', 'Декабря');
$q['л'] = array(-1 => 'n', '', 'янв', 'фев', 'мар', 'апр', 'май', 'июн', 'июл', 'авг', 'сен', 'окт', 'ноя', 'дек');
$q['Л'] = array(-1 => 'n', '', 'Янв', 'Фев', 'Мар', 'Апр', 'Май', 'Июн', 'Июл', 'Авг', 'Сен', 'Окт', 'Ноя', 'Дек');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'д', $i) !== FALSE) || (strpos($formatum, 'Д', $i) !== FALSE) ||
(strpos($formatum, 'к', $i) !== FALSE) || (strpos($formatum, 'К', $i) !== FALSE) ||
(strpos($formatum, 'м', $i) !== FALSE) || (strpos($formatum, 'М', $i) !== FALSE) ||
(strpos($formatum, 'л', $i) !== FALSE) || (strpos($formatum, 'Л', $i) !== FALSE)) {
$ch['д']=strpos($formatum, 'д', $i);
$ch['Д']=strpos($formatum, 'Д', $i);
$ch['к']=strpos($formatum, 'к', $i);
$ch['К']=strpos($formatum, 'К', $i);
$ch['м']=strpos($formatum, 'м', $i);
$ch['М']=strpos($formatum, 'М', $i);
$ch['л']=strpos($formatum, 'л', $i);
$ch['Л']=strpos($formatum, 'Л', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
echo 'Сегодня '.date_ru('Д, d л Y');
?>
A quick note about DATE_RSS and daylight savings...
DATE_RSS will return the timezone that your server is in as part of the format, which is normally correct when formatting a date for an RSS feed (RFC-822).
However, if you're in the UK and it's the summer, your timezone is set as "BST". This is not actually a valid RFC-822 timezone, thereby rendering DATE_RSS a bit useless for six months of the year.
The valid extension would actually be GMT. You should therefore adjust the time back by 1 hour and substitute the BST for GMT.
<?php
//for Indonesian get return today
echo returnDate(date("N"), "day") . ", " . date("j") . " " . returnDate(date("n"), "month") . " " . date("Y");
function returnDate($num, $tipe){
$str;
switch($tipe){
case "month":
$month_name = array("", "Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember");
$str = $month_name[floor($num)];
break;
case "day":
$day_name = array("", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu", "Minggu");
$str = $day_name[floor($num)];
break;
}
return $str;
}
?>
// showing how to detect a leap year
<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return $is_leap;
}
?>
<?php
$answer = is_leapyear(2000);
if($answer) {
echo "2000 is a leap year<BR>";
} else {
echo "2000 is not a leap year.<BR>";
}
/* Use default for the parameter */
$yy="2003";
$answer = is_leapyear(2003);
if($answer) {
echo "$yy is a leap year.<BR>";
} else {
echo "$yy is not a leap year.<BR>";
}
?>
Function to obtain last week timestamps.
<?php
function LastWeek(){
$week = date('W');
$year = date('Y');
$lastweek=$week-1;
if ($lastweek==0){
$week = 52;
$year--;
}
$lastweek=sprintf("%02d", $lastweek);
for ($i=1;$i<=7;$i++){
$arrdays[] = strtotime("$year". "W$lastweek"."$i");
}
return $arrdays;
}
$days = LastWeek();
echo "last week between " . date('Ymd000000',$days[0]) . " and " . date('Ymd235959', $days[6]) . "\n";
?>
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful for someone. Hope you don't mind changing your code tcasparr at gmail dot com.
<?php
/*******************************************************
* Simple function to take in a date format and return array of associated
* formats for each date element
*
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*
* This function is needed for PHP < 5.3.0
********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
$aDataRet = array();
$aPieces = split('[:/.\ \-]', $stFormat);
$aDatePart = split('[:/.\ \-]', $stData);
foreach($aPieces as $key=>$chPiece)
{
switch ($chPiece)
{
case 'd':
case 'j':
$aDataRet['day'] = $aDatePart[$key];
break;
case 'F':
case 'M':
case 'm':
case 'n':
$aDataRet['month'] = $aDatePart[$key];
break;
case 'o':
case 'Y':
case 'y':
$aDataRet['year'] = $aDatePart[$key];
break;
case 'g':
case 'G':
case 'h':
case 'H':
$aDataRet['hour'] = $aDatePart[$key];
break;
case 'i':
$aDataRet['minute'] = $aDatePart[$key];
break;
case 's':
$aDataRet['second'] = $aDatePart[$key];
break;
}
}
return $aDataRet;
}
?>
Also, if you need to change the format of dates:
<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
// When PHP 5.3.0 becomes available to me
//$date = date_parse_from_format($stFormatFrom,$stDate);
//For now I use the function above
$date = dateParseFromFormat($stFormatFrom,$stDate);
return date($stFormatTo,mktime($date['hour'],
$date['minute'],
$date['second'],
$date['month'],
$date['day'],
$date['year']));
}
?>
Heads up: The date('W') week number of the year is computed based on Monday, and may not be exactly what you expect. What is "Week 01" of year 2008? This is different from the date('z') day number of the year which is computed from January 1 == day zero.
<?php // RAY_date_W.php
echo "<br/>" . date('W', strtotime("December 28, 2008")); // 52
echo "<br/>" . date('W', strtotime("December 29, 2008")); // 01
echo "<br/>" . date('W', strtotime("January 2, 2009")); // 01
if (!date('z', strtotime("January 1"))) echo "<br/>FALSE"; // FALSE
?>
<?php
/**
* Simple function to take in a date format and return array of associated formats for each date element
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
* [year] => Y
* [month] => m
* [day] => d
* [hour] => g
* [minute] => i
* [second] => s
* )
*/
function extract_date_format($strFormat)
{
$format_array = array();
$pieces = split('[:/.\ \-]', $strFormat);
foreach($pieces as $piece)
{
switch ($piece)
{
case 'd':
case 'j':
$format_array['day'] = $piece;
break;
case 'F':
case 'M':
case 'm':
case 'n':
$format_array['month'] = $piece;
break;
case 'o':
case 'Y':
case 'y':
$format_array['year'] = $piece;
break;
case 'g':
case 'G':
case 'h':
case 'H':
$format_array['hour'] = $piece;
break;
case 'i':
$format_array['minute'] = $piece;
break;
case 's':
$format_array['second'] = $piece;
break;
}
}
return $format_array;
}
?>
It seems to me that you can reliably get the week range of a certain numeric week like so:
<?php
// 2009 is the year
// W01 is week number 1
// 1 is the day number (Monday), 7 would be Sunday
strtotime("2009W011");
// Example 1 (These return the days for Week 1 or 2009
Mon_timestamp = strtotime("2009W011");
Tue_timestamp = strtotime("2009W012");
Wed_timestamp = strtotime("2009W013");
Thu_timestamp = strtotime("2009W014");
Fri_timestamp = strtotime("2009W015");
Sat_timestamp = strtotime("2009W016");
Sun_timestamp = strtotime("2009W017");
// Example 2 (more dynamic)
// set the 7 dates of the week
for($i=1; $i<=7; $i++) {
$dates[$i] = strtotime($year.'W'.$week.$i);
}
?>
Just remember you must pad the week number if it's under 10. 1 won't work, it should be 01.
In a refreshing change, this code snippet is *not* about calculating date differences or anything like that.
<background-story>
I've always preferred date() over strftime() because of what each offers. For example, date has an st/nd/rd for the day number (S) while strftime does not. It also has an unpadded day number (j) that strftime doesn't (%e pads it with a space).
On the other hand, each character in the format string for date() is translated unless you prepend a backslash...
Recently I've wanted to create links with date information in it. Like with "January 21st 2009" each part would be a link (January => /2009/01, 21st => /2009/01/21, 2009 => /2009). date() makes this difficult because the HTML markup gets the treatment as well as the Y/m/d characters. Escaping all of those is ugly, not to mention annoying.
</background-story>
Here's my combination of date's placeholders and strftime's % markers. It's the best solution I could think of (at 5am mind you) but I'm open to suggestions.
Lots of comments because the code is rather tricky.
<?php
/**
* Combines placeholders from date() with the % marker from strftime()
*
* Like strftime, use %% for a literal %.
*
* @see date, strftime
* @param string $format The format of the outputted date string
* @param int $timestamp An integer Unix timestamp that defaults to the current local time
* @return A formatted date string
*/
function strfdate($format, $timestamp = null) {
// look for tokens
if (preg_match_all('/(?<!%)(%%)*%(.)/', $format, $matches)) {
// passing false or null as the timestamp doesn't work so we
// have to generate the default ourselves
if ($timestamp === null) $timestamp = time();
// run each token through date - all at once
// combines them into a "a!b!c!d" list, runs it through date,
// and splits it apart again
$parts = explode("!", date(implode("!", $matches[2]), $timestamp));
// (! should never show up in date() output so this works)
// a second function is used sequentially:
// the Xth time this function is called it will replace the Xth token
// with the corresponding element in $parts (which is passed through as $a)
//
// @param array $a Meant to be $parts as defined above
// @return $a[X] where X is how many times this function has been called
$replace = create_function('$a', 'static $i = 0; return $a[$i++];');
// find each token and get the replacement data from the $replace function
// note how the text being replaced isn't used anywhere: we already know
// what it is as it was used to create the $parts array
$result = preg_replace('/(%*)%./e', '"$1" . $replace($parts)', $format);
// finally "unescape" any %s
$result = str_replace("%%", "%", $result);
return $result;
}
return $format;
}
?>
Just in case anyone else is looking for an easy-to-find equivalent for W3C Datetime or date("c") in a previous version of php, here's one I did. Hope it helps someone.
<?php
function w3cDate($time=NULL)
{
if (empty($time))
$time = time();
$offset = date("O",$time);
return date("Y-m-d\TH:i:s",$time).substr($offset,0,3).":".substr($offset,-2);
}
?>
Examples:
echo w3cDate(); //2008-11-18T12:15:18-07:00
echo w3cDate(mktime(2,3,4,5,6,2007)); //2007-05-06T02:03:04-06:00
<?php
/*
Find out start and end date of current week.
I am assuming that week starts at sunday and ends at saturday.
so a typical week will look like this: sun,mon,tue,wed,thu,fri,sat
if you find any bug/error, please email me.
*/
//sunday = start of week
$sat = 6; //saturday = end of week
$current_day=date('w');
$days_remaining_until_sat = $sat - $current_day;
$ts_start = strtotime("-$current_day days");
$ts_end = strtotime("+$days_remaining_until_sat days");
echo date('m-d-Y',$ts_start); //start date
echo '<br>';
echo date('m-d-Y',$ts_end); //end date
/*
OUTPUT (m-d-y):
11-09-2008
11-15-2008
*/
?>
date(DATE_RFC822) and date(DATE_RFC2822) both work. note that RFC 822 is obsoleted by RFC 2822. The main difference is the year being 08 in RFC 822 and is 2008 in RFC 2822.
To use date(DATE_RFC2822), a short form is date('r').
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
a date function supporting the milliseconds format character
<?php
function udate($format, $utimestamp = null)
{
if (is_null($utimestamp))
$utimestamp = microtime(true);
$timestamp = floor($utimestamp);
$milliseconds = round(($utimestamp - $timestamp) * 1000000);
return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}
echo udate('H:i:s.u'); // 19:40:56.78128
echo udate('H:i:s.u', 654532123.04546); // 16:28:43.45460
?>
here is the simpliest way to get the start and end date of the week;
<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));
$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>
the format is for the string in strtotime is;
2008W200
this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....
so 2008W200 stands for the sunday of the 20th week of 2008.
This will only work in php 5 or better
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.
So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00
I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.
<?php
/**
* Finds the difference in days between two calendar dates.
*
* @param Date $startDate
* @param Date $endDate
* @return Int
*/
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
?>
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?php echo phpversion(); ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?php
$format='F j, Y';
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
?>
Trying: <?php echo $datep; ?> = <?php echo date($format, strtotime($datep)); ?><br>
<?php
}
?></div>
<div style='float:left;'>
<h3>NEW DateTime Class (v 5.2+)</h3><?php
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
$date = new DateTime($datep);
?>
Trying: <?php echo $datep; ?> = <?php echo $date->format($format); ?><br>
<?php
}
?></div>
Quick function for returning the names of the next 7 days of the week starting with today.
Returns an array that can be formatted to your liking.
<?php
/**
* Returns array of next 7 days starting with today
*
*/
function next_7_days() {
// create array of day names. You can change these to whatever you want
$days = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
$today = date('N');
for ($i=1;$i<$today;$i++) {
// take the first element off the array
$shift = array_shift($days);
// ... and add it to the end of the array
array_push($days,$shift);
}
// returns the sorted array
return $days;
}
?>
It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast. He/she uses $w as a key for the $weeks array. "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended. For May, 2008, I get 5 weeks as expected...
Array
(
[1] => Array
(
[4] => 1
[5] => 2
[6] => 3
)
[2] => Array
(
[0] => 4
[1] => 5
------------OMITTED-----------------
[4] => 22
[5] => 23
[6] => 24
)
[5] => Array
(
[0] => 25
[1] => 26
[2] => 27
[3] => 28
[4] => 29
[5] => 30
[6] => 31
)
)
I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).
I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).
<?php
$m = date('m');
$Y = date('Y');
// for() {months loop omitted
$var_date = mktime(0, 0, 0, $m, 1, $Y);
$month_name = date('F', $var_date);
$months[$month_name]['DAYS'] = date('t', $var_date);
$months[$month_name]['FIRST_DAY'] = date('w', $var_date);
//}
foreach($months as $month => $key) {
$weeks = array();
for($i = 1, $j = $key['FIRST_DAY'], $w = 1;$i <= $key['DAYS'];$i++) {
$weeks[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
$months[$month]['WEEKS'] = $weeks;
}
?>
Enjoy!
Weeks and days for any month/year combo:
<?php
$m = 2; // February
$Y = 2008;
// constants used here for legibility, use $vars for dynamicon...
define('MONTH_DAYS',date('t', strtotime(date($m . '/01/' . $Y))));
// w:0->6 = Sun->Sat
define('MONTH_FIRST_DAY',date('w', strtotime(date($m . '/01/' . $Y))));
for($i = 1, $j = MONTH_FIRST_DAY, $w = 1;$i <= MONTH_DAYS;$i++) {
$week[$w][$j] = $i;
$j++;
if($j == 7) {
$j = 0;
$w++;
}
}
?>
print_r($week):
-----------------------
Array
(
[1] => Array
(
[5] => 1
[6] => 2
)
[2] => Array
(
[0] => 3
[1] => 4
[2] => 5
[3] => 6
[4] => 7
[5] => 8
[6] => 9
)
[3] => Array
(
[0] => 10
[1] => 11
[2] => 12
[3] => 13
[4] => 14
[5] => 15
[6] => 16
)
[4] => Array
(
[0] => 17
[1] => 18
[2] => 19
[3] => 20
[4] => 21
[5] => 22
[6] => 23
)
[5] => Array
(
[0] => 24
[1] => 25
[2] => 26
[3] => 27
[4] => 28
[5] => 29
)
)
[EDIT BY danbrown AT php DOT net: In a note dated 03-JUL-08, (dmagick AT gmail DOT com) offered the following amendment to this note.]
[I've updated this] code as it doesn't take into account when a month finishes on a Saturday (eg May 2008).
<?php
$start_date = mktime(0, 0, 0,$start_month, 1, $start_year);
$days_in_month = date('t', $start_date);
$month_first_day = date('w', $start_date);
$j = $month_first_day;
$num_weeks = 1;
for($i = 1; $i <= $days_in_month; $i++) {
$j++;
if($j == 7) {
$j = 0;
$num_weeks++;
}
}
// if the last day of the month happens to be a Saturday,
// take one off the number of weeks
// because it was being added inside the for loop.
if ($j == 0) {
$num_weeks--;
}
?>
I wrote the following function to show a series of drop down boxes to select the date. When provided with a timestamp, that date is selected by default, when none is provided, the current date is selected.
<?php
function chooseDate($timestamp = ""){
if($timestamp == ""){
$timestamp = time();
}
$months = array(null, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
unset($months[0]);
print_r($months);
$out = '<select name="month">';
foreach($months as $key => $month){
if($month == date('M', $timestamp)){
$out .= '<option value="'.$key.'" selected="selected">'.$month.'</option>';
}else{
$out .= '<option value="'.$key.'">'.$month.'</option>';
}
}
$out .= '</select><select name="days">';
for($i = 1; $i <= 32; $i++){
if($i == date('j', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select><select name='year'>";
for($i = date('Y'); $i >= 1970; $i--){
if($i == date('Y', $timestamp)){
$out .= '<option value="'.$i.'" selected="selected">'.$i.'</option>';
}else{
$out .= '<option value="'.$i.'">'.$i.'</option>';
}
}
$out .= "</select>";
return $out;
}
?>
Usage is simple:
<?php
echo chooseDate(); // Will select current date
echo chooseDate(1149566400); // Will select June 6th, 2006
?>
to get the week of the month simply use:
ceil( date("j") / 7 );
I made a small code to get the last working day of the month:
<?php
$times = strtotime(date("Y")."-".date("m")."-".date("t"));
for ($lastworkingday=0;$lastworkingday==0;$times-=86400)
if (date("w",$times)!=0 && date("w",$times)!=6) $lastworkingday = date("j",$times);
print $lastworkingday;
?>
Found this helpful when converting unix dates for use with the ical file format.
<?php
// Converts a unix timestamp to iCal format (UTC) - if no timezone is
// specified then it presumes the uStamp is already in UTC format.
// tzone must be in decimal such as 1hr 45mins would be 1.75, behind
// times should be represented as negative decimals 10hours behind
// would be -10
function unixToiCal($uStamp = 0, $tzone = 0.0) {
$uStampUTC = $uStamp + ($tzone * 3600);
$stamp = date("Ymd\THis\Z", $uStampUTC);
return $stamp;
}
?>
<?php
/**
* Checks wether a date is between an interval
*
* Usage:
*
* // check if today is older than 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/31'));
* // check if today is younger than 2008/12/31
* var_dump(currentDayIsInInterval(null,'2008/12/31'));
* // check if today is between 2008/12/01 and 2008/12/31
* var_dump(currentDayIsInInterval('2008/12/01','2008/12/31'));
*
* Will trigger errors if date is in wrong format, notices if $begin > $end
*
* @param string $begin Date string as YYYY/mm/dd
* @param string $end Date string as YYYY/mm/dd
* @return bool
*/
function currentDayIsInInterval($begin = '',$end = '')
{
$preg_exp = '"[0-9][0-9][0-9][0-9]/[0-9][0-9]/[0-9][0-9]"';
$preg_error = 'Wrong parameter passed to function '.__FUNCTION__.' : Invalide date
format. Please use YYYY/mm/dd.';
$interval_error = 'First parameter in '.__FUNCTION__.' should be smaller than
second.';
if(empty($begin))
{
$begin = 0;
}
else
{
if(preg_match($preg_exp,$begin))
{
$begin = (int)str_replace('/','',$begin);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if(empty($end))
{
$end = 99999999;
}
else
{
if(preg_match($preg_exp,$end))
{
$end = (int)str_replace('/','',$end);
}
else
{
trigger_error($preg_error,E_USER_ERROR);
}
}
if($end < $begin)
{
trigger_error($interval_error,E_USER_WARNING);
}
$time = time();
$now = (int)(date('Y',$time).date('m',$time).date('j',$time));
if($now > $end or $now < $begin)
{
return false;
}
return true;
}
?>
The function below extracts any date time value basead in the string format.
Returns an associative array with day,month,year,hour,min and seg separated.
<?php
function ExtractDateTimeByFormat($strDateTime, $strFormat="dmYHis")
{
//extract the format
$i = 0;
$aFieldOrder = array();
$nFields = 0;
$strExtraction = "";
while(isset($strFormat[$i]))
{
$strField = $strFormat[$i];
switch ( strtolower($strField) )
{
case "D";
case "d";
$aFieldOrder[$nFields] = "d";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "M";
case "m";
$aFieldOrder[$nFields] = "m";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "y";
case "Y";
$aFieldOrder[$nFields] = "y";
$nFields++;
$strExtraction .= "%4d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "h";
case "H";
$aFieldOrder[$nFields] = "h";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "i";
$aFieldOrder[$nFields] = "i";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
case "S";
case "s";
$aFieldOrder[$nFields] = "s";
$nFields++;
$strExtraction .= "%d";
if(isset($strFormat[$i+1]))
{
$strExtraction .= "%*1c";
}
break;
}
$i++;
}
$aValues = array();
$aValues = sscanf($strDateTime,$strExtraction);
return array_combine($aFieldOrder,$aValues);
}
?>
For output formatting of a SAMP based seminar announcement system, i had to fetch the date of every friday of a given month in a given year. Here's what i did:
<?php
$givenYear = $_GET["givenYear"]; # assume "2006"
$givenMonth = $_GET["givenMonth"]; # assume "12"
if ($givenMonth != '12') {
$nextGivenMonth = "1";
$nextGivenYear = $givenYear + 1;}
else {
$nextGivenMonth = $givenMonth + 1;
$nextGivenYear = $givenYear;}
# Get the first weekday of the month
$firstDayOfMonth = date("d", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
$firstWeekDayOfMonth = date("l", mktime(0, 0, 0, $givenMonth, 1, $givenYear));
# Count days to first Friday
switch ($firstWeekDayOfMonth) {
case 'Monday': $numOfDaysToFirstFriday = "4"; break;
case 'Tuesday': $numOfDaysToFirstFriday = "3"; break;
case 'Wednesday': $numOfDaysToFirstFriday = "2"; break;
case 'Thursday': $numOfDaysToFirstFriday = "1"; break;
case 'Friday': $numOfDaysToFirstFriday = "0"; break;
case 'Saturday': $numOfDaysToFirstFriday = "6"; break;
case 'Sunday': $numOfDaysToFirstFriday = "5"; break;}
# Get first Friday's date
$numOfDaysToFirstFriday = 1 + $numOfDaysToFirstFriday;
$firstFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$firstFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
# Get the last weekday of the month
$lastDayOfMonth = date("d", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
$lastWeekDayOfMonth = date("l", strtotime("-1 day", strtotime(date("$nextGivenYear-$nextGivenMonth-01"))));
# Count days to last Friday
switch ($lastWeekDayOfMonth) {
case 'Monday': $numOfDaysToLastFriday = "3"; break;
case 'Tuesday': $numOfDaysToLastFriday = "4"; break;
case 'Wednesday': $numOfDaysToLastFriday = "5"; break;
case 'Thursday': $numOfDaysToLastFriday = "6"; break;
case 'Friday': $numOfDaysToLastFriday = "0"; break;
case 'Saturday': $numOfDaysToLastFriday = "1"; break;
case 'Sunday': $numOfDaysToLastFriday = "2"; break;}
# Get last Friday's date
$numOfDaysToLastFriday = $lastDayOfMonth - $numOfDaysToLastFriday;
$lastFridayOfMonthDate = date("d.m.Y", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
$lastFridayOfMonthDay = date("d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));
$divisor = $lastFridayOfMonthDay - $firstFridayOfMonthDay;
$divisor = $divisor / 7;
global $divisor;
# Get the dates of all Fridays in the given Month (can be either 4 or 5)
if ($divisor=='3') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
else if ($divisor=='4') {
$firstFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToFirstFriday, $givenYear));
$secondFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 21, $givenYear));
$thirdFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 14, $givenYear));
$fourthFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $lastFridayOfMonthDay - 7, $givenYear));
$lastFridayOfMonth = date("Y/m/d", mktime(0, 0, 0, $givenMonth, $numOfDaysToLastFriday, $givenYear));}
?>
Comments, suggestions and bugfixes are welcome ;-))
I have written a little Date Class Library for PHP that supports timestamps for dates greater than 2038 and lesser than 1970.
This library can be used in both PHP4 and PHP5.
Check it out here:
http://xwisdomhtml.com/dateclass.html
## This will produce the first day of last month and the last day of last month
## 2008-01-01 2008-01-31
<?php
echo date("Y-m-01", strtotime("-1 month", strtotime(date("Y-m-d"))))." ".date("Y-m-d", strtotime("-1 day", strtotime(date("Y-m-01")))) ?>
date("W") returns the iso8601 week number, while date("Y") returns the _current_ year. This can lead to odd results. For example today (dec 31, 2007) it returns 1 for the week and of course 2007 for the year. This is not wrong in a strict sense because iso defines this week as the first of 2008 while we still have 2007.
So, if you don't have another way to safely retrieve the year according to the iso8061 week-date - strftime("%G") doesn't work on some systems -, you should be careful when working with date("W").
For most cases strftime("%W") should be a safe replacement.
[edit: Much easier is to use "o" (lower case O) instead of "Y"]
I wanted to get the number of weeks for particular year.
Example with date():
<?php
$weeks_in_year = date("W", strtotime("12/31/2007"));
?>
It works for years smaller than current year, but returns '01' when year was the same or bigger as current year.
Not sure if I missed something or maybe misused this function but I couldn't get it to work even with different date representations.
So the workaround was using different function.
Example with strftime():
<?php
$weeks_in_year = strftime("%W",strtotime("12/31/2007"));
?>
Now it works as a charm.
PHP v.4.4.7
[EDIT BY danbrown AT php DOT net: In a note dated 25-JAN-09, "Juan Paredes" offered the following information as an amendment.]
Complementing the information [in this note], if you want to calculate the number of weeks in a given year, according to the week definition by ISO 8601, the following should be enough:
date('W', mktime(0,0,0,12,28,$year) );
(the last week on a give year always contains 28-Dec)
This function is like date, but it "speaks" Hungarian (or an other language)
<?php
/*
these are the hungarian additional format characters
ö: full textual representation of the day of the week
Ö: full textual representation of the day of the week (first character is uppercase),
ő: short textual representation of the day of the week,
Ő: short textual representation of the day of the week (first character is uppercase),
ü: full textual representation of a month
Ü: full textual representation of a month (first character is uppercase),
ű: short textual representation of a month
Ű: short textual representation of a month (first character is uppercase),
*/
function date_hu($formatum, $timestamp=0) {
if (($timestamp <= -1) || !is_numeric($timestamp)) return '';
$q['ö'] = array(-1 => 'w', 'vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat');
$q['Ö'] = array(-1 => 'w', 'Vasárnap', 'Hétfő', 'Kedd', 'Szerda', 'Csütörtök', 'Péntek', 'Szombat');
$q['ő'] = array(-1 => 'w', 'va', 'hé', 'ke', 'sze', 'csü', 'pé', 'szo');
$q['Ő'] = array(-1 => 'w', 'Va', 'Hé', 'Ke', 'Sze', 'Csü', 'Pé', 'Szo');
$q['ü'] = array(-1 => 'n', '', 'január', 'február', 'március', 'április', 'május', 'június', 'július', 'augusztus', 'szeptember', 'október', 'november', 'december');
$q['Ü'] = array(-1 => 'n', '', 'Január', 'Február', 'Március', 'Április', 'Május', 'Június', 'Július', 'Augusztus', 'Szeptember', 'Október', 'November', 'December');
$q['ű'] = array(-1 => 'n', '', 'jan', 'febr', 'márc', 'ápr', 'máj', 'júni', 'júli', 'aug', 'szept', 'okt', 'nov', 'dec');
$q['Ű'] = array(-1 => 'n', '', 'Jan', 'Febr', 'Márc', 'Ápr', 'Máj', 'Júni', 'Júli', 'Aug', 'Szept', 'Okt', 'Nov', 'Dec');
if ($timestamp == 0)
$timestamp = time();
$temp = '';
$i = 0;
while ( (strpos($formatum, 'ö', $i) !== FALSE) || (strpos($formatum, 'Ö', $i) !== FALSE) ||
(strpos($formatum, 'ő', $i) !== FALSE) || (strpos($formatum, 'Ő', $i) !== FALSE) ||
(strpos($formatum, 'ü', $i) !== FALSE) || (strpos($formatum, 'Ü', $i) !== FALSE) ||
(strpos($formatum, 'ű', $i) !== FALSE) || (strpos($formatum, 'Ű', $i) !== FALSE)) {
$ch['ö']=strpos($formatum, 'ö', $i);
$ch['Ö']=strpos($formatum, 'Ö', $i);
$ch['ő']=strpos($formatum, 'ő', $i);
$ch['Ő']=strpos($formatum, 'Ő', $i);
$ch['ü']=strpos($formatum, 'ü', $i);
$ch['Ü']=strpos($formatum, 'Ü', $i);
$ch['ű']=strpos($formatum, 'ű', $i);
$ch['Ű']=strpos($formatum, 'Ű', $i);
foreach ($ch as $k=>$v)
if ($v === FALSE)
unset($ch[$k]);
$a = min($ch);
$temp .= date(substr($formatum, $i, $a-$i), $timestamp) . $q[$formatum[$a]][date($q[$formatum[$a]][-1], $timestamp)];
$i = $a+1;
}
$temp .= date(substr($formatum, $i), $timestamp);
return $temp;
}
echo date_hu('Y. ü j. (ö) G:i');
?>
For those of us who don't have 5.x installed (that puts a colon in the time zone)...
<?php
$timezone = date("O"); // get timezone
$timezone_end = substr($timezone, -2, 2); // get last two numbers
$timezone= substr($timezone, 0, -2); // get first half
echo $timezone = $timezone . ":" . $timezone_end; // add colon
?>
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'] );
?>
For people who used "z" format...
The real range of "z" key format is 0 to 365 (instead of 366) and "z" represent the number of spent days in the year.
See this examples :
<?php
define ("\n" , NL );
print '<pre>';
print '"z" format interpretation:' . NL . NL;
print 'On 0 timestamp: "' . date( 'z : Y-m-d' , 0 ) . '"' . NL;
//show: On 0 timestamp: "0 : 1970-01-01"
print 'On second unix day: "' . date( 'z : Y-m-d' , 3600*24 ) . '"' . NL;
//show: On second unix day: "1 : 1970-01-02"
print 'On the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31, 2000 ) ) . '"' . NL;
//show: On the last day of a leap year: "365 : 2000-12-31"
print 'On the day after the last day of a leap year: "' . date( 'z : Y-m-d' , mktime( 23, 59, 59, 12, 31+1, 2000 ) ) . '"' . NL;
//show: On the day after the last day of a leap year: "0 : 2001-01-01"
print '</pre>';
?>
i needed the day (eg. 27th) of the last Monday of a month
<?php
$d=cal_days_in_month(CAL_GREGORIAN,$m,$y); // days in month
if (date('l',mktime(0,0,0,$m,$d,$y))=='Monday'): $finalmonday=$d;
else: $finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,$d,$y))); // day(date) of last monday of month, eg 26
endif;
?>
this also works...
<?php
$finalmonday=date('d',strtotime('last Monday',mktime(0,0,0,$m,($d+1),$y)));
//the '$d+1' is to catch the last day IS a monday (eg. dec 2007)
?>
Hope it helps, BigJonMX
<?php
/**
* Get date in RFC3339
* For example used in XML/Atom
*
* @param integer $timestamp
* @return string date in RFC3339
* @author Boris Korobkov
* @see http://tools.ietf.org/html/rfc3339
*/
function date3339($timestamp=0) {
if (!$timestamp) {
$timestamp = time();
}
$date = date('Y-m-d\TH:i:s', $timestamp);
$matches = array();
if (preg_match('/^([\-+])(\d{2})(\d{2})$/', date('O', $timestamp), $matches)) {
$date .= $matches[1].$matches[2].':'.$matches[3];
} else {
$date .= 'Z';
}
return $date;
}
?>
Just a small addition to dmitriy. If the present date is in daylight saving time, and the date in the past is not, the result will not be a whole number by dividing by 86400. It will be something like 48.958333333. This is because the day in which it changes from normal to daylight saving time is one hour longer than normal (90000 secs) and the opposite is true when changing back (the day would be one hour shorter - 82800 secs).
If you want a whole number of days use the following instead:
<?php
$digest_date = "2007-01-01";
$date_diff = round( abs(strtotime(date('y-m-d'))-strtotime($digest_date)) / 86400, 0 );
?>
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");
?>
Note for wips week limits function:
I had to run it over 52 weeks of the year and it was very slow so I've modified to improve:
<?php
function week_limits($weekNumber, $year, $pattern)
{
$pattern = ($pattern) ? $pattern : "m/d";
$stday = 7 * $weekNumber - 7;
$stDayNumber = date("w", mktime(0,0,0,1, 1+$stday, $year));
$stUtime = mktime(0,0,0,1,1+$stday-$stDayNumber, $year);
$start_time = date($pattern, $stUtime);
$end_time = date($pattern, $stUtime+6*24*60*60);
return array($start_time, $end_time);
}//week_limits()
?>
I wanted to shift an sql date forward by a set time period.
This is how I achived it... well handy.
<?php
function sql_date_shift($date, $shift)
{
return date("Y-m-d H:i:s" , strtotime($shift, strtotime($date)));
}
// example usage
$date = "2006-12-31 21:00";
$shift "+6 hours"; // could be days, weeks... see function strtotime() for usage
echo sql_date_shift($date, $shift);
// will output: 2007-01-01 03:00:00
?>
Hope it is of use,
Ashley
if you are sending your data to a database, you can just send time() and then use strftime() to turn the time() string into readable time format.
check both time() and strftime() functions both offer more or less same functionality as date(). date() can also be used with time() strings to display time in the past.
more or less with something like:
date("j F, Y - g:ia", $data['date_quoted'])
where time() = $data['date_quoted'] and time() is the exact time date when the string is executed. if this is done towards a database, the time() stored is the actual server time upon script execution, no matter the time set in the individual computer, this will record server time, unless a gmt is set in newer versions of php (5 and up).
<?php
/**
* Converts a date string from one format to another (e.g. d/m/Y => Y-m-d, d.m.Y => Y/d/m, ...)
*
* @param string $date_format1
* @param string $date_format2
* @param string $date_str
* @return string
*/
function dates_interconv( $date_format1, $date_format2, $date_str )
{
$base_struc = split('[/.-]', $date_format1);
$date_str_parts = split('[/.-]', $date_str );
print_r( $base_struc ); echo "<br>";
print_r( $date_str_parts ); echo "<br>";
$date_elements = array();
$p_keys = array_keys( $base_struc );
foreach ( $p_keys as $p_key )
{
if ( !empty( $date_str_parts[$p_key] ))
{
$date_elements[$base_struc[$p_key]] = $date_str_parts[$p_key];
}
else
return false;
}
$dummy_ts = mktime( 0,0,0, $date_elements['m'],$date_elements['d'],$date_elements['Y']);
return date( $date_format2, $dummy_ts );
}
$df_src = 'd/m/Y';
$df_des = 'Y-m-d';
$iso_date = dates_interconv( $df_src, $df_des, '25/12/2005');
?>
output:
2005-12-25
If you want to use the date function to fix the RFC-822 format from an allready made RSS 2.0 feed you can do it like this..
Maybe getting an external feed from another asp or php file that you cannot change, but want to have the correct dateformat for anyway.
<?php
header('Content-type: application/rss+xml; charset=iso-8859-1');
$xmlfile = simplexml_load_file($_GET[feedURL]);
for ( $i = 0; $i < count($xmlfile->channel->item); $i++ )
$xmlfile->channel->item[$i]->pubDate = date("r",strtotime((string)($xmlfile->channel->item[$i]->pubDate)));
echo $xmlfile->asXML();
?>
Then simply link to your rss feed like this
filename.php?feedURL=http://www.example.com/rss.asp
filename.php?feedURL=http://www.example.com/rss.xml
filename.php?feedURL=http://www.example.com/rss.php
or what you want. Hope anyone can take advantage of this, I wrote it to help a friend which had date stored in database only by yyyy-mm-dd hh:mm:ss and retrieved via asp from another script.
Article at http://www.xorath.com/articles/?article=2
To use the date("N") function in PHP < 5.1.0 use:
<?php
function dayofweek() {
$days = array("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun");
return array_search(date("D"), $days) + 1;
}
?>
If you want to count quarters between dates you can use the following:
<?php
function countQuarters($begindate, $enddate)
{
if (!isset($begindate) || empty($begindate) || !isset($enddate) || empty($enddate))
return -1;
$countyears = date("Y", strtotime($enddate)) - date("Y", strtotime($begindate));
$quarters = 0;
if (date("Y", strtotime($enddate)) == date("Y", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
return -1;
}
}
}
else
{
$quarters = (int) $countyears * 4;
if (date("m", strtotime($enddate)) != date("m", strtotime($begindate)))
{
if (date("m", strtotime($enddate)) > date("m", strtotime($begindate)))
{
$difference = date("m", strtotime($enddate)) - date("m", strtotime($begindate));
$quarters += ceil((int) $difference / 4);
}
else
{
$afterbegin = 12 - (int) date("m", strtotime($begindate));
$untilend = date("m", strtotime($enddate));
$quarters = ($quarters - 4) + ceil(($afterbegin + $untilend) / 4);
}
}
}
return $quarters;
}
?>
Easy way of switching between mysql and "normal" dates (english, not american)...
<?php
function flipdate($dt, $seperator_in = '-', $seperator_out = '-')
{
return implode($seperator_out, array_reverse(explode($seperator_in, $dt)));
}
?>
***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:
<?php
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 ;)
Slightly modified the code provided by "martin at smttuk dot com" so that you can give the function a date and/or time that you choose;
<?php
function zonedate($layout, $countryzone, $daylightsaving, $time)
{
if($daylightsaving) {
$daylight_saving = date('I');
if($daylight_saving){ $zone=3600*($countryzone+1); }
}
else {
if( $countryzone>>0){ $zone=3600*$countryzone; }
else { $zone=0; }
}
if(!$time) { $time = time(); }
$date = gmdate($layout, $time + $zone);
return $date;
}
?>
For example if I wanted the time and date of my birthday in New Zealand time;
<?php
echo zonedate('Y-m-d H:i:s',-12,true,mktime(18,46,0,9,7,1986));
?>
It's pretty simple, but in case anybody else is having problems getting the exact time they need because of DST (ex: on a Windows box in an area without DST), you can fix it all in a single line. Example...
<?php
echo "The time is " . date((date("I") ? intval(date("g")) - 1 : date("g")) . ":i m/d/y") . ".";
?>
<?php
/* Country Zone : Time Zone Name
-12 : Dateline Standard
-11 : Samoa Standard Time
-10 : Hawaiian Standard Time
-8 : Pacific Standard Time
-7 : Mexican Standard Time, Mountain Standard Time
-6 : Central Standard Time, Mexico Standard Time
-5 : Eastern Standard Time Eastern Time, SA Pacific Standard Time
-4 : Atlantic Standard Time, SA Western Standard Time, Pacific SA Standard Time
-3.5 : Newfoundland Standard Time
-3 : SA Eastern Standard Time, E. South America Standard Time
-2 : Mid:Atlantic Standard Time
-1 : Azores Standard Time, Cape Verde Standard Time
0 : Universal Coordinated Time, Greenwich Mean Time
1 : Romance Standard Time, Central Africa Standard Time, Central European Standard Time
2 : Egypt Standard Time, South Africa Standard Time, E. Europe Standard Time, FLE Standard Time, GTB Standard Time
3 : Arab Standard Time, E. Africa Standard Time, Arabic Standard Time, Russian Standard Time
3.5 : Iran Standard Time
4 : Arabian Standard Time, Caucasus Standard Time, Afghanistan Standard Time
5 : West Asia Standard Time
5.5 : India Standard Time
5.75 : Nepal Standard Time
6 : Central Asia Standard Time
6.5 : Myanmar Standard Time
7 : SE Asia Standard Time, North Asia Standard Time
8 : China Standard Time, W. Australia Standard Time, Singapore Standard Time, Taipei Standard Time, North Asia East Standard Time
9 : Tokyo Standard Time, Korea Standard Time, Yakutsk Standard Time
9.5 : AUS Central Standard Time, Cen. Australia Standard Time
10 : AUS Eastern Standard Time, E. Australia Standard Time
West Pacific Standard Time, Tasmania Standard Time, Vladivostok Standard Time
11 : Central Pacific Standard Time
12 : Fiji Standard Time, New Zealand Standard Time
13 : Tonga Standard Time
* How to use
$layout =
Same function as date : http://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;
}
?>
Number of weeks per month
I was trying to do a monthly calendar and required the number of weeks in a month, running from Monday to Sunday. Since PHP doesn't have this in its date() parameters I had to calculate it in a roundabout manner. By subtracting the week numbers away from each other we SHOULD get the number of weeks, since it is calculated on Mondays.
<?php
$year = date("Y", $date);
$month = date("m", $date);
if( (isset($_GET['year'])) && (intval($_GET['year']) > 1582) )
{
$year = intval($_GET['year']);
}
if( (isset($_GET['month'])) && (intval($_GET['month']) >= 1) && (intval($_GET['month']) <= 12) )
{
$month = intval($_GET['month']);
}
$date = mktime(1, 1, 1, $month, date("d"), $year);
$first_day_of_month = strtotime("-" . (date("d", $date)-1) . " days", $date);
$last_day_of_month = strtotime("+" . (date("t", $first_day_of_month)-1) . " days", $first_day_of_month);
$first_week_no = date("W", $first_day_of_month);
$last_week_no = date("W", $last_day_of_month);
if($last_week_no < $first_week_no) $last_week_no=date("W", strtotime("-1 week",$last_week_no)) + 1;
$weeks_of_month = $last_week_no - $first_week_no + 1;
?>
The check for weeknumber of the end of the month being smaller than the beginning of the month, is because of December. Where Monday 31st is actually in the first week of the following year.
The +1 adjustment is for the number of weeks, inclusive. ie if January had five week, then 5-1=4, so we need to add an extra one to make it 5.
I simplified this after I figured it out based upon Mel Boyce's simple solution. Thanks Mel!
I wanted to calculate dates based upon any given date and not just todays date which is what the hundreds of examples on the Internet use. I created a simple function and then just call the function with 2 parameters.. the date (string) to test and the number of days that I want to add (positive #) or subtract (negative #) My intended use is to retrieve dates from the database and perform the date calculations. This makes it simple. I hope this helps someone as frustrated as I was. Enjoy.
******************************************
<?php
// date calculation function
// adds or subtracts a date based upon the input.
// $this_date is a string format of a valid date ie.. "2006/08/11"
// $num_days is the number of days that you would like to add (positive number) or subtract (negative number)
function fnc_date_calc($this_date,$num_days){
$my_time = strtotime ($this_date); //converts date string to UNIX timestamp
$timestamp = $my_time + ($num_days * 86400); //calculates # of days passed ($num_days) * # seconds in a day (86400)
$return_date = date("Y/m/d",$timestamp); //puts the UNIX timestamp back into string format
return $return_date;//exit function and return string
}//end of function
$date_to_test = "2006/08/11";
$days_to_add = 7;
$past_date = fnc_date_calc($date_to_test,(($days_to_add)*-1));
$future_date = fnc_date_calc($date_to_test,$days_to_add);
echo "Test Date is: ".$date_to_test;
echo "<br>";
echo "Number of days to Calculate is: ".$days_to_add;
echo "<br>";
echo "Past date is: ".$past_date;
echo "<br>";
echo "Future date is: ".$future_date;
?>
For PHP 4 users wanting a format similar to ISO 8601 (http://www.w3.org/TR/NOTE-datetime):
echo date('Y-m-d H:i:s.0T');
returns something like 2006-07-27 16:54:14.0EDT
Here's a function that takes the year as input and returns an array or dates that are mondays. (It can be used for generating weekly reports just like I did)
<?php
function getMondays($year) {
$newyear = $year;
$week = 0;
$day = 0;
$mo = 1;
$mondays = array();
$i = 1;
while ($week != 1) {
$day++;
$week = date("w", mktime(0, 0, 0, $mo,$day, $year));
}
array_push($mondays,date("r", mktime(0, 0, 0, $mo,$day, $year)));
while ($newyear == $year) {
$test = strtotime(date("r", mktime(0, 0, 0, $mo,$day, $year)) . "+" . $i . " week");
$i++;
if ($year == date("Y",$test)) {
array_push($mondays,date("r", $test));
}
$newyear = date("Y",$test);
}
return $mondays;
}
?>
If You are looking for some simple date calculations:
<?php
function days_between($fyear, $fmonth, $fday, $tyear, $tmonth, $tday)
{
return abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
}
function day_before($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-1,$fyear));
}
function next_day($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday+1,$fyear));
}
function weekday($fyear, $fmonth, $fday) //0 is monday
{
return (((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, 7, 17, 2006))/(60*60*24))+700000) % 7;
}
function prior_monday($fyear, $fmonth, $fday)
{
return date ("Y-m-d", mktime (0,0,0,$fmonth,$fday-weekday($fyear, $fmonth, $fday),$fyear));
}
?>
If you do not PHP5 yet but want a week day to be in ISO format: 1 (for Monday) through 7 (for Sunday), you can use this:
<?php
//GET WEEK DAY 0 FOR SUNDAY, 6 FOR SATURDAY
$x = date( "w" );
$corrected_week_day = 7 - ( (7-$x) % (7+$x) );
?>
I've been flicking through the comments looking for some succinct date code and have noticed an alarming number of questions and over-burdened examples related to date mathematics. One of the most useful skills you can utilize when performing date math is taking full advantage of the UNIX timestamp. The UNIX timestamp was built for this kind of work.
An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days = floor((time() - strtotime("01-Jan-2006"))/86400);
print("$days days have passed.\n");
?>
Another usage could find itself in a class submitted by Kyle M Hall which aids in the creation of timestamps from the recent past for use with MySQL. Rather than the looping and fine tuning of a date, Kyle can use the raw UNIX timestamps (this is untested code):
<?php
$ago = 14; // days
$timestamp = time() - ($ago * 86400);
?>
Hopefully these two examples of "UNIX-style" timestamp usage will help those finding date mathematics more elusive than it should be.
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>
If you need dates that are prior to 1970 (or 1901 for php5.1), have a look at calendar at this very site:
http://www.php.net/calendar
Users in GMT may find some information on British Summer Time useful. Personally I was confused that date() for a timestamp of 0 was returning 1am, until I found about the all-year BST from 1968-71.
http://wwp.greenwichmeantime.com/info/bst2.htm
The examples for getting a date in the past or future is simply not the best way to do it. Especially if you are doing it dynamically.
I find the best way to get a date in the past or future is like this:
<?php
//get timestamp for past/future date I want
$pf_time = strtotime("-3 days");
//format the date using the timestamp generated
$pf_date = date("Y-m-d", $pf_time);
?>
There is a mistaken impression that the maximum difference between UTC and localtime is +/- 12 hours. Right now it is summer here in New Zealand, and we're 13 hours ahead of UTC, and further east in the Chatham Islands it's UTC+13:45.
Consequently, the range for the "Z" conversion is at least -43200 ... +49500
Using 'B' for the Swatch Internet Time (i.Beats) can still lead to misunderstandings, because the date given in the resulting string is the local date, not the date of the BMT (Biel Mean Time / UTC+0100) after which the i.Beats are counted. So while @000 is equal all around the globe, October 25th 2005 @000 in Chicago is really October 24th, 06:00 PM local time.
Otherwise, if you use date('d M Y @B') in Chicago on that day at 6pm, it will return "24 Oct 2005 @000" although it should be "25 Oct 2005 @000".
So it may happen that you miss an appointment by 24 hours (or 1000 Beats ;-)
Here's a way to return the Internet Time with correct date:
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
$ssm = date('H', $bmttime)*3600 + date('i', $bmttime)*60 + date('s', $bmttime); // seconds since midnight (BMT)
$ibeats = $ssm/86.4; // 86400 seconds = 1000 beats, so 1 beat = 86.4 seconds
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . $ibeats;
?>
Note: If you would try date('D, d M Y @B', $bmttime), the resulting beats would be wrong because the timezone used for calculation of the beats within the date() function is still your local one but the timestamp is UTC+0100. Another working way would be:
<?php
$curtime = time();
$utcdiff = date('Z', $curtime); // get difference to UTC in seconds
$bmttime = $curtime - $utcdiff + 3600; // BMT = UTC+0100
echo 'i.Beats : ' . date('D, d M Y', $bmttime) . ' @' . date('B', $curtime);
?>
But this way there are no floating-point beats possible, which may be handy sometimes.
I created a routine that fills an array with the dates in the current week. For example $WeekDays[0] is sunday's date, $WeekDays[1] is monday's date and so on no matter what day of the week it is today.
<?php
$lowEnd=date("w");
$lowEnd=-$lowEnd;
$highEnd=$lowEnd + 6;
$weekday=0;
for ($i=$lowEnd; $i<=$highEnd; $i++) {
$WeekDate[$weekday]=date("m/d",mktime(0, 0, 0, date("m") , date("d")+$i, date("Y")));
$weekday++;
}
?>
For users who want a different language than english, you can user strftime() function in combination with setlocale() instead of date():
e.g. for german language:
With date you would write:
<?php
echo date('l, d. F Y'); //Output: Wednesday, 07. September 2005
?>
With strftime() you can output it in german like this:
<?php
// Set the gloabal LC_TIME constant to german
setlocale(LC_TIME, 'de_DE');
// Little bit other Syntax but better effect
echo strftime('%A, %d. %B %Y'); //Output: Mittwoch, 07. September 2005
?>
Greetings, Andy!
Don't forget that months start on the 1st day, and not a zero date. Might seem obvious but:
<?php $test = date("F Y", mktime(0, 0, 0, 12, 0, 2005)); ?>
Will return November 2005, not December.
<?php $test = date("F Y", mktime(0, 0, 0, 12, 1, 2005)); ?>
The 1st is needed to get the right month.
Calculus of weeks in a year.
Since there is date("W") many still seem to have a problem regarding how many weeks there are in an year. Some rather complex solutions have been shown here.
It's defined, that a week which begins in december and ends in january the following year belongs to the year where most of its days lie. Therefore a week with at least 4 days in december is the last week of that year and a week with at least 4 days in january is the first week in the new year.
This concludes, that the last week of a year always contains the 28th day of december. So if you take date("W") on that day of a given year you always get the correct number of weeks for that year.
The other end of that definition is that the 4th day of january always lies in the first week of a year.
I hope this solves a lot of confusion.
(For those asking what all this fuzz about counting weeks is about: normally theres 52 weeks in a year but sometimes its 53 weeks in a year)
I wrote it down as a function, but as this is rather trivial one might consider using the date(...) only.
<?php
function weeks($year) {
return date("W",mktime(0,0,0,12,28,$year));
}
?>
To convert an unix timestamp to suite the syntax of a GeneralizedTime attribute for OpenLDAP, you can use
date ('YmdHiZO'). Note that this conversion uses local time, the recommended way is to store dates in UTC.
If your date is in UTC, just use
date ('YmdHiZ').'Z' to convert it ("Z" stands for "Zulu", which is UTC).
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha). Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10. (In the old Julian reckoning, EVERY 4th year was a leap-year.)
This algorithm was first proposed by the mathematician/physicist Gauss. Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.
<?php
function getOrthodoxEaster($date){
/*
Takes any Gregorian date and returns the Gregorian
date of Orthodox Easter for that year.
*/
$year = date("Y", $date);
$r1 = $year % 19;
$r2 = $year % 4;
$r3 = $year % 7;
$ra = 19 * $r1 + 16;
$r4 = $ra % 30;
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
$r5 = $rb % 7;
$rc = $r4 + $r5;
//Orthodox Easter for this year will fall $rc days after April 3
return strtotime("3 April $year + $rc days");
}
?>