PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links 
search for in the  
previousdba_synccheckdatenext
Last updated: Tue, 09 Jul 2002
view the printer friendly version or the printer friendly version with notes or change language to English | Brazilian Portuguese | Chinese | Czech | Dutch | Finnish | German | Hungarian | Italian | Japanese | Korean | Polish | Romanian | Russian | Spanish | Swedish | Turkish

XVIII. Dates et heures

Table des mati�res
checkdate -- Valide une date/heure.
date -- Formate une date/heure locale
getdate -- Retourne la date/heure
gettimeofday -- Retourne l'heure actuelle
gmdate -- Formate une date/heure GMT/CUT.
gmmktime -- Retourne le timestamp UNIX d'une date GMT.
gmstrftime --  Formate une date/heure GMT/CUT en fonction des param�trages locaux.
localtime -- Lit l'heure locale
microtime --  Retourne le timestamp UNIX actuel avec microsecondes.
mktime --  Retourne le timestamp UNIX d'une date.
strftime --  Formate une date/heure locale avec les options locales.
strtotime --  Transforme un texte anglais en timestamp
time --  Retourne le timestamp UNIX actuel.
User Contributed Notes
Dates et heures
add a note about notes
[email protected]
30-Jan-2000 07: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.

[email protected]
18-Feb-2000 04:17

If you have a date format that's in days (with the decimal part being fractional) you just need to find the number of days between the beginning of the pc date and the epoch (set the clock that works off of pc time to 1/1/70 to see how many days it is), subtract that number from the pc date, and multiply by the number of seconds in a day (60*60*24). That should work.
[email protected]
21-Feb-2000 05: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 12: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!

[email protected]
09-Jul-2000 03:11

To get the number of days between two dates Get the UNIX timestamp for the two days, using time for the current timestamp and mktime to generate others. Since timestamps are in seconds from Epoch time you can simply subtract the two and Multiply by 60 * 60 * 24 to get the number of days.
[email protected]
02-Aug-2000 07: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
[email protected]
23-Aug-2000 01: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);
}
}

}

[email protected]
29-Aug-2000 01: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.
[email protected]
07-Sep-2000 10: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.

[email protected]
08-Sep-2000 09:02

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

[email protected]
24-Sep-2000 02: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);
}

[email protected]
13-Nov-2000 06: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>

[email protected]
16-Nov-2000 03:58

need the age of a person or how many years passed since a certain date?
this should work, also works when the person is born on Feb, 29th

function get_age($birthday) {
if (!ereg ("([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})", $birthday, $regs)) { return false;} // Geb-Datum nicht korrekt �bergeben
$age = date("Y") - $regs[1];
if ($regs[2] > date("m")) {$age--;}
elseif ($regs[2] == date("m")) {
if ($regs[3] > date("d")) {$age--;}
}
return $age;
} // Ende function get_age

[email protected]
26-Nov-2000 04:38

Function 'wend'
Pass to: A number representing the week of the year ($wkno).
Uses: $t - the current time and return value
$dx - the current day of the week (0-6)
$woy - the current week in the year
DAY - The number of seconds in a day
WEEK - The number of seconds in a week
MAXDAY - The max day-of-the-week num.

The bulk of the work is performed by the line immediately preceeding the 'return $t;'.

First of all the weekending timestamp is defined for the current week '((MAXDAY - $dx) * DAY) ' it is then adjusted for the week of the year that you wish to determine weekending date for by the '(($wkno - $woy) * WEEK)' term.

Returns: A timestamp ($t) for the weekending (a Saturday) relating to the week number passed the date is then generated in the main program using a line like..... '$wkending = date("d/m/y",(wend($wk)));'

function wend($wkno)
{
define ("DAY", "86400");
define ("WEEK", "604800");
define ("MAXDAY", "6");
$t = time();
$dx = date("w");
$woy = exec('date +%U');
$t += (((MAXDAY - $dx) * DAY) + (($wkno - $woy) * WEEK));
return $t;
}

[email protected]
13-Dec-2000 02: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;
?>

[email protected]
11-Jan-2001 05: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!

