PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<dba_synccheckdate>
view the version of this page
Last updated: Sat, 19 Apr 2003

XVIII. Datums- und Zeit-Funktionen

Einf�hrung

Diese Funktionen erm�glichen es Ihnen, Datums- und Zeitangaben vom Server, auf dem PHP l�uft, abzufragen. Die Ausgabe von Datums- und Zeitangaben kann mit Hilfe dieser Funktionen in unterschiedlichster Weise formatiert werden.

Anmerkung: Beachten Sie bitte, dass diese Funktionen von den lokalen Systemeinstellungen Ihres Servers abh�ngen. Ein besonderes Augenmerk sollten Sie auf Sommer- und Winterzeit und Schaltjahre haben.

Anforderungen

Diese Erweiterung ben�tigt zur Erstellung keine externen Bibliotheken.

Installation

F�r diese Funktionen ist keine Installation erforderlich, diese geh�ren zum Grundbestand von PHP.

Laufzeit Konfiguration

Diese Erweiterung definiert keine Konfigurationseinstellungen in der php.ini.

Resource Typen

Diese Erweiterung definiert keine Resource-Typen.

Vordefinierte Konstanten

Diese Erweiterung definiert keine Konstanten.

Inhaltsverzeichnis
checkdate --  Pr�ft ein gregorianisches Datum auf G�ltigkeit
date -- Formatiert ein(e) angegebene(s) Zeit/Datum
getdate -- Gibt Datums- und Zeitinformationen zur�ck
gettimeofday -- Gibt die aktuelle Zeit zur�ck
gmdate -- Formatiert eine GMT/UTC Zeit- Datumsangabe
gmmktime --  Gibt einen UNIX-Timestamp (Zeitstempel) f�r ein GMT Datum zur�ck
gmstrftime --  Formatiert eine Datum-/Zeitangabe in GMT/UTC-Format entsprechend den lokalen Einstellungen
localtime -- Ermittelt die lokalen Zeitwerte
microtime --  Gibt den aktuellen UNIX-Timestamp/Zeitstempel in Mikrosekunden zur�ck
mktime --  Gibt den UNIX-Timestamp/Zeitstempel f�r ein Datum zur�ck
strftime --  Formatiert eine Zeit-/Datumsangabe nach den lokalen Einstellungen
strtotime --  Wandelt ein beliebiges Datum (englisches Format) in einen UNIX-Zeitstempel (Timestamp) um.
time --  Gibt den gegenw�rtigen UNIX-Timestamp/Zeitstempel zur�ck


User Contributed Notes
Datums- und Zeit-Funktionen
add a note
liv at nospam dot duke dot edu
30-Jan-2000 08:06

If you need to convert a string to a timestamp, versions 3.0.12 and up include strtotime($AString) which uses a yacc-generated parser to generate a timestamp from your user input. It assumes that times are broken up by ":", and that dates use the "/" delimiter and are entered in American (MM/DD/YY) format. am/pm and 24 hour formats are accepted for times.
If the string passed to the function only indicates the time (for example, 12:00am) the timestamp that is generated will contain that time, on the day that the timestamp was generated.
Dates without a time are assumed to be 12:00am. There may be odd behavior related to time-zones, as under certain circumstances the creation of the date and the printing of the date may each assume that the date is in UTC, causing a double correction.
One other thing about strtotime- if your entry is invalid, it'll return -1 to indicate failure.

adm at imexis dot com
21-Feb-2000 06:04

The quick and easy to convert a mysql timestamp is to use the UNIX_TIMESTAMP(field_name) function in mysql when you query the data.  It converts a 14-digit mysql timestamp to a standard unix timestamp.
25-Apr-2000 01:44
Regarding the postings regarding MySQL timestamps, please be aware that there are several MySQL date and time types, as documented at


So, in reference to the above posts, nic_lee's algorhythm works on the MySQL TIMESTAMP type, while jmat's function works on the MySQL DATETIME type -- they are NOT the same!

philip at langelund dot net
02-Aug-2000 08:00

To get the calendar week use: strftime("%W",mktime(0,0,0,$month,$day,$year)); This returns the week number fram a date... -Philip
andy at datanetlink dot com
23-Aug-2000 02:36

This is a little procedure to make time loop under a start time, end time and an interval,I have done the same type thing with the date.
where you see:
echo "Time: $timeh:$timem
\n";
that is my command you can of course call your own functions with the vars,$timeh & $timem.

$timeh = "9"; # Inital Start Time (hours part)
$timem = "30"; # Inital Start Time (mins part)
$end_timeh = "17"; # End Time (hours)
$end_timem = "30"; # End Time (mins)
$interval = "5"; # Interval (mins)


$exit_called = "0";

while ($exit_called == "0")
{
# Pad is a my pre-deffined function add a '0' infront of a var if need be for proper formating.
$timem = pad($timem);
$timeh = pad($timeh);

# command goes here for execution with the time

echo "Time: $timeh:$timem
\n";


if($timeh >= $end_timeh)
{
$exit_called = "1";
}
else
{

# Increment Counters

$timem = $timem + $interval;

if($timem >= "60")
{
$answer = ($timem / 60);
$round_val = round($answer);

if($round_val > $answer)
{
$round_val = ($round_val - 1);

}
$timeh = ($timeh + $round_val);
$round_val = ($round_val * 60);
$timem = ($timem - $round_val);
}
}

}

