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.
date
(PHP 4, PHP 5)
date — Formatuje lokalny czas/datę
Opis
Zwraca datę sformatowaną zgodnie z szablonem podanym w argumencie jako znacznik_czasu , lub aktualnego czasu w przypadku wywołania jej bez tego argumentu. Innymi słowy, znacznik_czasu jest parametrem opcjonalnym, domyślnie pobierającym wartość funkcji time().
Parametry
- format
-
Format zwracanej daty string. Zobacz możliwe ustawienia formatowania poniżej.
Poniższych znaków używa się jako tekstu w parametrze format Zawartość parametruformat Opis Przykład zwróconej wartości Dzień --- --- d Dzień miesiąca, 2 cyfry z wiodącymi zerami 01 do 31 D Tekstowy opis angielskiej nazwy dnia, trzy litery Mon kończąc na Sun j Dzień miesiąca bez zer wiodących 1 do 31 l (mała litera 'L') Pełen angielski opis dnia tygodnia Sunday aż do Saturday N Liczbowa forma dnia tygodnia, zgodna z normą ISO-8601 (dodana w PHP 5.1.0) 1 (dla Poniedziałku) aż do 7 (dla Niedzieli) S Angielski przyrostek porządkowy dla dnia miesiąca, 2 litery st, nd, rd lub th. Dobrze wygląda w połączeniu z j w Liczbowa forma dnia tygodnia 0 (dla Niedzieli) aż do 6 (dla Soboty) z Dzień roku (Zaczynając od 0) 0 aż do 365 Week --- --- W Numer tygodnia w roku, zgodny z normą ISO-8601, Tygodnie rozpoczynają Poniedziałki (dostępne od PHP 4.1.0) Przykład: 42 (42. tydzień roku) Month --- --- F Pełen angielski opis, dnia miesiąca, taki jak January czy March January aż do December m Liczbowa forma miesiąca, z zerami wiodącymi 01 aż do 12 M Krótki, angielski opis miesiąca, trzy litery Jan a do Dec n Liczbowa forma miesiąca, bez zer wiodących 1 aż do 12 t Ilość dni w danym miesiącu 28 do 31 Rok --- --- L Informacja o tym, czy rok jest przestępnym 1 jeśli rok jest przestępny, 0 w przeciwnym wypadku. o Numer roku, zgodny z normą ISO-8601. Zwraca to taką samą wartość jak Y, z takim wyjątkiem, że numer tygodnia ISO (W) należy do poprzedniego lub następnego roku, niż rok użyty w tym miejscu. (dodane w PHP 5.1.0) Przykłady: 1999 lub 2003 Y Pełna liczbowa forma roku, 4 cyfry Przykłady: 1999 lub 2003 y Dwie cyfry reprezentujące rok Przykłady: 99 or 03 Czas --- --- a Pora dnia - dwie małe litery (przed/po południu) (ang. Ante/Post meridiem) am lub pm A Pora dnia - dwie duże litery (przed/po południu) (ang. Ante/Post meridiem) AM lub PM B Swatch Internet Time 000 aż do 999 g Godzina, w formacie 12-godzinnym, bez zer wiodących 1 aż do 12 G Godzina, w formacie 24-godzinnym, bez zer wiodących 0 aż do 23 h Godzina, w formacie 12-godzinnym, z zerami wiodącymi 01 aż do 12 H Godzina, w formacie 24-godzinnym, z zerami wiodącymi 00 through 23 i Minuty z zerami wiodącymi 00 do 59 s Sekundy, z zerami wiodącymi 00 aż do 59 u Mikrosekundy (dodano w PHP 5.2.2) Przykład: 54321 Strefa czasowa --- --- e Identyfikator strefy czasowej (dodano w PHP 5.1.0) Przykłady: UTC, GMT, Europe/Zagreb I (duże i) Informacja o tym, czy czas jest letni 1 jeśli czas jest letni, 0 w przeciwnym razie. O Różnica z czasem Greenwich (GMT) w godzinach Przykład: +0200 P Różnica z czasem Greenwich (GMT) z dwukropkiem pomiędzy godzinami i minutami (dodano w PHP 5.1.3) Przykład: +02:00 T Skrót dla strefy czasowej Przykłady: EST, MDT ... Z Różnica dla strefy czasowej w sekundach. Wyrównanie to jest zawsze ujemne dla stref położonych na zachód od południka 0, oraz dodatnie dla tych leżących na wschódod niego. -43200 aż do 50400 Pełna Data/Czas --- --- c Data w standardzie ISO 8601 (dodana w PHP 5) 2004-02-12T15:19:21+00:00 r Data sformatowana zgodnie z » RFC 2822 Przykład: Thu, 21 Dec 2000 16:01:07 +0200 U Sekundy liczone od ery UNIX-a (1 stycznia 1970 00:00:00 czasu Greenwich - GMT) Zobacz także time() Inne znaki umieszczone w łańcuchu formatującym zostaną przez parser przepisane. Z zwróci zawsze 0 podczas używania gmdate().
Informacja: Odkąd ta funkcja przyjmuje jako znacznik czasu jedynie typ integer znak formatujący u przydaje się jedynie, gdy używamy funkcji date_format() z samodzielnie zdefiniowanymi znacznikami czasu stworzonymi za pomocą funkcji date_create().
- timestamp
-
Opcjonalny parametr uniksowy znacznik czasu timestamp jest typu integer i domyślnie jest ustawiony na bieżący czas lokalny jeśli timestamp nie został podany. Innymi słowy, domyślnie to wartość funkcji time().
Zwracane wartości
Zwraca sformatowaną datę jako łańcuch. Jeśli użyto wartości parametru znacznik_czasu innej niż liczbowa, cała funkcja zwróci FALSE oraz pojawi się ostrzeżenie klasy E_WARNING.
Błędy/Wyjątki
Każde wywołanie do funkcji date/time spowoduje wygenerowanie E_NOTICE jeśli strefa czasowa jest nieprawidłowa, lub/i wiadomość E_STRICT jeśli użyto ustawień systemu lub zmiennej środowiskowej TZ. Patrz także date_default_timezone_set()
Rejestr zmian
| Wersja | Opis |
|---|---|
| 5.1.0 | Poprawny zakres znacznika czasu to zwykle od piątku, 13 grudnia 1901 20:45:54 GMT (czasu Greenwich) do wtorku, 19 stycznia 2038 03:14:07 GMT. (Wartości te odpowiadają minimalnej i maksymalnej wartości 32-bitowej liczbie całkowitej ze znakiem). Jednakże przed PHP 5.1.0, w niektórych systemach (np. Windows) ten przedział był bardziej ograniczony i zawiera się w przedziale 01-01-1970 do 19-01-2038. |
| 5.1.0 | Teraz generuje błędy strefy czasowej o poziomie E_STRICT i E_NOTICE. |
| 5.1.1 | Istnieją użyteczne stałe standaryzujące formaty daty/czasu mogące być użyte w celu określenia parametru format . |
Przykłady
Przykład #1 Przykłady użycia funkcji date()
<?php
// ustawia domyślnie używaną strefę czasową. Dostępne od PHP 5.1
date_default_timezone_set('UTC');
// wypisuje np.: Monday
echo date("l");
// wypisuje coś jak: Monday 8th August 2005 03:12:46 PM
echo date('l jS F Y h:i:s A');
// wypisuje: 1 lipca, 2000 wypada w Saturday
echo "1 lipca, 2000 wypada w " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* użycie stałych jako parametru format */
// wypisuje coś jak: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// wypisuje coś jak: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
Możesz ochronić rozpoznawalne znaki w łańcuchu formatującym przed zinterpretowaniem przez poprzedzenie ich znakiem ucieczki - backslashem. Jeśli znak razem z backslashem jest specjalną sekwencją, możliwe, iż będzie trzeba poprzedzić kolejnym znakiem ucieczki całą sekwencję.
Przykład #2 Znaki ucieczki w funkcji date()
<?php
// wypisuje coś jak: jest Wednesday, 15th
echo date("\j\e\s\\t l, jS");
?>
Możliwe jest użycie funkcji date() razem z funkcją mktime() w celu znalezienia dat z przeszłości lub przyszłości.
Przykład #3 Przykład użycia date() i mktime()
<?php
$jutro = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$ostatni_miesiac = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nastepny_rok = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Informacja: Rozwiązanie to jest rozsądniejsze, od prostego dodawania lub odejmowania określonej liczby sekund w dniu lub miesiącu, chociażby z powodu zmian czasu.
Poniżej znajduje się kilka przykładów zastosowania date(). Proszę zwrócić uwagę, że powinno się cytować wszystkie znaki aby uniknąć nieoczekiwanych rezultatów, a poza tym, nawet te znaki, które obecnie nie mają specjalnych znaczeń, mogą mieć przypisane jakieś znaczenie w przyszłych wersjach PHP. O ile to możliwe, należy używać cudzysłowów pojedynczych, żeby uniknąć np. zamiany \n na znak nowej linii.
Przykład #4 zastosowania date()
<?php
// Przypuśćmy, że dziś jest 10 marca, 2001, 5:16:18 pm, oraz, że jesteśmy w
// strefie czasowej MST (Mountain Standard Time)
$dzisiaj = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$dzisiaj = date("m.d.y"); // 03.10.01
$dzisiaj = date("j, n, Y"); // 10, 3, 2001
$dzisiaj = date("Ymd"); // 20010310
$dzisiaj = date('h-i-s, j-m-y, it is w Day z '); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01
$dzisiaj = date('\t\o jS \d\z\i\e\ń'); // to 10. dzień
$dzisiaj = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001
$dzisiaj = date('H:m:s \m \t\o\ \m\i\e\s\i\ą\c'); // 17:03:18 m is month
$dzisiaj = date("H:i:s"); // 17:16:18
?>
Aby sformatować datę w innych językach, należy użyć funkcji setlocale() i strftime() zamiast date().
Notatki
Informacja: Aby stworzyć znacznik czasu z tekstowego opisu daty, możesz użyć strtotime(). Dodatkowo, niektóre bazy danych mają funkcje konwertujące ich format daty na znacznik czasu (tak jak funkcja » UNIX_TIMESTAMP w MySQL).
Znacznik czasu z chwili wysłania zapytania jest dostępny w $_SERVER['REQUEST_TIME'] od PHP 5.1.
Zobacz też:
- getlastmod() - Gets time of last page modification
- gmdate() - Formatuje datę/czas dla strefy GMT/UTC
- mktime() - Oblicza uniksowy znacznik czasu dla podanej daty
- strftime() - Formatuje lokalną datę/czas zgodnie z lokalizacją
- time() - Zwraca aktualny uniksowy znacznik czasu
date
11-Jun-2009 11:20
27-May-2009 04:12
<?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;
}
?>
24-May-2009 08:52
// 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>";
}
?>
29-Apr-2009 06:55
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";
?>
21-Apr-2009 08:34
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']));
}
?>
14-Apr-2009 02:10
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
?>
13-Apr-2009 05:21
<?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;
}
?>
24-Feb-2009 10:22
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.
21-Jan-2009 02:47
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;
}
?>
18-Nov-2008 07: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 08: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
*/
?>
02-Oct-2008 10: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').
12-Sep-2008 01:01
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
27-Aug-2008 06: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 12: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
14-Aug-2008 10: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 06: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 08: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>
<?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>
10-Jul-2008 04: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 03: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('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!
01-Jul-2008 04:20
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--;
}
?>
30-Jun-2008 02:18
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'>"