[email protected]
31-Jan-2001 10: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);

[email protected]
07-Feb-2001 11: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

[email protected]
18-Feb-2001 09: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).
[email protected]
17-Apr-2001 10: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;
}

[email protected]
18-May-2001 04:52

This function will return the unix-timestamp of the specified date.

function dateToTime($date, $blnUs = false)
{
$blnUs ? list($m,$d,$y)=split('[.-/,]',$date) : list($d,$m,$y)=split('[.-/,]',$date);

return mktime(0,0,0,$m,$d,$y);
}

The string containing the date can be of any digit-based format:
d.m.yy, dd/m/yyyy,....

If the 2nd parameter is set to true the function also handles us - formatted dates (m-d-yyyy, mm.d.yyyy,...)

[email protected]
22-Jun-2001 01:57

For add 30 day to a date from a form.

Page1
<INPUT TYPE='text' NAME='codea' maxlength='4' size=4 value=''>-
<INPUT TYPE='text' NAME='codeb' maxlength='2' size=2 value=''>-
<INPUT TYPE='text' NAME='codec' maxlength='2' size=2 value=''>

Page2
<?
$encoded_date = "$codea-$codeb-$codec";
$poll = "$codea/$codeb/$codec";
$encoded_datc = date("Y m d",$data + 2592000);
echo " $encoded_datc ";
?>

[email protected]
17-Jul-2001 01:42

For those who want portable timestamps between ODBC-compliant datasources, use the following format:

{ts '1890-12-30 00:00:00'}
(The above timestamp is associated as the "zero-base" in many datasources)

So, to use the above timestamp in a query, do something like this:

INSERT INTO MyTable (Table_ID, Table_TS)
VALUES (1, {ts '1890-12-30 00:00:00'})

If you just want to use the date, use this:

{d '1890-12-30'}

Or just the time:

{t '00:00:00'}


That should ease someone's pain. Instead of running a query against the database for a timestamp (which is generally slow), you can generate one real-time. For instance:

echo "{ts '".gmdate("Y-m-d h:i:s", time())."'}";

It is just a matter of modifying the above code for whatever queries you need to perform.


MacTruck

(BTW, if you can't tell, those are braces '{}' rather than parenthesis '()' surrounding the timestamp...they are also known as "escape characters" in ODBC terminology).

[email protected]
31-Jul-2001 12:07

In addition to [email protected]'s example. I needed a quick simple function that added 30 days to a date for a PHP Site running 3.0.7.

I came up with,

// -----------------------------
// -- Add thirty days --
// -----------------------------

$timenow = time();
$plusthirtydays = date("d-m-Y", $timenow + 2592000);

// -----------------------------

$plusthirtydays now contains your date, 30 days later than current.

You can change the timestamp if you wish to increase the number of days etc. And you can select whether to add or subtract.

Alternatively, I believe strtotime() is a good function to do this job, available in 3.0.12

Its not much, but I like it :),
Amadiere

[email protected]
16-Aug-2001 11:20

Simple addDays function: add $days to a typical $datetime value (see return).

function addDays($datetime, $days) {
$dd = strtotime($datetime);
$dd2 = $dd + 3600*24*$days;
return date("Y-m-d H:i:s", $dd2);
}

[email protected]
19-Aug-2001 01: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;
}
#####################################################################

[email protected]
31-Aug-2001 05:21

For all of us who speak Spanish, here is a function that adds a determinated amount of days to a given date... the format for the incoming and the outgoing date is: DD-MM-YYYY
-----------------------
Para todos quienes hablamos espa�ol, he aqu� una funci�n que agrega una determinada cantidad de d�as a una fecha dada... el formato tanto para la fecha de entrada como para la de salida es: DD-MM-YYYY

function agregaDias($fecha, $dias) {
$t1 = mktime(0,0,0,substr($fecha,3,2),substr($fecha,0,2),substr($fecha,6,4));
$t2 = $t1 + 3600*24*$dias;
return date("d-m-Y", $t2);
}

[email protected]
15-Sep-2001 09:50

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

[email protected]
09-Oct-2001 08:06