joachim dot durchholz at halstenbach dot de
29-Aug-2000 02:29

Please note that the calendar week algorithm to apply is country-specific. The first week of a year is usually just a partial week (e.g. Wed-Sun), and the ideas whether this partial week is week 0, week 52 of the previous year, or week 1 depend on social (and business) conventions which can vary across countries; sometimes the definition varies according to whether that partial week has at least 4 days. These conventions may even vary with time; for example, Germany had its weeks from Sunday to Saturday and went to a Monday-to-Sunday cycle some time between ten and twenty years ago.
mpdulle at loyno dot edu
07-Sep-2000 11:18

if you were trying to convert a mysql format date or time string you could always do it in the select statement by using DATE_FORMAT and TIME_FORMAT.
mysql date is 2000-09-07
mysql time is 03:13:27

so...

SELECT DATE_FORMAT(date, '%m.%d.%Y') AS date, TIME_FORMAT(time, '%l.%i %p') AS time

would produce date as September 7, 2000 and time as 3:13 AM.  See
for more date and time formatting specifiers.

teddk at box100 dot com
08-Sep-2000 10:02

There is an an excellent article by Allan Kent on PHP date/time. The full article can be found at:

jon at gaarsmand dot dk
24-Sep-2000 03:53

Need the week of the month?
Heres a function that should do the trick:
/*Call the function as:
weekofmonth(year,month,date)
- either can be int's or strings with leading 0's.
If theres no arguements today will be the arguements.
Output is in the form "YYYYmmw" where "w" represents the week of the month.
*/
function weekofmonth($yr=0,$mn=0,$dd=0) {
if(!($yr>0&$mn>0&$dd>0)) { $yr=date("Y");$mn=date("m");$dd=date("d"); }
 $thisweek = strftime("%U",mktime(0,0,0,$mn,$dd,$yr));
$firstweekofmonth = strftime("%U", mktime(0, 0, 0, date("m", mktime(0, 0, 0, $mn, $dd+(6-date("w", mktime(0, 0, 0, $mn, $dd, $yr))), $yr)), 1,$ yr));
 $thisweek = (abs($thisweek-$firstweekofmonth)>5) ? $firstweekofmonth:$thisweek;
 return date("Y", mktime(0, 0, 0, $mn, $dd+(6-date("w", mktime(0, 0, 0, $mn, $dd, $yr))), $yr)) . date("m", mktime(0, 0, 0, $mn, $dd+(6-date("w",mktime(0, 0, 0, $mn, $dd, $yr))), $yr)) . (($thisweek - $firstweekofmonth) + 1);
}

joey dot garcia at usa dot net
13-Nov-2000 07:13

I was trying to make a Month-At-A-Glance and I finally got it to work so I thought I'd share it too.  What you need to get this to work is the "Day Of The Week Number", i.e., Sunday=1 and the "Number Of Days in the Month".  I also used Allan Kent's Date/Time Column at PHPBuilder to get the required information.  I also added the process I used to the requried information.

Enjoy!

<html>
<head>
<title>Month-At-A-Glance</title>
</head>
<body>
&lt;?php
// *** These are here if you need to calculate the required values ***
// *** Reference Allan Kent's Column on Dates at PHPBuilder.com
//$thismonth =  mktime($hours, $minutes,$seconds ,$month, $day,$year);
//$firstday =  mktime($hours, $minutes,$seconds ,$month, 1,$year);
//$dayofweek=date("D",$thismonth);
//$firstdayofmonth=date("D",$firstday);
//$weekdaynum=array("Sun"=>1, "Mon"=>2, "Tue"=>3, "Wed"=>4, "Thu"=>5, "Fri"=>6, "Sat"=>7);
//$dayNumber=$weekdaynum[$dayofweek];

print "<table width=80% align=center border=1>\n";
print"<tr><th>Sun(1)</th> <th>Mon(2)</th> <th>Tue(3)</th> <th>Wed(4)</th> <th>Thu(5)</th> <th>Fri(6)</th> <th>Sat(7)</th> </tr>";
$daysinmonth=31;//For July 2000 this is 31 days
$daycount=1;
$firstdayofmonth=7;//For July 2000 this is Sat, or day 7
for ($week=1; $week <= 6; $week++){
print"<tr>\n";
  for($day=1; $day <=7; $day++){
       if( ($day >= $firstdayofmonth) || ($week >1) ){
           print"<td height=40px>";
             if ($daycount <= $daysinmonth){
                  print $daycount;
$daycount++;
               }
         print"&nbsp;</td>\n";
       }
      else{
           print"<td height=40px> &nbsp; </td>\n";
       }
  }
print"\n</tr>\n";
}
print"</table>";
?>
</body>
</html>

fancao0515 at 0451 dot com
13-Dec-2000 03:19

You can use Mysql function:

<?php
$data_time="1998-12-31 23:59:59";
$connect_id=mysql_connect('localhost');
$query_id=mysql_query("SELECT DATE_ADD('$data_time',INTERVAL 1 YEAR)",$connect_id);
$data_time=mysql_result($query_id,0);
mysql_close($connect_id);
echo $data_time;
?>

