|
 |
getdate (PHP 3, PHP 4, PHP 5) getdate -- Возвращает информацию о дате/времени Описаниеarray getdate ( [int timestamp] )
Возвращает ассоциативный массив, содержащий информацию о дате,
представленной меткой времени timestamp или
текущем системном времени, если timestamp не
передан.
Массив содержит следующие элементы:
Таблица 1. Индексы возвращаемого ассоциативного массива Индекс | Описание | Пример значения |
---|
"seconds" | Секунды | От 0 до 59 | "minutes" | Минуты | От 0 до 59 | "hours" | Часы | От 0 до 23 | "mday" | Порядковый номер дня месяца | От 1 до 31 | "wday" | Порядковый номер дня | От 0 (воскресенье) до 6 (суббота) | "mon" | Порядковый номер месяца | От 1 до 12 | "year" | Порядковый номер года, 4 цифры | Примеры: 1999, 2003 | "yday" | Порядковый номер дня в году (нумерация с 0) | От 0 до 365 | "weekday" | Полное наименование дня недели | От Sunday до Saturday | "month" | Полное наименование месяца, например January или March | от January до December | 0 | Колическтво секунд, прошедших с начала Эпохи Unix (The Unix
Epoch), подобно значению, возвращаемому функцией time() и
используемому функцией date(). | Платформо-зависимое, в большинстве случаев от
-2147483648 до 2147483647.
|
Пример 1.
Пример использования функции getdate()
<?php
$today = getdate();
print_r($today);
?>
|
Вывод будет выглядеть так:
Array
(
[seconds] => 40
[minutes] => 58
[hours] => 21
[mday] => 17
[wday] => 2
[mon] => 6
[year] => 2003
[yday] => 167
[weekday] => Tuesday
[month] => June
[0] => 1055901520
) |
|
See also date(),
time(), and
setlocale().
getdate
John Sherwood
14-May-2006 11:10
In response to the "Simple routine for determining whether a date in mySQL format has gone past":
function pastdate($t)
{
if (strtotime($t) < time())
return false;
return true;
}
or you could use
mysql_select("SELECT UNIX_TIMESTAMP(fieldname) FROM tablename"), which would give you the date in seconds since unix epoch, and which you could compare to time().
king_of_t3rrors at hotmail dot com
28-Apr-2006 09:55
The function below is also wrong :)
This one is right ( I promise ):
{
$today = getdate() ;
$datebits=explode('-',$date);
$year = intval($datebits[strpos($formato, 'y')]);
$mon = intval($datebits[strpos($formato, 'm')]);
$day = intval($datebits[strpos($formato, 'd')]);
$y=0; $m=0;
if ( $today['year'] > $year ) {
$y=1 ;
}
if ( $today['mon'] > $mon ) {
$m=1;
}
if ( $y==1 || $m==1 ) {
return true; //past date
}
if ( $today['year'] == $year ) {
if ( $today['mon'] > $mon ) {
return true; //past date
}
if ( $today['mon']==$mon ) {
if ( $today['mday'] > $day ) {
return true; //past date
}
}
}
return false;
}
king_of_t3rrors at hotmail dot com
27-Apr-2006 05:12
This is a correction of the note posted on 27-Feb-2006 03:29:
"Simple routine for determining whether some date given
in MySQL format (yyyy-mm-dd) has gone past."
I think that code was wrong.
My code is:
function is_past( $date,$format )
// When calling this function remember:
// $date format: yyyy-mm-dd
// $format--> insert 'ymd' as second argument
{
$today = getdate() ;
$datebits=explode('-',$date);
$year = intval($datebits[strpos($format, 'y')]);
$mon = intval($datebits[strpos($format, 'm')]);
$today = intval($datebits[strpos($format, 'd')]);
if ( $today['year'] > $year ) {
return false ;
}
if ( $today['mon'] > $mon ) {
return false;
}
if ( $today['mday'] > $today ) {
return false;
}
return true;
}
Cas_AT_NUY_DOT_INFO
04-Mar-2006 05:47
// This functions calculates the next date only using business days
// 2 parameters, the startdate and the number of businessdays to add
function calcduedate($datecalc,$duedays) {
$i = 1;
while ($i <= $duedays) {
$datecalc += 86400; // Add a day.
$date_info = getdate( $datecalc );
if (($date_info["wday"] == 0) or ($date_info["wday"] == 6) ) {
$datecalc += 86400; // Add a day.
continue;
}
$i++;
}
return $datecalc ;
}
27-Feb-2006 06:29
Simple routine for determining whether some date given in MySQL format (yyyy-mm-dd) has gone past. E.g., has a membership expired or a special offer gone stale.
function is_past( $date )
{
$today = getdate() ;
$yyyy = intval(substr($date,0,4)) ;
$mm = intval(ltrim(substr($date,5,2),'0')) ;
$dd = intval(ltrim(substr($date,8,2),'0')) ;
if ( $today['year'] > $yyyy ) return true ;
if ( $today['year'] < $yyyy ) return false ;
if ( $today['mon'] > $mm ) return true ;
if ( $today['mon'] < $mm ) return false ;
if ( $today['mday'] > $dd ) return true ;
return false ;
}
WAYLER - suwala at timpadd dot pl
09-Feb-2006 04:13
I think this is better method to calculate day difference between two timestamps:
<? php
if( $first_timestamp > $second_timestamp )
{
die('Reverse timestamps');
}
else
{
$first_date = getdate( $first_timestamp );
$second_date = getdate($second_timestamp);
$years_between = $second_date['year'] - $first_date['year'];
if($years_between==0)
{
$days_between = $second_date['yday'] - $first_date['yday'];
}
if($years_between>0)
{
$start_year = 365;
$count_365_years = 0;
$count_366_years = 0;
if($first_date['year']%4==0) $start_year = 366;
for($i = 1; $i<=$years_between-1; $i++)
{
if(($first_date['year']+$i)%4==0) $count_366_years++;
else{ $count_365_years++; }
}
$days_between = $start_year - $first_date['yday'] + 365*$count_365_years + 366*$count_366_years + $second_date['yday'];
}
}
?>
Should works every time :)
mbaart at planet dot nl
27-Jan-2006 05:34
A simple way to calculate the days between to timestamps:
<?php
if( $first_timestamp > $second_timestamp )
{
die('Reverse timestamps');
} else
{
$first_date = getdate( $first_timestamp );
$second_date = getdate( $second_timestamp );
$days_in_between = ($second_date['year']-$first_date['year'])*365 +
($second_date['yday']-$first_date['yday']);
}
?>
At least, given that every year has 365 days :)
datacompboy at river-net dot org
17-Dec-2005 08:06
Note: this function returns a gmt time, not your local.
datacompboy at river-net dot org
17-Dec-2005 08:01
Note: this function returns a gmt time, not your local.
OREN WISMAN
09-Oct-2005 01:43
add few days for today date and convert to mysql date format
<?php
$days_2_add = 2;
$expired = mktime(0, 0, 0, date("m"), date("d")+$days_2_add, date("Y"));
$expired = date("Y-m-d",$expired);
?>
timtaler [at] mailueberfall [dot] de
12-Sep-2005 08:35
# very nice function to check for a leap year
$arr_date = getdate();
$jahr = $arr_date['year'];
if ( $jahr % 4 == 0 ){
if ( $jahr % 100 == 0 ){
if ( $jahr % 400 == 0 ){
$ydays = 366;
}
else{
$ydays = 365;
}
}
else{
$ydays = 366;
}
}
else{
$ydays = 365;
}
$one_year = ($ydays * 24 * 60 * 60); # create a int varibale for one year
leo25in at yahoo dot com
11-May-2005 05:17
getting weekday(actual date) from any give date.
function cal_date($wday,$tstamp)
{
return $tstamp-($wday*(24*3600));
}
function getweekday($m,$d,$y)
{
$tstamp=mktime(0,0,0,$m,$d,$y);
$Tdate = getdate($tstamp);
$wday=$Tdate["wday"];
switch($wday)
{
case 0;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 1;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 2;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 3;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 4;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 5;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
case 6;
$wstamp=cal_date($wday,$tstamp);
//echo date("Y-m-d",$wstamp);
break;
}
$w["day"]=date("d",$wstamp);
$w["month"]=date("m",$wstamp);
$w["year"]=date("Y",$wstamp);
return $w;
}
ahigerd at stratitec dot com
05-Apr-2005 02:05
The comment below about getdate() being insensitive to LOCALE is simply incorrect:
<?php print_r(getdate(0)); ?>
Array
(
[seconds] => 0
[minutes] => 0
[hours] => 18
[mday] => 31
[wday] => 3
[mon] => 12
[year] => 1969
[yday] => 364
[weekday] => Wednesday
[month] => December
[0] => 0
)
Note that I'm in CDT at the moment.
davidhc at gmail dot com
20-Jan-2005 12:55
function getDateForMysqlDateField() {
$date = getDate();
foreach($date as $item=>$value) {
if ($value < 10)
$date[$item] = "0".$value;
}
return $date['year']."-".$date['mon']."-".$date['mday']." ".$date['hours'].":".$date['minutes'].":".$date['seconds'];
}
pascal dot bonderff at wanadoo dot fr
05-Nov-2004 12:32
Note that this fonction doesn't care about LOCALE settings. use strftime insteand
Liis make
16-Sep-2004 03:22
function win2unix($date_string,$date_timestamp)
{
$epoch_diff = 11644473600; // difference 1601<>1970 in seconds. see reference URL
$date_timestamp = $date_timestamp * 0.0000001;
$unix_timestamp = $date_timestamp - $epoch_diff;
echo date($date_string,$unix_timestamp);
}
getisomonday($year, $week)
21-Apr-2004 02:58
getdate does not convert week numbers. this function relies on strftime to find a timestamp that falls on the monday of specified year and ISO week:
<?php function getisomonday($year, $week) {
$year = min ($year, 2038); $year = max ($year, 1970);
$week = min ($week, 53); $week = max ($week, 1);
$monday = mktime (1,1,1,1,7*$week,$year);
while (strftime('%V', $monday) != $week)
$monday -= 60*60*24*7;
while (strftime('%u', $monday) != 1)
$monday -= 60*60*24;
return $monday;
} ?>
Yura Pylypenko (plyrvt at mail dot ru)
15-Sep-2003 06:29
In addition to canby23 at ms19 post:
It's a very bad idea to consider day having 24 hours (86400 secs), because some days have 23, some - 25 hours due to daylight saving changes. Using of mkdate() and strtotime() is always preferred. strtotime() also has a very nice behaviour of datetime manipulations:
<?php
echo strtotime ("+1 day"), "\n";
echo strtotime ("+1 week"), "\n";
echo strtotime ("+1 week 2 days 4 hours 2 seconds"), "\n";
echo strtotime ("next Thursday"), "\n";
echo strtotime ("last Monday"), "\n";
?>
intronis
11-Sep-2003 11:04
When adding a timestamp to a database from php, be carefule because if your DB Server is a different computer than your webserver, the NOW() function in the SQL will use the DB Server's time, and not the web server's. You can use NTP to synch the times on both computers.
coolen at astron dot nl
09-Dec-2002 06:36
Yup, it does so the getdate gives you the wrong daynumber.
using the following modification will give you the exact weeknr:
function week_of_year($nDay,$nMonth,$nYear)
{
$date=getDate(mktime(9,0,0,$nMonth,$nDay,$nYear));
$weeknr=floor(($date["yday"]+1)/7)+1;
$weeknr %=52;
return $weeknr;
}
squagmire at yaspoo dot com
17-Mar-2002 11:39
How I created a local UNIX timestamp running PHP on Windows 2000. Similar to other functions already posted here, but I figured I'd stick my two cents in.
function get_time_at_page_load() {
global $time_at_page_load;
$temp = getdate();
$time_at_page_load = $temp['year'];
$zerofill = array
( 'mon' => '-'
, 'mday' => '-'
, 'hours' => ' '
, 'minutes' => ':'
, 'seconds' => ':'
);
while( list( $name, $pfix ) = each( $zerofill ) ) {
if ($temp[$name] < 10) $temp[$name] = (string)'0'.$temp[$name];
$time_at_page_load .= $pfix.$temp[$name];
}
$time_at_page_load = strtotime($time_at_page_load);
}
logan dot hall at asu dot edu
11-Mar-2002 12:32
It seems that 'yday' (the day of the year) that php produces is one less than what the unix 'date +%j' produces.
Not sure why this is, but I would guess that php uses 0-365 rather than 1-366 like unix does. Just something to be careful of.
21-Oct-2001 04:55
Another way to map US day no to European count
function sunsat_to_monsun($wday)
{
return ($wday + 6) % 7;
}
And a bit faster code, to calculate it directly from timestamp:
$wday = (time() % 604800 / 86400 + 3) % 7;
hfuecks at hotmail dot com
20-Aug-2001 07:36
If you wanted to find which day of the week corresponds to a particular date you could do something like this (for August 20th, 2001 - a Monday!) ;
<?
$timestamp = mktime(0,0,0,8,20,2001);
$date = getdate ($timestamp);
$dayofweek = $date['wday'];
echo ( "$dayofweek" );
?>
This returns a 1 (0 being Sunday)
ih2 at morton-fraser dot com
17-Oct-2000 05:01
To do comparisons on dates stored in mysql db against 7 days ago, 1 month ago etc use the following:
$last_week = date("Y-m-d", mktime(0,0,0, date(m), date(d)-7,date(Y)));
if($date > $last_week)
{
etc.
This allows for intelligent looping i.e. works at start/end of month/year
I have noticed other postings re this and they have not worked for me.Hope this helps.
zparker at rpinteractive dot com
06-Mar-2000 03:14
Re: timestamping w/ php + mysql.
If you're writing a php script and just want a quick timestamp for mysql, there's an easier method.
Create a field of type datetime, and then do the following:
insert into blah (blah, tstamp) values ('blah', NOW());
of course, if you're doing something more complex than timestamping, then you'll need to use the php method. but for timestamping, this is less hassle. ;)
ems at itg dot net
14-Feb-2000 10:28
*Note* - Month and day are NOT zero-filled, so be careful when inserting dates generated by getdate(time()) into a database.
| |