Simple way to calculate the days until something (looks like one of the entries above suggest multiplying instead of dividing!). This'll return a nice number formatted to two (2) decimal places.

$today = time();
$daysuntil = ((($timestamp - $today) / 60) / 60) / 24;
$daysuntil = number_format($daysuntil,2);

[email protected]
18-Oct-2001 11: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 06: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).

[email protected]
04-Nov-2001 11:41

the no of seconds in one day is 86400

so to round a unix timestamp down to the nearest day, use

$time = floor(time()/86400)*86400

[email protected]
05-Dec-2001 12:38

For Brazilian users:

Remember that the banking ticket uses a sequencial date which begins on October 1st, 1997.

Lembre-se que o fator de vencimento nos boletos bancarios e' uma data sequencial, cujo dia 1 e' na verdade 7/10/1997.

[email protected]
22-Jan-2002 02:14

I probably didn't need to write this but it was fun anyway. This function will work out the difference between two timestamps and process the number of seconds into a text string broken down into years,weeks,minutes and seconds. Years aren't accurate since it doesn't take into account leap years.

function get_time_diff($start,$end){ // Calculates difference in seconds and returns text string.
$diff = ($end-$start);
if($diff<60){
$sec = $diff;
}
else{
if($diff<3600){
$min = floor($diff/60);
$sec = $diff-(60*$min);
}
else{
if($diff<86400){
$hour = floor($diff/3600);
$min = floor(($diff-($hour*3600))/60);
$sec = (($diff-($hour*3600)-(60*$min)));
}
else{
if($diff<604800){
$day = floor($diff/86400);
$hour = floor(($diff-($day*86400))/3600);
$min = floor(($diff-($day*86400)-($hour*3600))/60);
$sec = (($diff-($day*86400)-($hour*3600)-(60*$min)));
}
else{
if($diff<31536000){
$week = floor($diff/604800);
$day = floor(($diff-($week*604800))/86400);
$hour = floor(($diff-($week*604800)-($day*86400))/3600);
$min = floor(($diff-($week*604800)-($day*86400)-($hour*3600))/60);
$sec = (($diff-($week*604800)-($day*86400)-($hour*3600)-(60*$min)));
}
else{
$year = floor($diff/31536000);
$week = floor(($diff-($year*31536000))/604800);
$day = floor(($diff-($year*31536000)-($week*604800))/86400);
$hour = floor(($diff-($year*31536000)-($week*604800)-($day*86400))/3600);
$min = floor(($diff-($year*31536000)-
($week*604800)-($day*86400)-($hour*3600))/60);
$sec = (($diff-($year*31536000)
-($week*604800)-($day*86400)-($hour*3600)
-(60*$min)));
}
}
}
}
}

if($sec != ''){
if($sec == 1){
$final = $sec . ' second';
}
else{
$final = $sec . ' seconds';
}
}
if($min != ''){
if($min == 1){
$final = $min . ' minute ' . $final;
}
else{
$final = $min . ' minutes ' . $final;
}
}
if($hour != ''){
if($hour == 1){
$final = $hour . ' hour ' . $final;
}
else{
$final = $hour . ' hours ' . $final;
}
}
if($day != ''){
if($day == 1){
$final = $day . ' day ' . $final;
}
else{
$final = $day . ' days ' . $final;
}
}
if($week != ''){
if($week == 1){
$final = $week . ' week ' . $final;
}
else{
$final = $week . ' weeks ' . $final;
}
}
if($year != ''){
if($year == 1){
$final = $year . ' year ' . $final;
}
else{
$final = $year . ' years ' . $final;
}
}
return $final;
}

[email protected]
30-Jan-2002 12: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.

[email protected]
30-Jan-2002 12: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.

[email protected]
18-Feb-2002 09: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;
}
}

[email protected]
08-Mar-2002 12: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.

[email protected]
11-Mar-2002 04:16

dameFechas($dateINI,$dateEND) in the format "20020311" will return an array with the dates between that two days.

For example:
var_dump(dameFechas("20011230","20020102"));

will return