th at definitynet dot com
11-Jan-2001 06:00

I had some problems with dates between mySQL and PHP.  PHP had all these great date functions but I wanted to store a usable value in my database tables. In this case I was using TIMESTAMP(14)  <or 'YYYYMMDDHHMMSS'>.
This is perhaps the easiest way I have found to pull the PHP usable UNIX Datestamp from my mySQL datestamp stored in the tables:

Use the mySQL UNIX_TIMESTAMP() function in your SQL definition string. i.e.

$sql= "SELECT field1, field2, UNIX_TIMESTAMP(field3) as your_date
         FROM your_table
        WHERE field1 = '$value'";

The query will return a temp table with coulms "field1" "Field2" "your_date"

The "your_date" will be formatted in a UNIX TIMESTAMP!  Now you can use the PHP date() function to spew out nice date formats.

Sample using above $sql:
20010111002747  = Date Stored on mySQL table (TIMESTAMP(14))
979172867  = value returned as your_date in sql stmt (UNIX_TIMESTAMP)

if we use $newdate = date("F jS, Y -- g:ia", $row["your_date"]);
  --(after fetching our array from the sql results of course)--

echo "$newdate";              --Will produce:
January 11th, 2001 -- 12:27am

Hope this helps someone out there!

mgidman at corp dot christianity dot com
31-Jan-2001 11:44

in jmat's example above
function mysql_to_epoch ($datestr) {
list($year,$month,$day,$hour,$minute,$second) = split("([^0-9])",$datestr);
return date("U",mktime($hour,$minute,$second,$month,$day,$year));
}

If your $datestr has quotes around it you will need to add a placeholder to the list.
Ex:
list($junk,$year,$month,$day,$hour,$minute,$second) = split("([^0-9])",$datestr);

vincentv at thevoid dot demon dot nl
08-Feb-2001 12:23

Some general date functions.

