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
?>
date
(PHP 4, PHP 5)
date — Formate une date/heure locale
Description
Retourne une date sous forme d'une chaîne, au format donné par le paramètre format , fournie par le paramètre timestamp ou la date et l'heure courantes si aucun timestamp n'est fourni. En d'autres termes, le paramètre timestamp est optionnel et vaut par défaut la valeur de la fonction time().
Liste de paramètres
- format
-
Le format de la date désirée. Voir les options de formatage ci-dessous.
Les caractères suivants sont reconnus dans le paramètre format . Caractères pour le paramètre format Description Exemple de valeurs retournées Jour --- --- d Jour du mois, sur deux chiffres (avec un zéro initial) 01 à 31 D Jour de la semaine, en trois lettres (et en anglais) Mon à Sun j Jour du mois sans les zéros initiaux 1 à 31 l ('L' minuscule) Jour de la semaine, textuel, version longue, en anglais Sunday à Saturday N Représentation numérique ISO-8601 du jour de la semaine (ajouté en PHP 5.1.0) 1 (pour Lundi) à 7 (pour Dimanche) S Suffixe ordinal d'un nombre pour le jour du mois, en anglais, sur deux lettres st, nd, rd ou th. Fonctionne bien avec j w Jour de la semaine au format numérique 0 (pour dimanche) à 6 (pour samedi) z Jour de l'année 0 à 366 Semaine --- --- W Numéro de semaine dans l'année ISO-8601, les semaines commencent le lundi (ajouté en PHP 4.1.0) Exemple : 42 (la 42ème semaine de l'année) Mois --- --- F Mois, textuel, version longue; en anglais, comme January ou December January à December m Mois au format numérique, avec zéros initiaux 01 à 12 M Mois, en trois lettres, en anglais Jan à Dec n Mois sans les zéros initiaux 1 à 12 t Nombre de jours dans le mois 28 à 31 Année --- --- L Est ce que l'année est bissextile 1 si bissextile, 0 sinon. o L'année ISO-8601. C'est la même valeur que Y, excepté que si le numéro de la semaine ISO (W) appartient à l'année précédente ou suivante, cette année sera utilisé à la place. (ajouté en PHP 5.1.0) Exemples : 1999 ou 2003 Y Année sur 4 chiffres Exemples : 1999 ou 2003 y Année sur 2 chiffres Exemples : 99 ou 03 Heure --- --- a Ante meridiem et Post meridiem en minuscules am ou pm A Ante meridiem et Post meridiem en majuscules AM ou PM B Heure Internet Swatch 000 à 999 g Heure, au format 12h, sans les zéros initiaux 1 à 12 G Heure, au format 24h, sans les zéros initiaux 0 à 23 h Heure, au format 12h, avec les zéros initiaux 01 à 12 H Heure, au format 24h, avec les zéros initiaux 00 à 23 i Minutes avec les zéros initiaux 00 à 59 s Secondes, avec zéros initiaux 00 à 59 u Millisecondes (ajouté en PHP 5.2.2) Exemple : 54321 Fuseau horaire --- --- e L'identifiant du fuseau horaire (ajouté en PHP 5.1.0) Exemples : UTC, GMT, Atlantic/Azores I (i majuscule) L'heure d'été est activée ou pas 1 si oui, 0 sinon. O Différence d'heures avec l'heure de Greenwich (GMT), exprimée en heures Exemple : +0200 P Différence avec l'heure Greenwich (GMT) avec un deux-points entre les heures et les minutes (ajouté dans PHP 5.1.3) Exemple : +02:00 T Abréviation du fuseau horaire Exemples : EST, MDT ... Z Décalage horaire en secondes. Le décalage des zones à l'ouest de la zone UTC est négative, et à l'est, il est positif. -43200 à 50400 Date et Heure complète --- --- c Date au format ISO 8601 (ajouté en PHP 5) 2004-02-12T15:19:21+00:00 r Format de date » RFC 2822 Exemple : Thu, 21 Dec 2000 16:01:07 +0200 U Secondes depuis l'époque Unix (1er Janvier 1970, 0h00 00s GMT) Voir aussi time() Les caractères non reconnus seront imprimés tels quel. "Z" retournera toujours 0 lorsqu'il est utilisé avec gmdate().
Note: Sachant que cette fonction n'accepte que des entiers sous la forme de timestamp, le caractère u n'est utile que lors de l'utilisation de la fonction date_format() avec un timestamp utilisateur créé avec la fonction date_create().
- timestamp
-
Le paramètre optionnel timestamp est un timestamp Unix de type entier qui vaut par défaut l'heure courante locale si le paramètre timestamp n'est pas fourni. En d'autres termes, il faut par défaut la valeur de la fonction time().
Valeurs de retour
Retourne une date formatée. Si une valeur non-numérique est utilisée dans le paramètre timestamp , FALSE sera retourné et une erreur de niveau E_WARNING est émise.
Erreurs / Exceptions
Chaque appel à une fonction date/heure générera un message de type E_NOTICE si le fuseau horaire n'est pas valide., et/ou un message de type E_STRICT si vous utilisez la configuration du système ou la variable d'environnement TZ. Voir aussi date_default_timezone_set()
Historique
| Version | Description |
|---|---|
| 5.1.0 | L'intervalle de validité d'un timestamp va généralement du Vendredi 13 Décembre 1901 20:45:54 GMT au Mardi 19 Janvier 2038 03:14:07 GMT. (Ces dates correspondent aux valeurs minimales et maximales des entiers 32 bits non-signés). Cependant, avant PHP 5.1.0, cette intervalle va du 01-01-1970 au 19-01-2038 sur quelques systèmes (e.g. Windows). |
| 5.1.0 | Émet un message de type E_STRICT et E_NOTICE lors d'erreurs de fuseaux horaires. |
| 5.1.1 | Il y a plusieurs constantes utiles de formats date/heure standards qui peuvent être utilisées pour spécifier le paramètre format . |
Exemples
Exemple #1 Exemple avec date()
<?php
// Définit le fuseau horaire par défaut à utiliser. Disponible depuis PHP 5.1
date_default_timezone_set('UTC');
// Affichage de quelque chose comme : Monday
echo date("l");
// Affichage de quelque chose comme : Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
// Affiche : July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000));
/* utilise les constantes dans le paramètre format */
// Affichage de quelque chose comme : Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);
// Affichage de quelque chose comme : 2000-07-01T00:00:00+00:00
echo date(DATE_ATOM, mktime(0, 0, 0, 7, 1, 2000));
?>
Vous pouvez faire afficher un caractère spécial dans la chaîne de format en le protégeant par un antislash. Si le caractère est lui-même une séquence incluant un antislash, vous devrez protéger aussi l'antislash.
Exemple #2 Protection des caractères dans la fonction date()
<?php
// Affichage de quelque chose comme : Wednesday the 15th
echo date("l \\t\h\e jS");
?>
Il est possible d'utiliser date() et mktime() ensemble pour générer des dates dans le futur ou dans le passé.
Exemple #3 Exemple avec date() et mktime()
<?php
$tomorrow = mktime(0, 0, 0, date("m") , date("d")+1, date("Y"));
$lastmonth = mktime(0, 0, 0, date("m")-1, date("d"), date("Y"));
$nextyear = mktime(0, 0, 0, date("m"), date("d"), date("Y")+1);
?>
Note: Cette méthode est plus sûre que simplement ajouter ou retrancher le nombre de secondes dans une journée ou un mois à un timestamp, à cause des heures d'hiver et d'été.
Voici maintenant quelques exemples de formatage avec date(). Notez que vous devriez échapper tous les autres caractères, car s'ils ont une signification spéciale, ils risquent de produire des effets secondaires indésirables. Notez aussi que les versions futures de PHP peuvent attribuer une signification à des lettres qui sont actuellement inertes. Lorsque vous échappez les caractères, pensez à utiliser des guillemets simples, pour que les séquences \n ne deviennent pas des nouvelles lignes.
Exemple #4 Exemple avec date()
<?php
// Aujourd'hui, le 12 Mars 2001, 10:16:18 pm
$today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm
$today = date("m.d.y"); // 03.10.01
$today = date("j, n, Y"); // 10, 3, 2001
$today = date("Ymd"); // 20010310
$today = date('h-i-s, j-m-y, it is w Day z '); // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // C'est le 12th jour.
$today = date("D M j G:i:s T Y"); // Sat Mar 10 15:16:08 MST 2001
$today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:17 m est le mois
$today = date("H:i:s"); // 17:16:17
?>
Pour formater des dates dans d'autres langues, utilisez les fonctions setlocale() et strftime() au lieu de la fonction date().
Notes
Note: Pour générer un timestamp à partir d'une représentation de date, vous pouvez utiliser la fonction strtotime(). De plus, certaines bases de données disposent de fonctions pour convertir leurs propres formats de date en timestamps (par exemple, MySQL et sa fonction » UNIX_TIMESTAMP()).
Un timestamp représentant le début de la requête est disponible dans la variable $_SERVER['REQUEST_TIME'] depuis PHP 5.1.
date
27-Aug-2008 08:47
26-Aug-2008 02:32
here is the simpliest way to get the start and end date of the week;
<?php
$sdate=date('c',strtotime(date('Y')."W".date('W')."0"));
$edate=date('c',strtotime(date('Y')."W".date('W')."7"));
?>
the format is for the string in strtotime is;
2008W200
this stands for year - 2008, constant never changes - W, week number of the year - 20, day of the week - 0 for sunday, 1 for monday, etc....
so 2008W200 stands for the sunday of the 20th week of 2008.
This will only work in php 5 or better
22-Aug-2008 11:16
simple code to get the date of the monday and sunday of the current week.
inspired by: wulf dot kaiser at mpimf-heidelberg dot mpg dot de
<?
$day = date('d');
$wkday = date('l');
$month = date('m');
$year = date('Y');
switch($wkday) {
case 'Monday': $numDaysToSun = 6; $numDaysToMon = 0; break;
case 'Tuesday': $numDaysToSun = 5; $numDaysToMon = 1; break;
case 'Wednesday': $numDaysToSun = 4; $numDaysToMon = 2; break;
case 'Thursday': $numDaysToSun = 3; $numDaysToMon = 3; break;
case 'Friday': $numDaysToSun = 2; $numDaysToMon = 4; break;
case 'Saturday': $numDaysToSun = 1; $numDaysToMon = 5; break;
case 'Sunday': $numDaysToSun = 0; $numDaysToMon = 6; break;
}
echo $wkday;
echo " - ";
echo $day;
echo " - ";
echo $month;
echo " - ";
echo $year;
echo " - ";
echo $numDaysToSun;
echo " - ";
echo $numDaysToMon;
echo " - ";
echo $monday = date('d-m-Y', mktime('0','0','0', $month, $day-$numDaysToMon, $year));
echo " - ";
echo $sunday = date('d-m-Y', mktime('0','0','0', $month, $day+$numDaysToSun, $year));
?>
headings:
Day(string) - day - month - year - days to sun - days from mon - monday date - sunday date
output:
Friday - 22 - 08 - 2008 - 2 - 4 - 18-08-2008 - 24-08-2008
15-Aug-2008 12:53
All novices must be very carefull when working with timestamps as second values.
From first glance it looks like date("Y-m-d H:i:s",TIMESTAMP) will return correct date, based on "how much seconds gone from 1970".
But here is the feature, it'll be corrected time, according to LOCAL timezone.
So if you take a 25200 as timestamp (10 hours),
then on one server you'll get
1970-01-01 08:00:00
and on other server you'll get
1970-01-01 09:00:00
and so on.
Though you could expect 1970-01-01 10:00:00 in all cases, because if 25200 seconds gone from 1970-01-01 00:00:00 it obviously have to be 1970-01-01 10:00:00
I spend today 3 hours to correct scripts which were created with such error by previous programmer, so please, guys, don't make me work like this and remember about conversation to LOCAL time.
06-Aug-2008 08:25
Try this for finding the difference in days between 2 dates/datetimes... take note though, date_parse requires PHP version 5.1.3 or higher.
<?php
/**
* Finds the difference in days between two calendar dates.
*
* @param Date $startDate
* @param Date $endDate
* @return Int
*/
function dateDiff($startDate, $endDate)
{
// Parse dates for conversion
$startArry = date_parse($startDate);
$endArry = date_parse($endDate);
// Convert dates to Julian Days
$start_date = gregoriantojd($startArry["month"], $startArry["day"], $startArry["year"]);
$end_date = gregoriantojd($endArry["month"], $endArry["day"], $endArry["year"]);
// Return difference
return round(($end_date - $start_date), 0);
}
?>
28-Jul-2008 12:16
if you want to get the number of month
between two dates
you can use this function:
<?php
/*
$start = "YYYYMM" ;
$stop = "YYYYMM" ;
*/
function getNumMonth($start,$stop) {
$aSta = substr($start,0,4) ;
$aSto = substr($stop,0,4) ;
$mSta = substr($start,4,2) ;
$mSto = substr($stop,4,2) ;
if($aSta == $aSto) {
return $mSto-$mSta+1 ;
} else {
if(($aSto-$aSta) == 1) {
return 12-$mSta+$mSto+1 ;
} else {
return (12-$mSta+$mSto+1)+($aSto-$aSta-1)*12;
}
}
}
?>
25-Jul-2008 10:22
<?php
// A demonstration of the new DateTime class for those
// trying to use dates before 1970 or after 2038.
?>
<h2>PHP 2038 date bug demo (php version <?= phpversion() ?>)</h1>
<div style='float:left;margin-right:3em;'>
<h3>OLD Buggy date()</h3>
<?
$format='F j, Y';
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
?>
Trying: <?=$datep?> = <?=date($format, strtotime($datep))?><br>
<?
}
?></div>
<div style='float:left;'>
<h3>NEW DateTime Class (v 5.2+)</h3><?
for ( $i = 1900; $i < 2050; $i++) {
$datep = "$i-01-01";
$date = new DateTime($datep);
?>
Trying: <?=$datep?> = <?=$date->format($format)?><br>
<?
}
?></div>
18-Jul-2008 09:41
<?php
/*
@params $firstdate, $lastdate
@return array() of array(monday,sunday)
@description returns all the mondays and sundays of the given date range
*/
function get_week_intervals($fdate,$ldate)
{
list($year,$month,$day) = explode('-',$fdate);
$daynum = date('w',
mktime(date('H'),
date('i'),
date('s'),
$month,
$day,
$year)
);
$daynum = $daynum==0? 7 : $daynum;
$week=array();
//get the dayname of the first day
//if month = current month get the current date as the last day
if($month==date('m'))
{
$lastday = date('d');
}
else
{
$lastday = date('t', strtotime($fdate));
}
if((date('l',strtotime($fdate))) == 'Sunday')
{
$monday = $fdate;
$sunday = $fdate;
}
else
{
$monday = $fdate;
$sunday = date('Y-m-d',(mktime(date('H'),
date('i'),date('s'),$month,
$day,$year))-($daynum-7)*86400);
}
$week[] = array('monday'=>$monday,'sunday'=>$sunday);
$day = date('d',strtotime($sunday." +1 day"));
while($sunday < $ldate)
{
$monday = date('Y-m-d',strtotime($sunday." +1 day"));
list($year,$month,$day) = explode('-',$monday);
$daynum = date('w',
mktime(date('H'),
date('i'),
date('s'),
$month,
$day,
$year)
);
$daynum = $daynum==0? 7 : $daynum;
$sunday = date('Y-m-d',(mktime(date('H'),date('i'),
date('s'),$month,$day,$year))-($daynum-7)*86400);
if($sunday > $ldate)
{
$sunday = $ldate;
}
$week[] = array('monday'=>$monday,'sunday'=>$sunday);
}
return $week;
}
?>
17-Jul-2008 06:30
to get the date of the monday from a week these function is useful:
<?php
/* Get First Calendar Week of Year x*/
function firstkw($jahr)
{
$erster = mktime(0,0,0,1,1,$jahr);
$wtag = date('w',$erster);
if ($wtag <= 4) {
/**
* Donnerstag oder kleiner: auf den Montag zurückrechnen.
*/
$montag = mktime(0,0,0,1,1-($wtag-1),$jahr);
} else {
/**
* auf den Montag nach vorne rechnen.
*/
$montag = mktime(0,0,0,1,1+(7-$wtag+1),$jahr);
}
return $montag;
}
/*GET timestamp of monday of month x*/
function mondaykw($kwtime)
{
$firstmonday =$this->firstkw(date("Y", $kwtime));
$mon_monat = date('m',$firstmonday);
$mon_jahr = date('Y',$firstmonday);
$mon_tage = date('d',$firstmonday);
$tage = (date("W", $kwtime)-1)*7;
$mondaykw = mktime(0,0,0,$mon_monat,$mon_tage+$tage,$mon_jahr);
return $mondaykw;
}
echo mondaykw(time()); //1215986400
?>
14-Jul-2008 09:56
here is a function to split a number of seconds in hours, minutes and seconds
<?php
function split_seconds($seconds)
{
// get the minutes
$minutes = floor($seconds / 60) ;
$seconds_left = $seconds % 60 ;
// get the hours
$hours = floor($minutes / 60) ;
$minutes_left = $minutes % 60 ;
// (test) show the result
echo "$hours hours $minutes_left minutes and $seconds_left seconds" ;
}
split_seconds(68648) ;
?>
best regards
fernando gabrieli
14-Jul-2008 02:43
Assuming a week starts on Monday. To calculate the week number of the current date starting from a specified date, use this function:
<?php
function weekcounter($start_date)
{
$start_date = strtotime($start_date);
$today = strtotime(date('d-m-Y'));
$week = 1;
while($start_date < $today) {
$start_date = strtotime('next Monday', $start_date);
$week++;
}
return $week;
}
// Example:
//now = 14-07-2008
echo weekcounter('01-07-2008'); //prints 3
echo weekcounter('01-06-2008'); //prints 8 instead of 7; because 1st jun is a Sunday so it is week 1 and 2nd june is week 2. Feel free to tweak.
?>
10-Jul-2008 06:38
Quick function for returning the names of the next 7 days of the week starting with today.
Returns an array that can be formatted to your liking.
<?php
/**
* Returns array of next 7 days starting with today
*
*/
function next_7_days() {
// create array of day names. You can change these to whatever you want
$days = array(
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday',
'Sunday');
$today = date('N');
for ($i=1;$i<$today;$i++) {
// take the first element off the array
$shift = array_shift($days);
// ... and add it to the end of the array
array_push($days,$shift);
}
// returns the sorted array
return $days;
}
?>
It basically takes an array starting with Monday and shifts each day to the end of the array until the first element in the array is today.
10-Jul-2008 05:46
Doing $w-- for months ending on Sat won't hurt (i.e. if you're counting weeks as is the case below), but halocastle's code is perfectly fine as is and quite fast. He/she uses $w as a key for the $weeks array. "Halo" does this BEFORE $w++, so $w-- is superfluous as the loop has already ended. For May, 2008, I get 5 weeks as expected...
Array
(
[1] => Array
(
[4] => 1
[5] => 2
[6] => 3
)
[2] => Array
(
[0] => 4
[1] => 5
------------OMITTED-----------------
[4] => 22
[5] => 23
[6] => 24
)
[5] => Array
(
[0] => 25
[1] => 26
[2] => 27
[3] => 28
[4] => 29
[5] => 30
[6] => 31
)
)
I guess the one pit-fall of the code is if you overlap months, say the following year, then $m-- makes perfect since...I think (haven't gotten that far...yet).
I modified "Halo's" code to include months, too (this is from a snippet that produces a three month calendar, hence the outer $months loop, omitted here).
<?php
$m = date('m');
$Y = date('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!
03-Jul-2008 04:44
Slight amendment to halocastle at yahoo dot com 's 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--;
}
?>
01-Jul-2008 06: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
)
)
30-Jun-2008 04: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'>";
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
?>
26-Jun-2008 10:12
@anonymous (12-Jun-2008 08:45):
date("t") returns the last day of the month, not the last working day of the month.
A cleaner example would be as follows:
<?php
function lastworkingday($date)
{
for($lastday=mktime(0,0,0,date("m",$date),
date("t",$date),date("Y",$date));
date("w",$lastday)==0 || date("w",$lastday)==6;
$lastday-=60*60*24);
return date("j",$lastday);
}
?>
18-Jun-2008 12:29
to get the week of the month simply use:
ceil( date("j") / 7 );
10-Jun-2008 01:27
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;
?>
26-May-2008 07:37
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;
}
?>
23-May-2008 03:54
<?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