array(4) {
[0]=>
string(8) "20020102"
[1]=>
string(8) "20020101"
[2]=>
string(8) "20011231"
[3]=>
string(8) "20011230"
}

<?

// Bisiesto
function esBisiesto($y) {
$res=$y%4==0 && $y%100<>0 || $y%400==0;
return $res;
}
function numDias($i_ano,$i_mes) {
switch ($i_mes) {
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 (!esBisiesto($i_ano)) { return 28; } else { return 29; };
break;
}
}

function formatoa2($i) {
if (strlen($i)==1)
return "0".$i;
else
return $i;
}

function menosmenosuno(&$s_cad) {
$s_cad--;
$s_cad=formatoa2($s_cad);
}

function dameFechas($fechaIni,$fechaFin) {
$a_res=array();

$ini_ano=substr($fechaIni,0,4);
$fin_ano=substr($fechaFin,0,4);
$ini_mes=substr($fechaIni,4,2);
$fin_mes=substr($fechaFin,4,2);
$ini_dia=substr($fechaIni,6,2);
$fin_dia=substr($fechaFin,6,2);

$i=$fin_dia;
while (($fin_ano.$fin_mes)>=($ini_ano.$ini_mes)) {
while ($fin_mes>=1 && ($fin_ano.$fin_mes)>=($ini_ano.$ini_mes)) {
while ($fin_dia>=1 && ($fin_ano.$fin_mes.$fin_dia)>=($ini_ano.$ini_mes.$ini_dia)) {
$a_res[]=$fin_ano.$fin_mes.$fin_dia;
menosmenosuno($fin_dia);
}
menosmenosuno($fin_mes);
$fin_dia=numDias($fin_ano,$fin_mes);
}
$fin_mes=12;
$fin_dia=31;
$fin_ano--;

}

return $a_res;
}

echo "<pre>";
var_dump(dameFechas("20020309","20020310"));
echo "</pre>";

?>

Hope this helps.

[email protected]
22-Mar-2002 10:39

The editor is going to tell me it's easier to use UNIX_TIMESTAMP (I know you're watching us ed! ;) ), but I disagree. I often want to just do a "SELECT * FROM...", and this function makes that possible.

I also see a guy above has also written basically the same function. Great minds think alike, or fools seldom differ? ;)

/**
* Convert mysql timestamp to PHP timestamp.
*
* The format of a mysql date is "yyyymmddhhmmss" whereas
* PHP uses the (UNIX) format "sssssssssss" (number of seconds
* since 1970). Though it is possible to convert using
* the UNIX_TIMESTAMP function of mysql, it is sometimes more convenient
* to read in the timestamp variable just like any other (for example,
* by doing a "SELECT * FROM mytable"), and convert the timestamp
* field when it is in the program.
*
* This function simply does that conversion.
*
* Example:
* $sql_row = mysql_fetch_array( $result );
* $php_timestamp = mysql_to_php_timestamp($sql_row[my_timestamp_field]);
* $display_date = strftime("%d %B %Y %H:%M:%S", $php_timestamp);
*/
function mysql_to_php_timestamp( $mysql_date )
{
// mysql date looks like "yyyymmddhhmmss"
$year = substr( $mysql_date, 0, 4 );
$month = substr( $mysql_date, 4, 2 );
$day = substr( $mysql_date, 6, 2 );
$hour = substr( $mysql_date, 8, 2 );
$min = substr( $mysql_date, 10, 2 );
$sec = substr( $mysql_date, 12, 2 );

// Warning: mktime uses a strange order of arguments
$php_timestamp = mktime( $hour, $min, $sec, $month, $day, $year );

return $php_timestamp;
}

[email protected]
28-Mar-2002 02: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;
}

[email protected]
31-Mar-2002 08: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 03: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" ...

[email protected]
30-Jul-2002 04: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;

}

[email protected]
22-Aug-2002 10: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 :

add a note about notes
previousdba_synccheckdatenext
Last updated: Tue, 09 Jul 2002
show source | credits | stats | mirror sites
Copyright © 2001, 2002 The PHP Group
All rights reserved.
This mirror generously provided by:
Last updated: Sat Aug 31 06:19:44 2002 CEST