function sub($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp - $mytime;
}
function add($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {
$mytime = mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
return $timestamp + $mytime;
}
function dayOfWeek($timestamp) {
return intval(strftime("%w",$timestamp));
}
function daysInMonth($timestamp) {
$timepieces = getdate($timestamp);
$thisYear   = $timepieces["year"];
$thisMonth = $timepieces["mon"];

for($thisDay=1;checkdate($thisMonth,$thisDay,$thisYear);$thisDay++);

return $thisDay;
}
function firstDayOfMonth($timestamp) {
$timepieces = getdate($timestamp);
return mktime( $timepieces["hours"],
$timepieces["minutes"],
$timepieces["seconds"],
$timepieces["mon"],
1,
$timepieces["year"]);
}
function monthStartWeekDay($timestamp) {
return dayOfWeek(firstDayOfMonth($timestamp));
}
function weekDayString($weekday) {
$myArray = Array( 0 => "Sun",
1 => "Mon",
2 => "Tue",
3 => "Wed",
4 => "Thu",
5 => "Fri",
6 => "Sat");
return $myArray[$weekday];
}
function stripTime($timestamp) {
$timepieces = getdate($timestamp);
return mktime( 0,
0,
0,
$timepieces["mon"],
$timepieces["mday"],
$timepieces["year"]);
}
function getDayOfYear($timestamp) {
$timepieces = getdate($timestamp);
return intval($timepieces["yday"]);
}
function getYear($timestamp) {
$timepieces = getdate($timestamp);
return intval($timepieces["year"]);
}
function dayDiff($timestamp1,$timestamp2) {
$dayInYear1 = getDayOfYear($timestamp1);
$dayInYear2 = getDayOfYear($timestamp2);
return ((getYear($dayInYear1)*365 + $dayInYear1) -
(getYear($dayInYear2)*365 + $dayInYear2));
}

hope they are usefull to you.

- Vincent

shinelight at excite dot com
18-Feb-2001 10:39

To use dates and times in ODBC-compliant databases (including MySQL), you can use the timestamp format:  {ts 'yyyy-mm-dd hh:mm:ss'}.  {ts '1899-12-30 00:00:00'} is the earliest date and time that can be inserted into a database using this format.  This is perhaps the most portable and supported syntax out there by most databases (however, a good database will support several methods for date/time objects).
mmotley at la-mirada dot nospam dot net
17-Apr-2001 11:42

Some useful functions:

/* dayofweek() will return the day of the week a given date falls. 0=Sunday, 1=Monday, etc. */

function dayofweek($day,$month,$year) {

/* Check date for validity */
       if (!checkdate($month,$day,$year))
              return -1;

       $a=(int)((14-$month) / 12);
      $y=$year-$a;
       $m=$month + (12*$a) - 2;

      $retval=($day + $y + (int)($y/4) - (int)($y/100) + (int)($y/400) + (int)((31*$m)/12)) % 7;
       return $retval;
}

/* phpdow_mod is a mod function that deals with negative numbers properly, used by the nthDayOfMonth function below. */

function phpdow_mod($a,$b) {
       if ($a <= 0)
               return (int)phpdow_mod($b-abs($a),$b);
       else
              return (int)($a%$b);
}

/*
* nthDayOfMonth($n,$dow,$month,$year) will compute the Nth day of the given
* month.  For example, the first Monday in April 2001.
*
* Parameters:
*  $n - the Nth day you want, i.e. 2 for 2nd
*  $dow - The day of week you want, 0=Sunday, 1=Monday, etc. [0-6]
*  $month - The month you want [1-12]
*  $year - The full year [like 2001]
*
* Returns:
*  The date, in the month you passed, that fits the criteria.
*  or..
*    -1 = invalid date
*    -2 = There is no Nth day of that month, like no 5th Tuesday
*         of the specified month
*/

function nthDayOfMonth($n,$dow,$month,$year) {

       /* Check the date */
       if ($month > 12)
               return -1;
     if ($dow > 6)
               return -1;

       /* Valid Nth day, should be no more than 5 */
       if (($n <= 0) || ($n > 5))
               return -1;

       $retval = (7*$n)-6+phpdow_mod($dow-dayofweek(1,$month,$year),7);

/* Sanity check */
       if (!checkdate($month,$retval,$year))
             return -2;
       return $retval;
}

william at ScriptingBiz dot Com
19-Aug-2001 02:06

[Editor's note: a simpler and more efficient solution is to use the UNIX_TIMESTAMP(fieldname) function in MySQL when performing a SELECT query. This is documented in the MySQL manual.]

Ever use the mysql column type of "timestamp"?  It crams all the digits fo the date/time togeter and makes it hard to deal with.  Here's a solution:

#####################################################################
// myts_date is identical to date except that it takes a
// mysql timestamp instead of epoch seconds for an argument
// written by William Janoch - [email protected]
//
// I write "clever little" code that never
// complains when the sky isn't falling.
// /* see also "chicken little" code */

function myts_date($format,$mytimestamp)
{
  $month  = substr($mytimestamp,4,2);
   $day    = substr($mytimestamp,6,2);
   $year   = substr($mytimestamp,0,4);

   $hour   = substr($mytimestamp,8,2);
   $min    = substr($mytimestamp,10,2);
   $sec    = substr($mytimestamp,12,2);

   $epoch  = mktime($hour,$min,$sec,$month,$day,$year);
   $date   = date ($format, $epoch);
   return $date;
}
#####################################################################

andrew at sonicmedia dot net
15-Sep-2001 10:50

[Editor's Note: Yes, these are all documented in the date() function page]

PM or AM = A
Seconds = s
Minuts = i
Hours = h
Year = Y
Month = F
Month (16th) = dS
Day = 1

rupert at ditzed dot org
18-Oct-2001 12:24

A major problem I have run into regarding timestamps is the limitation implied by the UNIX timestamp range, which starts at 12:00am on 1st January 1970, and ends some time in 2030 (I think).
Anything outside this range returns a -1 from the mktime() function.

florent at kzar.net
25-Oct-2001 07:26

The Latest date available for timestamp related functions (mktime...) is:
January 19 th, 2038, 3:23 AM and 27 seconds (or 2147480607 Unix timestamp).

php-contrib at i-ps dot nospam dot net
30-Jan-2002 01:07

Someone may find this info of some use:

Rules for calculating a leap year:

1) If the year divides by 4, it is a leap year (1988, 1992, 1996 are leap years)
2) Unless it divides by 100, in which case it isn't (1900 divides by 4, but was not a leap year)
3) Unless it divides by 400, in which case it is actually a leap year afterall (So 2000 was a leap year).

In practical terms, to work out the number of days in X years, multiply X by 365.2425, rounding DOWN to the last whole number, should give you the number of days.

The result will never be more than one whole day inaccurate, as opposed to multiplying by 365, which, over more years, will create a larger and larger deficit.

php-contrib at i-ps dot nospam dot net
30-Jan-2002 01:26

Where possible, use the database built-in time and date functions, as they often are not affected by the UTS limitation.

For example: I tested MySQL "dayname" with "1978-08-09" (my birthdate), which returned "Wednesday", which is correct.
I also tried "1500-08-09", which returned Thursday. I have no actual way of verifying this, as no other time functions on my PC go back that far, though I double-checked it on a Linux server, and that returned the same day.

mindaugas at roventa dot lt
18-Feb-2002 10:31

Some lines about LeapYear and day count of month:

   function mod($a,$b)
   {
   $x1=(int) abs($a/$b);
   $x2=$a/$b;
  return $a-($x1*$b);    
   }    

   function IsLeapYear($dt)
   {
   $y=$dt["year"];
  $bulis=((mod($y,4)==0) && ((mod ($y,100)<>0) || (mod($y,400)==0)));
   return $bulis;
   }

   function daycount($dt)
   {
   $dc_year=$dt["year"];
  $dc_month=$dt["mon"];
  $dc_day=$dt["mday"];
switch ($dc_month)
{
case 1:
case  3:
case  5:
case  7:
case  8:
case 10:
case 12:
       return 31;
break;
case  4:
case 6:
case  9:
case 11:
       return 30;
break;
case 2:
if (IsLeapYear($dt)) { return 28; } else { return 29; };
break;
}
   }

spaula at takas dot lt
08-Mar-2002 01:37

Warning!
You have to be VERY carefull with things like:
$same_time_tomorrow = time() + 60*60*24;

It's because:
1. Mar-24 23:30 + 24 hours = Mar-26 00:30
2. Oct-28 00:30 + 24 hours = Oct-28 23:30

This occurs because of the daylight saving time shifts.

m dot bouquet at wanadoo dot fr
28-Mar-2002 03:21

Corrections about add months of "Some general date functions" in these notes

function sub($timestamp, $seconds,$minutes,$hours,$days,$months,$years)
{
$mytime =
mktime(1+$hours,0+$minutes,0+$seconds,1,1+$days,1970+$years);
$times=$timestamp - $mytime;
if ($months!=0)
{
$year=date('Y',$times)*12+date('n',$times)*1;
$year2=$year-$months;
$year3=floor($year2/12);
$month3=abs($year2-$year3*12);
$times=mktime (date('H',$times),date('i',$times),date('s',$times),
$month3,date('j',$times),date('Y',$times));
}
return $times;
}

function add($timestamp, $seconds,$minutes,$hours,$days,$months,$years) {

$mytime =
mktime(1+$hours,0+$minutes,0+$seconds,1+$months,1+$days,1970+$years);
$times=$timestamp + $mytime;
if ($months!=0)
{
$year=date('Y',$times)*12+date('n',$times)*1;
$year2=$year+$months;
$year3=floor($year2/12);
$month3=abs($year2-$year3*12);
$times=mktime (date('H',$times),date('i',$times),date('s',$times),
$month3,date('j',$times),date('Y',$times));
}
return $times;
}

mwedgwood at ILUVSPAMhotmail dot com
31-Mar-2002 09:24

In vincentv's examples, you should use gmmktime instead of mktime for portability across time zones. For example:

function DateSub($timestamp, $unit, $amount) {
// Possible $units are: "hr", "min", "sec",
//         "mon", "day", or "yr"
// $amount should be an integer
   $delta_vars = array("hr"=>0, "min"=>0,
"sec"=>0, "mon"=>1,
"day"=>1,"yr"=>1970);
  $delta_vars[$unit] += $amount;
   $delta = gmmktime($delta_vars["hr"],
$delta_vars["min"],
$delta_vars["sec"],
$delta_vars["mon"],
$delta_vars["day"],
$delta_vars["yr"]);
  return $timestamp - $delta;
}

emerix at rol dot ro
15-Jul-2002 04:50

The simplest function for formating a timestamp difference.

function date_diff ( $date1, $date2 ) {
  $some=date("z \\d\\a\\y\\s H\\h i\\m s\\s",$data-7200);
return $some;
}

Where $date1 and $date2 are the timestamps you want.

Ex. date_diff(1024681353, 1023917859);
Will output :
8 days 20h 04m 54s

If you want smater output you should have a
switch(date("z", $date)) {
...
}
in order to avoid "1 days" ...

nightowl at NOS-PA-M dot uk2 dot net
30-Jul-2002 05:59

I wanted to find all records in my database which match the current week (for a call-back function). I made up this function to find the start and end of the current week :

function week($curtime) {

$date_array = getdate (time());
$numdays = $date_array["wday"];

$startdate = date("Y-m-d", time() - ($numdays * 24*60*60));
$enddate = date("Y-m-d", time() + ((7 - $numdays) * 24*60*60));

$week['start'] = $startdate;
$week['end'] = $enddate;

return $week;

}

jemore dot at dot m6net dot dot dot fr at nospam dot com
22-Aug-2002 11:42

I have write a library to manipulate date and time as a TDateTime-like Delphi object.
My new DateTime format is a float value, where the integer part is the number of day since a given date (1/1/1899), and the fractional part represents the number of milliseconds since 0h0m0s of this day.
So it is easy to compare, add, multiply dates, and there is no 1970-2038 limit.
You can convert DateTime number to unix epoch and mysql DATETIME type.
url is :

asg at ftpproxy dot org
24-Sep-2002 08:23

If you like to have the last day of the current month, try this oneliner:

$lastday = strftime ("%d.%m.%Y", (mktime (0,0,0,(date(m)+1),0,(date(Y)))));

-

albaity at php4web dot com
25-Oct-2002 05:59

To get arabic date use this function

function HejriDate($format, $time) {

/*
Hejri Date Function
Calculation is written by Khaled Mamdouh www.vbzoom.com
Enhanced and developed by Salah [email protected] on 30-07-2002
(please keep credit comments)

Example:
          echo  HejriDate("D, d-M-y", time());
                // will output  �����, 12-����-1423
*/

$ArbMonths = array("����",
        "���",
        "���� ���",
         "���� ����",
        "���� ���",
        "���� ����",
        "���",
        "�����",
        "�����",
        "����",
        "�� ������",
        "�� �����");

$ArbDays = array("Sat"=>"�����",
        "Sun"=>"�����",
        "Mon"=>"�������",
        "Tus"=>"��������",
        "Wed"=>"��������",
        "Thu"=>"������",
        "Fri"=>"������");

$TDays=round($time/(60*60*24));
$HYear=round($TDays/354.37419);
$Remain=$TDays-($HYear*354.37419);
$HMonths=round($Remain/29.531182);
$HDays=$Remain-($HMonths*29.531182);
$HYear=$HYear+1389;
$HMonths=$HMonths+10;
$HDays=$HDays+23;

if ($HDays>29.531188 && round($HDays)!=30) {
$HMonths=$HMonths+1;
 $HDays=Round($HDays-29.531182);
} else {
$HDays=Round($HDays);
}

$DayName=date("D", $DayName);
$HDayName=$ArbDays[$DayName];
$HMonthName=$ArbMonths[$HMonths-1];

if ($format) {
     $HDate = str_replace("d","$HDays", $format);
     $HDate = str_replace("D","$HDayName", $HDate);  
    $HDate = str_replace("m","$HMonths", $HDate);  
    $HDate = str_replace("M","$HMonthName", $HDate);  
     $HDate = str_replace("y","$HYear", $HDate);
     $HDate = str_replace("Y","$HYear", $HDate);  
     $HDate = str_replace("h",date("h", $time), $HDate);  
     $HDate = str_replace("H",date("H", $time), $HDate);  
    $HDate = str_replace("i",date("i", $time), $HDate);  
     $HDate = str_replace("s",date("s", $time), $HDate);  
     $HDate = str_replace("i",date("i", $time), $HDate);  
    $HDate = str_replace("a",date("a", $time), $HDate);  
      $HDate = str_replace("A",date("A", $time), $HDate);  
      $HDate = str_replace("am",date("�", $time), $HDate);  
     $HDate = str_replace("pm",date("�", $time), $HDate);  
} else {
   $HDate="$HDays-$HMonths-$HYear";
}
return $HDate;
}

writen by prokhaled And enhanced by Visualmiind



eric at nitrateNO_SPAM dot nl
09-Dec-2002 12:16

Here is a quick example of how to iterate through all days
between 2 dates (with a adjustable increment)
---------------------------------------------------------
//make time stamps from our start & end dates
$start_time = mktime(0,0,0,$start_month,$start_day,$start_year);
$end_time = mktime(0,0,0,$end_month,$end_day,$end_year);

//find the number of days between start_time & end_time
$days = ($end_time - $start_time) / (24 * 3600);
//we want to count the days including the first ..
$days++;

//select a 1 week interval ..
$inc=7;

//find all days (actually periods since we use a increment)
for ($i=0;$i<$days;$i+=$inc)
{
 //calculate start & end of period using some magic of mktime :)
 $start_date = date("Y-m-d", mktime(0,0,0,$start_month,$start_day+$i,$start_year));
 $end_date = date("Y-m-d", mktime(0,0,0,$start_month,$start_day+$i+$inc-1,$start_year));  
//print it all ...
 print("Period start:" . $start_date . "\n");
 print("Period end: " . $end_date . "\n");
}

visualmind at php dot net
25-Dec-2002 07:49

Here's a new function for Hejri (Hijri) date conversion, It has a better flawless calculation than the previous posted function and it's implemented to be an official alternative for the php DATE function which returns Arabic Translated date and optionally Hejri converted.
Note: to view arabic titles correctly change view-encoding to Arabic-Windows (windows-1256)

function arabicDate($format, $timestamp) {
/*
  written by Salah Faya ([email protected])
$format:
  [*]hj|ar|en:[jdl][Fmn][Yy][Aa]  (php.date function handles the rest chars)
  * will add <span dir=rtl lang=ar-sa>..</span>
  examples:
  echo arabicDate('hj:l d-F-Y ��', time());  
  echo arabicDate('ar:l d/F - h:iA', time());
*/
$format=trim($format);
if (substr($format,0,1)=='*') {
               $use_span=true;
$format=substr($format,1);
       } else $use_span=false;
$type=substr($format,0,3);

$arDay = array("Sat"=>"�����", "Sun"=>"�����", "Mon"=>"�������", "Tue"=>"��������",
"Wed"=>"��������", "Thu"=>"������", "Fri"=>"������");
$ampm=array('am'=>'�����','pm'=>'����');
list($d,$m,$y,$dayname,$monthname,$am)=explode(' ',date('d m Y D M a', $timestamp));
if ($type=='hj:') {
if (($y>1582)||(($y==1582)&&($m>10))||(($y==1582)&&($m==10)&&($d>14))) {
$jd=ard_int((1461*($y+4800+ard_int(($m-14)/12)))/4);
$jd+=ard_int((367*($m-2-12*(ard_int(($m-14)/12))))/12);
$jd-=ard_int((3*(ard_int(($y+4900+ard_int(($m-14)/12))/100)))/4);
$jd+=$d-32075;
} else {
$jd = 367*$y-ard_int((7*($y+5001 + ard_int(($m-9)/7)))/4) + ard_int((275*$m)/9)+$d+1729777;
}
$l=$jd-1948440+10632;
$n=ard_int(($l-1)/10631);
$l=$l-10631*$n+355; // Correction: 355 instead of 354
$j=(ard_int((10985-$l)/5316)) * (ard_int((50*$l)/17719)) + (ard_int($l/5670)) * (ard_int((43*$l)/15238));
$l=$l-(ard_int((30-$j)/15)) * (ard_int((17719*$j)/50)) - (ard_int($j/16)) * (ard_int((15238*$j)/43))+29;
$m=ard_int((24*$l)/709);
$d=$l-ard_int((709*$m)/24);
$y=30*$n+$j-30;
$format=substr($format,3);
$hjMonth = array("����", "���", "���� ���", "���� ����",
"���� ���", "���� ����", "���", "�����", "�����", "����", "�� ������", "�� �����");
$format=str_replace('j', $d, $format);
$format=str_replace('d', str_pad($d,2,0,STR_PAD_LEFT), $format);
$format=str_replace('l', $arDay[$dayname], $format);
$format=str_replace('F', $hjMonth[$m-1], $format);
$format=str_replace('m', str_pad($m,2,0,STR_PAD_LEFT), $format);
$format=str_replace('n', $m, $format);
$format=str_replace('Y', $y, $format);
$format=str_replace('y', substr($y,2), $format);
$format=str_replace('a', substr($ampm[$am],0,1), $format);
$format=str_replace('A', $ampm[$am], $format);
} elseif ($type=='ar:') {
$format=substr($format,3);
$arMonth=array("Jan"=>"�����", "Feb"=>"������","Mar"=>"����", "Apr"=>"�����", "May"=>"����",
"Jun"=>"�����", "Jul"=>"�����", "Aug"=>"�����", "Sep"=>"������", "Oct"=>"������",
"Nov"=>"������", "Dec"=>"������");
$format=str_replace('l', $arDay[$dayname], $format);
$format=str_replace('F', $arMonth[$monthname], $format);
$format=str_replace('a', substr($ampm[$am],0,1), $format);
$format=str_replace('A', $ampm[$am], $format);
       }
$date = date($format, $timestamp);
if ($use_span) return '<span dir="rtl" lang="ar-sa">'.$date.'</span>';
else return $date;
}

function ard_int($float) {
      return ($float < -0.0000001) ? ceil($float-0.0000001) : floor($float+0.0000001);
}

brighn (a) yahoo (.) com
03-Jan-2003 04:46

I needed a function that determined the last Sunday of the month. Since it's made for the website's "next meeting" announcement, it goes based on the system clock; also, if today is between Sunday and the end of the month, it figures out the last Sunday of *next* month. lastsunday() takes no arguments and returns the date as a string in the form "January 26, 2003". I could probably have streamlined this quite a bit, but at least it's transparent code. =)

 /* The two functions calculate when the next meeting will
    be, based on the assumption that the meeting will be on
    the last Sunday of the month. */  

 function getlast($mon, $year) {
   $daysinmonth = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
   $days = $daysinmonth[$mon-1];
   if ($mon == 2 && ($year % 4) == 0 && (($year % 100) != 0 ||
   ($year % 400) == 0)) $days++;
  if ($mon == 2 && ($year % 4) == 0 && ($year % 1000) != 0) $days++;
   $lastday = getdate(mktime(0,0,0,$mon,$days,$year));
  $wday = $lastday['wday'];
   return getdate(mktime(0,0,0,$mon,$days-$wday,$year));
 }

 function lastsunday() {
   $today = getdate();
   $mon = $today['mon'];
  $year = $today['year'];
   $mday = $today['mday'];
   $lastsun = getlast($mon, $year);
   $sunday = $lastsun['mday'];
   if ($sunday < $mday) {
     $mon++;
     if ($mon = 13) {
     $mon = 1;
       $year++;
     }
     $lastsun = getlast($mon, $year);
     $sunday = $lastsun['mday'];
   }
  $nextmeeting = getdate(mktime(0,0,0,$mon,$sunday,$year));
   $month = $nextmeeting['month'];
   $mday = $nextmeeting['mday'];
   $year = $nextmeeting['year'];
   return "$month $mday, $year";
}

zan at stargeek dot com
03-Jan-2003 08:18

a calendar making script that uses the date/time functions is exemplified at
NO dot php at SPAM dot typetango dot com
13-Jan-2003 10:52

// returns person's age in years
// accepts person's birthday in 'Y-m-d' format

function find_age($birthday)
{ list($byear, $bmonth, $bday) = explode('-', $birthday);
list($cyear, $cmonth, $cday) = explode('-', date('Y-m-d'));
$cday -= $bday;
$cmonth -= $bmonth;
$cyear -= $byear;
if($cday < 0)
$cmonth--;
if($cmonth < 0)
$cyear--;
return $cyear;
}

zan at stargeek dot com
24-Jan-2003 04:49

an update to my earlier webcalendar funciton this is a class that uses a table full of start and end dates to generate a webcalendar
jlim at natsoft dot com dot my
26-Jan-2003 08:26

SUPPORT FOR DATES OUTSIDE 1901-2038

PHP native date functions use integer timestamps
for computations. Because of this, dates are restricted
to the years 1901-2038 on Unix and 1970-2038 on Windows
due to integer overflow for dates beyond those years.
This has been frustrating for me, so i developed this
library to overcome these limitation by replacing the
native function's signed integers (normally 32-bits)
with PHP floating point numbers (normally 64-bits) when
necessary.

This has been frustrating for me, so i developed this
library to overcome these limitation by replacing the
native function's signed integers (normally 32-bits)
with PHP floating point numbers (normally 64-bits)
when necessary.

This library supports dates from 100 A.D. to billions of
years in the future.

Download:

To use, simply replace

getdate()  with  adodb_getdate()
date()    with  adodb_date()
gmdate()   with  adodb_gmdate()
mktime()   with  adodb_mktime()
gmmktime() with adodb_gmmktime()

Performance

For high speed, this library uses the native date functions
where possible, and only switches to PHP code when the dates
fall outside the 32-bit signed integer range.

jlim at natsoft dot com dot my
26-Jan-2003 08:28

For a date() function that supports dates outside the range 1901 and 2038 (by using floats when needed) see adodb_date( ) in


balin
16-Feb-2003 08:23

this function count days between $start and $end dates in mysql format (yyyy-mm-dd)
if one of paramters is 0000-00-00 will return 0
$start date must be less then $end
<?
//For Count Days
function count_days($start, $end)
{
   if( $start != '0000-00-00' and $end != '0000-00-00' )
   {
       $timestamp_start = strtotime($start);
       $timestamp_end = strtotime($end);
      if( $timestamp_start >= $timestamp_end ) return 0;
      $start_year = date("Y",$timestamp_start);
       $end_year = date("Y", $timestamp_end);
       $num_days_start = date("z",strtotime($start));
       $num_days_end = date("z", strtotime($end));
       $num_days = 0;
      $i = 0;
       if( $end_year > $start_year )
       {
         while( $i < ( $end_year - $start_year ) )
          {
            $num_days = $num_days + date("z", strtotime(($start_year + $i)."-12-31"));
             $i++;
          }
       }
        return ( $num_days_end + $num_days ) - $num_days_start;
   }
   else
   {
        return 0;
   }
}
?>

garyc at earthling dot net
19-Mar-2003 03:08

I needed to calculate the week number from a given date and vice versa, where the week starts with a Monday and the first week of a year may begin the year before, if the year begins in the middle of the week (Tue-Sun). This is the way weekly magazines calculate their issue numbers.

Here are two functions that do exactly that:

Hope somebody finds this useful.

Gary

/*  w e e k n u m b e r -------------------------------------- //
weeknumber returns a week number from a given date (>1970, <2030)
Wed, 2003-01-01 is in week 1
Mon, 2003-01-06 is in week 2
Wed, 2003-12-31 is in week 53, next years first week
Be careful, there are years with 53 weeks.
// ------------------------------------------------------------ */

function weeknumber ($y, $m, $d) {
$wn = strftime("%W",mktime(0,0,0,$m,$d,$y));
$wn += 0; # wn might be a string value
$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
if ($firstdayofyear["wday"] != 1) # if 1/1 is not a Monday, add 1
$wn += 1;
return ($wn);
} # function weeknumber

/*  d a t e f r o m w e e k ---------------------------------- //
From a weeknumber, calculates the corresponding date
Input: Year, weeknumber and day offset
Output: Exact date in an associative (named) array
2003, 12, 0: 2003-03-17 (a Monday)
1995,  53, 2: 1995-12-xx
...
// ------------------------------------------------------------ */

function datefromweek ($y, $w, $o) {

$days = ($w - 1) * 7 + $o;

$firstdayofyear = getdate(mktime(0,0,0,1,1,$y));
if ($firstdayofyear["wday"] == 0) $firstdayofyear["wday"] += 7;
# in getdate, Sunday is 0 instead of 7
$firstmonday = getdate(mktime(0,0,0,1,1-$firstdayofyear["wday"]+1,$y));
$calcdate = getdate(mktime(0,0,0,$firstmonday["mon"], $firstmonday["mday"]+$days,$firstmonday["year"]));

$date["year"] = $calcdate["year"];
$date["month"] = $calcdate["mon"];
$date["day"] = $calcdate["mday"];

return ($date);

} # function datefromweek

you NOSPAM don't need 2 know ETC
24-Mar-2003 02:17

EXCEL DATES TO UNIX TIMESTAMPS
----------------------------

I get a lot of dates which are sent to me in those dastardly Excel spreadsheet things. For example, the date 15 April 1976, Excel stores as 27865.

I convert these to UNIX timestamps using the little function below.

<?
function xl2timestamp($xl_date)
{
$timestamp = ($xl - 25569) * 86400;
return $timestamp;
}
?>

Sascha at Sonicdelay dot de
23-Apr-2003 03:24

After having some trouble checking deltas between DB-Timestamps and my server time, I use this to convert something like a MySQL-Timestamp(14) to the UNIX format:

$Timestamp="20030423145607";

$UnixTimestamp = strtotime (substr_replace (substr (substr ($Timestamp,0,2).chunk_split (substr ($Timestamp,2,6),2,"-").chunk_split (substr ($Timestamp,8),2,":"),0,19)," ",10,1));

->1051102567

add a note

<dba_synccheckdate>
 Last updated: Sat, 19 Apr 2003
show source | credits | mirror sites 
Copyright © 2001-2003 The PHP Group
All rights reserved.
This mirror generously provided by: /
Last updated: Mon May 12 21:12:21 2003 CEST