SSISO Community검색 |
|
SSISO Community메뉴 |
|
SSISO Community카페 |
|
블로그 카테고리 |
|
|
spring로 검색한 결과 |
|
등록일:2005-07-04 21:39:53 작성자: 제목:날짜/시간 - strtotime ( string time [, int now]) |
|
strtotime
(PHP 3>= 3.0.12, PHP 4 , PHP 5)
strtotime -- Parse about any English textual datetime description into a Unix timestamp
Description
int strtotime ( string time [, int now])
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp relative to the timestamp given in now, or the current time if none is supplied. Upon failure, -1 is returned.
Because strtotime() behaves according to GNU date syntax, have a look at the GNU manual page titled Date Input Formats. Described there is valid syntax for the time parameter.
예 1. strtotime() examples
<?php
echo strtotime("now"), "\n";
echo strtotime("10 September 2000"), "\n";
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";
?>
예 2. Checking for failure
<?php
$str = 'Not Good';
if (($timestamp = strtotime($str)) === -1) {
echo "The string ($str) is bogus";
} else {
echo "$str == " . date('l dS of F Y h:i:s A', $timestamp);
}
?>
참고: The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.) Additionally, not all platforms support negative timestamps, therefore your date range may be limited to no earlier than the Unix epoch. This means that e.g. dates prior to Jan 1, 1970 will not work on Windows, some Linux distributions, and a few other operating systems.
add a note User Contributed Notes
strtotime
ruben at wipkip dot com
28-Jun-2005 08:14
This is an easy way to calculate the number of months between 2 dates (including the months in which the dates are themselves).
<?
$startDate = mktime(0,0,0, 6, 15, 2005);
$stopDate = mktime(0,0,0, 10, 8, 2006);
$nrmonths = ((idate('Y', $stopDate) * 12) + idate('m', $stopDate)) - ((idate('Y', $startDate) * 12) + idate('m', $startDate));
?>
Results in $nrmonths = 16.
rogier at patsfactor dot nl
20-Jun-2005 09:07
@brett at medeaproject dot co dot za
Slightly offtopic:
It might be easier to select the unix timestamp directly from MySQL, something like "SELECT UNIX_TIMESTAMP( mysqltimestampfield ) AS TIME" should render you little function obsolete.
brett at medeaproject dot co dot za
15-Jun-2005 07:24
Got irritated using strtotime to try and parse a SQL server timestamp to a unix time stamp...
So i wrote this little function hopesomeone else finds it useful
function mssql_date_parser($indate){
//YYYY-MM-DD HH:mm:ss.splits
$indate = explode(" ", $indate);
$dateArr = explode("-", $indate[0]);
$timeArr = explode(":", $indate[1]);
$timeArr[2] = substr($timeArr[2],0, strpos($timeArr[2],"."));
$outdate = mktime(
$timeArr[0],
$timeArr[1],
$timeArr[2],
$dateArr[1],
$dateArr[2],
$dateArr[0]
);
return $outdate;
}
yasingedikli at hotmail dot com
24-May-2005 08:45
You can get the beginn and end date from weeknumber !
function dateweek($weeknumber)
{
$x = strtotime("last Monday");
$Year = date("Y",$x);
$Month = date("m",$x);
$Day = date("d",$x);
if ($Month < 2 && $Day < 8) {
$Year = $Year--;
$Month = $Month--;
}
if ($Month > 1 && $Day < 8)
$Month = $Month--;
//DATE BEGINN OF THE WEEK ( Monday )
$Day = $Day+7*$weeknumber;
echo date('Y-m-d', mktime(0, 0, 0, $Month, $Day, $Year));
//DATE END OF THE WEEK ( Sunday )
$Day = $Day+6;
echo date('Y-m-d', mktime(0, 0, 0, $Month, $Day, $Year));
}
// THIS WEEK
dateweek(0);
// LAST WEEK
dateweek(-1);
// NEXT WEEK
dateweek(1);
// 4 WEEK THEN
dateweek(4);
Rene Leonhardt (rele at gmx dot de)
11-May-2005 08:48
Here is a slightly improved version of date_uk_to_american, posted by James McGuigan on 27-Dec-2004 08:31.
Now you can use the function to parse a date string (user input) to show, whether it was recognized correctly.
function date_uk_to_american($date, $replace_separator = FALSE) {
$days = '0?[1-9]|[12][0-9]|3[01]';
$months= '0?[1-9]|1[0-2]';
$year = '\d{2}|\d{4}';
$non_alpha = '[^0-9a-zA-Z]+';
return preg_replace( "/^\s*($days)($non_alpha)($months)($non_alpha)($year)/", $replace_separator === FALSE ? '$3$2$1$4$5' : '$3'.$replace_separator.'$1'.$replace_separator.'$5', $date);
}
function parse_date($date) {
return date("d.m.Y", strtotime(date_uk_to_american($date, '/')));
}
//example: echo parse_date('3.12.83');
not provided
11-May-2005 08:34
A shorter function for recognising dates before 1970 and returning a negative number is below. All it does is replaces years before 1970 with ones 68 years later (1904 becomes 1972), and then offsets the return value by a couple billion seconds. It works back to 1/1/1902, but only on dates that have a century.
function safestrtotime ($s) {
$basetime = 0;
if (preg_match ("/19(\d\d)/", $s, $m) && ($m[1] < 70)) {
$s = preg_replace ("/19\d\d/", 1900 + $m[1]+68, $s);
$basetime = 0x80000000 + 1570448;
}
return $basetime + strtotime ($s);
}
Note that a negative number is stored the same as a really big positive number. 0x80000000 is the number of seconds between 13/12/1901 20:45:54 and 1/1/1970 00:00:00. And 1570448 is the seconds between this date and 1/1/1902 00:00:00, which is 68 years before 1/1/1970.
LittleZephyr at nillahood dot net
09-May-2005 04:49
Here's a quick one-line function you can use to get the time difference for relative times. But default, if you put in a relative time (like "1 minute"), you get that relative to the current time. Using this function will give you just the time difference in seconds:
<?php function relative_time( $input ) { return strtotime($input) - time(); } ?>
For example "1 minute" will return 60, while "30 seconds ago" will return -30
Valid relative time formats can be found at http://www.gnu.org/software/tar/manual/html_chapter/tar_7.html#SEC115
Ed Lecky-Thompson
26-Apr-2005 12:04
Here's a quick function which can replace strtotime, and will work fine on dates pre-1970 (i.e. it will return a negative number as expected).
This negative time stamp seems to be supported as an input parameter by methods like date() up to a point, but if you get crazy and start talking about dates in the 1700s (everybody was using PHP3 back then, of course) it gets upset.
For those of you doing staff databases and so forth, of course, this is probably fine - it's definitely OK for any dates post 1900, and this value has been hard coded into the function below.
function safestrtotime($strInput) {
$iVal = -1;
for ($i=1900; $i<=1969; $i++) {
# Check for this year string in date
$strYear = (string)$i;
if (!(strpos($strInput, $strYear)===false)) {
$replYear = $strYear;
$yearSkew = 1970 - $i;
$strInput = str_replace($strYear, "1970", $strInput);
};
};
$iVal = strtotime($strInput);
if ($yearSkew > 0) {
$numSecs = (60 * 60 * 24 * 365 * $yearSkew);
$iVal = $iVal - $numSecs;
$numLeapYears = 0; # Work out number of leap years in period
for ($j=$replYear; $j<=1969; $j++) {
$thisYear = $j;
$isLeapYear = false;
# Is div by 4?
if (($thisYear % 4) == 0) {
$isLeapYear = true;
};
# Is div by 100?
if (($thisYear % 100) == 0) {
$isLeapYear = false;
};
# Is div by 1000?
if (($thisYear % 1000) == 0) {
$isLeapYear = true;
};
if ($isLeapYear == true) {
$numLeapYears++;
};
};
$iVal = $iVal - (60 * 60 * 24 * $numLeapYears);
};
return($iVal);
};
websafe at partybitchez dot org
24-Apr-2005 02:53
A small update... Should be ok now.
<?php
function count_months($start_date, $end_date) {
# Returns whole-month-count between two dates
# websafe<at>partybitchez<dot>org
# usage
# count_months("1978-02-18", "2028-08-12");
#
$start_date_unixtimestamp = strtotime($start_date);
$start_date_month = date("m", $start_date_unixtimestamp);
$end_date_unixtimestamp = strtotime($end_date);
$end_date_month = date("m", $end_date_unixtimestamp);
$calculated_date_unixtimestamp = $start_date_unixtimestamp;
$counter=0;
while ($calculated_date_unixtimestamp < $end_date_unixtimestamp)
{
$counter++;
$calculated_date_unixtimestamp = strtotime($start_date . " +{$counter} months");
}
#
if ( ($counter==1) && ($end_date_month==$start_date_month)) $counter=($counter-1);
return $counter;
}
?>
Example 01: count_months("1996-02-18", "2005-11-24") returns 118
Example 02: count_months("2005-04-24", "2005-04-24") returns 0
Example 03: count_months("2005-04-24", "2005-04-25") returns 0
Example 04: count_months("1978-02-18", "2028-08-12") returns 606
Example 05: count_months("2008-02-29", "2009-02-29") returns 12
Example 06: count_months("2008-02-29", "2008-03-01") returns 1
Example 07: count_months("2008-02-29", "2008-03-02") returns 1
Example 08: count_months("2008-02-29", "2009-02-28") returns 12
Example 09: count_months("2008-02-29", "2009-02-29") (not existing enddate) returns 12
Example 10: count_months("2008-02-29", "2009-03-01") returns 12
Example 11: count_months("2008-02-29", "2009-03-02") returns 13
miamiseb at nospam_gmail dot com
22-Apr-2005 12:59
If you strtotime the epoch (Jan 1 1970 00:00:00) you will usually get a value, rather than the expected 0. So for example, if you were to try to use the epoch to calculate the difference in times (strtotime(Jan 1 1970 21:00:00)-strtotime(Jan 1 1970 20:00:00) for example) You get a value that depends strongly upon your timezone. If you are in EST for example, the epoch is actually shifted -5 to YOUR epoch is Jan 1 1970 19:00:00) In order to get the offset, simply use the following call to report the number of seconds you are away from the unix epoch. $offset=strtotime("1970-01-01 00:00:00"); Additionally, you can append GMT at the end of your strtotime calls so save yourself the trouble of converting relative to timezone.
thraoln at yahoo dot com
16-Apr-2005 07:04
Quick solution to strtotime() function returning wrong results(for PHP4 and below) when it tries to "guess what you meant" and will successfully parse dates that would otherwise be considered invalid...just dont use it, this works better:
function valid_date($thedate) {
list($year, $month, $day) = sscanf($thedate, "%d-%d-%d");
return checkdate($month, $day, $year);
}
"2005-11-25" returns TRUE
"2005-11-32" returns FALSE
ldbkutty at yahoo dot com
12-Apr-2005 06:21
I was trying to find a funtion that will let me add months to a date.
I have tried
$myDate = strtotime("+1 month",mktime(0,0,0,1,31,2004));
This returns 2004-03-02 but I wanted the result as 2004-02-29. So, I noticed there is no equilent function like setLenient as false and I wrote one.
Hope this helps for someone.
<?php
function addMonthNoLenient($my_date, $add_month)
{
$day = date( "d", $my_date );
$month = date( "m", $my_date );
$year = date( "Y", $my_date );
$new_date = date( "Y-m-d", mktime( 0, 0, 0, $month + $add_month, $day, $year) );
$month_for_days = ( $month + $add_month ) % 12;
if( $month_for_days == 0 )
{
$month_for_days = 12;
}
if( $month_for_days != date( "m", mktime( 0, 0, 0, $month + $add_month , $day, $year ) ) )
{
$new_year = date( "Y", mktime( 0, 0, 0, $month + $add_month, $day, $year ) );
$days_in_month = cal_days_in_month( CAL_GREGORIAN, $month_for_days, $new_year );
$new_date = date( "Y-m-d", mktime( 0, 0, 0, $month + $add_month, $days_in_month, $year ) );
}
return $new_date;
}
?>
<?
$your_date = mktime( 0, 0, 0, 1, 30, 2004 );
$months_to_add = 25;
echo addMonthNoLenient( $your_date, $months_to_add );
?>
Greg Robbins
08-Apr-2005 04:12
This function will count fractional months between 2 dates, perhaps for billing purposes (like for hosting, as was my case).
<?php
function count_months($start_date, $end_date)
{
//Initialize counters for days and months
$days = 0;
$months = 0;
//get current month (as of your start_date)
$curr_month = date("Y-m-01", $start_date);
//loop by days
while($start_date <= $end_date)
{
//If the current iteration has passed on to a new month
if($curr_month != date("Y-m-01", $start_date))
{
//divide the number of days counted by the number of days in the month
//to get a decimal representation of how many months should be counted.
//Increment the months count by this value
$months += $days / date("t", strtotime($curr_month));
//Uncomment the following line to see how it counts month by month
//echo "$days Days / " . date("t", strtotime($curr_month)) . " days in month $curr_month<br>\n";
//Advance the current month
$curr_month = date("Y-m-01", strtotime($curr_month . " + 1 months"));
//Reset the days counter sibce we are now counting a new month
$days = 0;
}
//Advance tot he next day...
$start_date = strtotime(date("Y-m-d", $start_date) . " + 1 days");
//And increment the day counter
$days++;
}
//This is the same as above but applied to the last month
$months += $days / date("t", strtotime($curr_month));
//Uncomment the following line to see how it counts month by month
//echo "$days Days / " . date("t", strtotime($curr_month)) . " days in month $curr_month<br>\n";
//This returns a decimal value to two decimals of accuracy
return sprintf("%01.2f", $months);
}
//Check it out:
$last_billed_date = "2004-12-31";
$bill_thru_this_date = "2005-04-15";
$unix_start_date = strtotime($last_billed_date . " +1 days");
$unix_end_date = strtotime($bill_thru_this_date);
echo "Last billed date: " . $last_billed_date . "<br>";
echo "Bill through date: " . $bill_thru_this_date . "<br>";
echo "Total months: " . count_months($unix_start_date, $unix_end_date);
?>
05-Apr-2005 02:45
I ran into the same problem with "last" as gabrielu at hotmail dot com (05-Apr-2005 10:45) when using strtotime() with getdate(). My only guess is that it has to do with daylight savings time as it seemed to be ok for most dates except those near the first Sunday in April and last Sunday in October.
I used strftime() with strtotime() and that gave me the result I was looking for.
gabrielu at hotmail dot com
05-Apr-2005 12:45
While working on an employee schedule application I noticed an issue with using strtotime('last...'). I ran tests on each weekday for each week within a year and noticed inconsistencies while using:
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
Most calculations of the 'last Wednesday' for each week calculated accordingly however I noticed a problem with several dates, one being '04/05/2005' (April 5th 2005).
date('m/d/Y', strtotime('last Wednesday', '2005-04-05'))
The above should have returned '03/30/2005'. Instead, it returned '03/29/2005'. I don't understand why the function is returning this value. Regardless, my solution:
date('m/d/Y', strtotime('-1 week' ,strtotime('Wednesday', '2005-04-05')))
insta at citiesunlimited dot com
01-Apr-2005 05:56
Just a note ... there cannot be spaces between the + and the amount you want to add.
strtotime("{$myDate} -1 months") is correct.
strtotime("{$myDate} - 1 months") is not.
Caused me a headache ...
dfuchs at donotspam dot gmail dot com
29-Mar-2005 05:15
Just pointing out that date( 'M', strtotime( 'last month', [some timestamp]) ) will not actually give the name of the previous month if the day of [some timestamp] doesn't exsist in the previous month. It will instead round up, and give the name of one month AFTER the previous month ('this month', that is).
For example date( 'M', strtotime( 'last month', [March 31st]) ) will return 'Mar'.
This is documented here: http://www.gnu.org/software/tar/manual/html_chapter/tar_7.html (also linked from this manual page), but is not easy to find:
" The fuzz in units can cause problems with relative items. For example, `2003-07-31 -1 month' might evaluate to 2003-07-01, because 2003-06-31 is an invalid date. To determine the previous month more reliably, you can ask for the month before the 15th of the current month. For example:
$ date -R
Thu, 31 Jul 2003 13:02:39 -0700
$ date --date='-1 month' +'Last month was %B?'
Last month was July?
$ date --date="$(date +%Y-%m-15) -1 month" +'Last month was %B!'
Last month was June! "
Hope that helps somebody!
jason at draxjinn dot com
02-Mar-2005 07:02
After searching the (entire) internet for a routine that would (re)format a date string without the pre-1970 problems of strtotime, I ended up writing the following function. [Note that it doesn't support all of the formatting options that the date() function does, but it is really a trivial matter to implement the remaining features.]
(Thanks to Jan Goyvaerts site http://www.regular-expressions.info/dates.html for having the snippets of regular expressions that parse the date formats)
Hope this helps:
function formatDate($szFormat, $szDate = NULL)
{
if (!isset($szDate))
$szDate = date("Y-m-d H:i:s");
$szTemp = "00-00-0000";
$arryMatch = Array();
if ( preg_match('%(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])%', $szDate, $arryMatch) )
{
// Date is in the format of Y-m-d
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[1];
$arryDate['d'] = $arryTemp[2];
$arryDate['Y'] = $arryTemp[0];
//$szTemp = .'-'.$arryTemp[2].'-'.$arryTemp[0];
}
elseif ( preg_match('%(0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])[- /.](19|20)\d\d%', $szDate, $arryMatch) )
{
// Date is in the format of m-d-Y
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[0];
$arryDate['d'] = $arryTemp[1];
$arryDate['Y'] = $arryTemp[2];
//$szTemp = $arryTemp[0].'-'.$arryTemp[1].'-'.$arryTemp[2];
}
elseif ( preg_match('%(0[1-9]|[12][0-9]|3[01])[- /.](0[1-9]|1[012])[- /.](19|20)\d\d%', $szDate, $arryMatch) )
{
// Date is in the format of d-m-Y
$arryTemp = preg_split('%[- /.]%', $arryMatch[0]);
$arryDate['m'] = $arryTemp[1];
$arryDate['d'] = $arryTemp[0];
$arryDate['Y'] = $arryTemp[2];
//$szTemp = $arryTemp[1].'-'.$arryTemp[2].'-'.$arryTemp[2];
}
if (!checkdate($arryDate['m'], $arryDate['d'], $arryDate['Y']))
{
return -1;
}
$nJD = gregoriantojd($arryDate['m'], $arryDate['d'], $arryDate['Y']);
$szTemp = str_replace('Y', $arryDate['Y'], $szFormat);
$szTemp = str_replace('m', $arryDate['m'], $szTemp);
$szTemp = str_replace('d', $arryDate['d'], $szTemp);
$szTemp = str_replace('D', jddayofweek( $nJD, 2), $szTemp);
$szTemp = str_replace('F', jdmonthname( $nJD, 1), $szTemp);
//echo $szTemp;
return $szTemp;
}
alchemyx at uznam dot net dot pl
02-Mar-2005 11:39
You need to remember, that there is a bug in strtotime implementation for 64bit architectures. So at the moment look out for weirdly big return values which will be instead of -1.
Guilherme Blanco
27-Feb-2005 10:27
I made a simple hack to allow a correct date parse of Quarters.
For example, of you have this date: Q1 2005, it should be converted to 2005-03-27. The only support it doesn't have is for 2 digit year based (because of my Regular Expression).
So, these entries are allowed:
- Q7 2005 => will be converted to Q3 2006
- Q1 2005 10:01:50
- February 2005
- 16-feb-2006
- and other strtotime compatible.
The function:
<?php
function str2time($str)
{
$str = preg_replace("/Q(.+){1}\s+([[:digit:]]{4})(.*)/i", "\\2-X\\1X-27\\3", trim($str));
preg_match_all("/X(.+)X/i", $str, $matches);
$quarter = $matches[1][0];
$month = $quarter * 3;
if (strlen($month) == 1) $month = "0".$month;
return strtotime(str_replace("X{$quarter}X", $month, $str));
}
?>
Example call:
<?php
print_r(getdate(str2time("Q1 2005 10:01:50")));
?>
farooqym at ieee dot org
22-Feb-2005 11:12
This function will return an array containing the months between two dates:
function get_months ( $start, $end ) {
while ( strtotime($start) <= strtotime($end) ) {
$months[] = date("F, Y", strtotime( "$start" ) );
$start = date("Y-m-d", strtotime( "$start + 1 months")) ;
}
return $months;
}
mazinmk at yahoo-inc dot com
31-Jan-2005 07:22
Want to add days to specific date and want to list out all the days.
<?php
$days = 6; // No. Of days to add
$from_date = date("Y-m-d"); // any date.
for ($i=0; $i<=$days; $i++)
{
print date("Y-m-d", strtotime("$from_date + $i days"));
echo "<br>";
}
?>
bruce dot drummond at tribalinternet dot co dot uk
27-Jan-2005 06:35
Just a comment that the strtotime function supports American date format before it supports English date format.
$input = "02/01/2000";
$time = strtotime($input);
$output = date("Ymd", $time);
For the example date above, the output will be 20000201.
However, for the 29th January 2000 (29/01/2000) the output is 20020501
so it assumes mm/dd/yyyy rather than dd/mm/yyyy
ned at nospam dot wgtech dot com
24-Jan-2005 12:11
For those who might be looking for a way to format date information in one string according to the formatting rules of another string for whatever reason, I have a function over on evil walrus that will do just that. It returns an array formatted similarly to getdate();
Gives you a bit more control than the blind swinging strtotime() does.
Its here:
http://www.evilwalrus.com/viewcode.php?codeEx=627
paul at l-n dot org dot uk
17-Jan-2005 04:00
If you have moved from 5-5.02 to >5.02 and need the previous behaviour of relative times being "computed from today's midnight", just specify the time aswell.
For example: strtotime("today 00:00:00").
skeets011 at skeets011 dot com
14-Jan-2005 11:08
If you are using strtotime to compare times such as if building a scheduling script, keep in mind that if you enter in a time only, such 12:00pm and it is already past that time, the timestamp returned will be for 12:00pm the next day. A workaround would be
strtotime("12:00pm",strtotime("today"))
ssettl2 at gee mail dot com
13-Jan-2005 04:09
Needed a way to query mysql and find things occuring in the most recently completed workweek.
<?
$last_friday = date("Y-m-d 00:00:00",strtotime("last Friday"));
$last_monday = date("Y-m-d 23:59:59",strtotime("last Monday",strtotime($last_friday)));
?>
Now I just compare these dates with dates in my table.
James McGuigan
27-Dec-2004 02:31
A slightly more advanced method for converting European / UK dates (DD-MM-YYYY) to US dates (MM-DD-YYYY) that
<?php
// helper function needed for date_uk_to_american($date)
// implode_range('|', 7, 11, true) returns "7|07|8|08|9|09|10|11"
function implode_range($seperator, $start, $end, $add_zeros=true) {
$array_int = range($start, $end);
if($add_zeros == false) { return implode($seperator,$array_int); }
else {
$array = array();
$digit_count = strlen("$end");
foreach($array_int as $number) {
$string = "$number";
$array[] = $string;
if(strlen($string) != $digit_count) {
$array[] = str_pad($string, $digit_count, '0', STR_PAD_LEFT);
}
}
return implode($seperator,$array);
}
}
// converts (DD-MM-YY) into (MM-DD-YY)
function date_uk_to_american($date) {
$days = implode_range('|',0,12,true);
$months = implode_range('|',0,30,true);
$year = '\d{2}|\d{4}';
//$whitespace = '[\W\/-\\\\]{1,3}';
$non_alpha = '[^0-9a-zA-Z]+';
return preg_replace( "/^($days)($non_alpha)($months)($non_alpha)($year)$/", '$3$2$1$4$5', $date);
}
echo date_uk_to_american('3-12-82') . '<br>'; // 12-3-82
echo date_uk_to_american('9-31-2004') . '<br>'; // 9-31-2004 - non valid uk date - not converted
echo date_uk_to_american('2004-12-01'). '<br>'; // 2004-12-01 - ISO date -not converted
echo date_uk_to_american('01-02-04') . '<br>'; // 02-01-04
echo date_uk_to_american('04-02-01') . '<br>'; // 02-04-01 - can't detect YY-MM-DD dates with 2 digit years between 2000 and 2012 - so it
?>
my_nick // aristos , home , pl
25-Dec-2004 05:52
Despite the fact that GNU manual ( http://www.gnu.org/software/tar/manual/html_chapter/tar_7.html#SEC117 ) describes "@number" format for Epoch time as correct, strtotime() seems to return -1.
# php -r 'echo strtotime("@1234");'
-1
Good to know, if you want to avoid frustrating hours of debugging "looks-like-correct" code...
Jeremy - phpnet AT jagged DOT co DOT nz
22-Dec-2004 06:34
For the "rest of the world" who dont use american date format
ie. use dd/mm/yy NOT mm/dd/yy
Using the pregmatch line shown below should convert any dates in this format to the correct format...
HOWEVER dates in yy/mm/dd will no longer be able to be parsed, not a big loss if you ask me.
$input = "12/02/05";
echo date('d M Y',strtotime($input));
$input = preg_replace( '/(\d{2})\W(\d{2})\W(\d{2}|\d{4})/', '$2/$1/$3', $input);
echo date('d M Y',strtotime($input));
phpnotes at majiclab dot com
16-Dec-2004 09:10
If anyone is stuck with PHP5 version <5.0.3, and needs to use strtotime functions:
<?php
function strtotimefix($strtotime)
{
return time() + (strtotime($strtotime) - strtotime('now'));
}
strtotime('+10 seconds'); // will not work as expected
strtotimefix('+10 seconds'); // should work as expected
?>
Freek Dijkstra
10-Dec-2004 07:03
Note that (at least for PHP 4.3.3) strtotime does not support the ISO 8601 format "2004-12-01T20:10:02Z", although it does support both "2004-12-01 20:10:02Z" and "2004-12-01T20:10:02".
bishop
08-Dec-2004 11:12
Be warned that strtotime() tries to "guess what you meant" and will successfully parse dates that would otherwise be considered invalid:
<?php
$ts = strtotime('1999-11-40');
echo date('Y-m-d', $ts);
// outputs: 1999-12-10
?>
It is my understanding (I have not verified) that the lexer for strtotime() has been rewritten for PHP5, so these semantics may only apply for PHP4 and below.
j_lozinski at yahoo dot co dot uk
08-Dec-2004 12:17
If you're looking to get the 1st and last day of a month, then date() is what you want. For example
date("Y-m-01") => 1st of this month
date("Y-m-t") => last of this month (t is num days in the month)
date("Y-m-t", strtotime("+1 Month")) => last day of next month.
the result from date() can be fed into strtotime, like so:
strtotime(date("Y-m-t")) => last of this month as unix timestamp
Dot_Whut?
06-Dec-2004 05:47
I'm not so sure the following claim (taken from above) is true in all cases:
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!
When I try this (on a server that acknowledges Pacific Daylight Savings Time):
echo date('Y-m-d H:i:s'. $date_time2);
I get:
2004-04-03 17:00:00
which is incorrect. It should be 18:00 hours, the day prior. It would appear that although GMT (or UTC or even Z) is specified in the time string, the date is treated as if a Daylight Savings Time switch should apply when it shouldn't.
Try this (only if your server would acknowledge PST/PDT in North America)...
// In Greenwich (UTC) at 2:00 AM on the first Sunday in April,
// it is NOT Daylight Savings Time ANYWHERE in North America
$std_time = strtotime('2004-04-04 01:59:59 UTC');
$std_time = strtotime('2004-04-04 02:00:00 UTC');
echo 'Standard Time: ' . date('Y-m-d H:i:s', $std_time) . '<br />';
echo 'Daylight Savings: ' . date('Y-m-d H:i:s', $dst_time) . '<br />';
Emits:
Standard Time: 2004-04-03 17:59:59
Daylight Savings: 2004-04-03 17:00:00
Which is totally incorrect. Why does should the clock "fall" backward anyways? I thought the rule was "spring" forward.
The following example does work properly as expected:
// In Greenwich (UTC) at 10:00 AM on the first Sunday in April,
// it is Daylight Savings Time in most of North America
// For Mountain 08:59, Central 07:59, Eastern 06:59, Atlantic 05:59
$std_time = strtotime('2004-04-04 09:59:59 UTC');
// For Mountain 9:00, Central 08:00, Eastern 07:00, Atlantic 06:00
$dst_time = strtotime('2004-04-04 10:00:00 UTC');
echo 'Standard Time: ' . date('Y-m-d H:i:s', $std_time) . '<br />';
echo 'Daylight Savings: ' . date('Y-m-d H:i:s', $dst_time) . '<br />';
Which emits:
Standard Time: 2004-04-04 01:59:59
Daylight Savings: 2004-04-04 03:00:00
Which is correct...
aripollak at gmail dot com
15-Nov-2004 01:28
To find the last Friday of the current month (when Date::Calc::NWeekdayOfMonth isn't available):
<?php
$nextmonth = strftime("%B %Y", strtotime("+1 month"));
$lastfriday = strtotime("-1 week friday", strtotime("1 $nextmonth")) + 43200;
print strftime('%B %d, %Y', $lastfriday);
?>
matt at farleyfamily dot net
20-Oct-2004 12:05
Here's a good way to find the next X Weekday of the month (ie the next 3rd Tuesday of the month)
<?
# set nextmtg to 3rd tuesday after the first of the month
$nextMeeting = strtotime("+2 week Tuesday", strtotime("first ".date("F"))) + 43200;
# if nextmtg is past, set it to 3rd tuesday after first of next month
if ($nextMeeting < time())
$nextMeeting = strtotime("+2 week Tuesday", strtotime("first ".date("F",strtotime("month")))) + 43200;
$nextMeeting = date("F dS, Y", $nextMeeting);
echo " <p>√ <strong>$nextMeeting</strong></p>";
?>
maxz /* at */ rdtc /* dot */ ru
17-Sep-2004 06:52
When you convert date string got by untrusted source (such as If-Modified-Since HTTP Header) don't forget to check if the date string is empty.
<? strtotime('') ?>
returns current timestamp on my php 4.3.8
Mike Toppa
23-Aug-2004 09:58
If you're using SQL Server, it returns dates as a fixed length field, which means you'll often get whitespace at the end of a date. If you use strtotime() on such a date, it will behave correctly about half the time. The other half, it will return -1 (to demonstrate, run it through a web page, and keep hitting reload, and you'll see it randomly jump back and forth). This isn't a strtotime bug, as I assume it's not designed to handle whitespace. So the solution is to trim any dates you get from SQL Server tables before using strtotime() on them.
This is also a problem if you use Smarty's date formatting features. Trim dates you get from SQL Server before you send them to Smarty.
tom at( at ) itx dot hu
23-Aug-2004 07:19
I've found that v4.1.2 strtotime('next Monday') gives me today's date if today is Monday.
The workaround is simple, use:
strtotime('next Monday', strtotime('+1 day'));
tim at komta dot com
19-Aug-2004 09:38
After a slight moment of frustration, and finding that I'm not the only one with this problem (see http://bugs.php.net/bug.php?id=28088 - it's a known bug) I decided to write a short workaround for dealing with the 00 hour problem.
The problem only seems to occur when inputting strings such as '08/20/2004 0047' and NOT '08/20/2004 00:47'. Hence, my fix:
<?php
$your_value ( preg_replace ('#^(\d+/\d+/?\d{2,4} )(00)(\d{2})$#', '$1$2:$3', $your_value() ));
?>
Faust
17-Aug-2004 10:44
i found one Mistake. This is right:
function getMonday ($kwName)
{
$thisWo = date("W");
$diffWo = $kwName-$thisWo;
if (date("w") == 1) {
$monday = strtotime("this Monday");
} else {
$monday = strtotime("last Monday");
}
$plus_week = "+".$diffWo." week";
$nextMon = date("d.m.y", strtotime($plus_week, $monday));
echo $nextMon;
}
Faust
16-Aug-2004 12:56
the easiest way (i think :) to get a monday from a week's number:
<?php
function getMonday ($kwName)
{
$thisWo = date("W");
$diffWo = $kwName-$thisWo;
$monday = strtotime("this Monday");
$plus_week = "+".$diffWo." week";
$nextMon = date("d.m.y", strtotime($plus_week, $monday));
echo $nextMon;
}
?>
where $kwName - a week's number.
viazenetti
05-Aug-2004 09:53
Another note concerning the 'next' syntax.
In 4.2.2 the following code did the expected
<?
$myDate = strtotime('next month', $myDate);
?>
Since 4.3.3 the result is the month after the next month.
For example when myDate was February, the 'next month' would be April instead of March as you would expect.
A workaround that works in 4.2. ans 4.3. is this:
<?
$myDate = strtotime('+1 month', $myDate);
?>
OJW
27-Jun-2004 02:06
I believe these functions can be "stacked" to produce some quite useful results. For example, the following code gives you the last Monday in August (a UK bank holiday)
<?php
$LastMondayAugust = strtotime("-1 week monday", strtotime("1 september 2004")) + 43200;
?>
"-1 week" gives you the week before 1 september
"monday" increases the day until it's a monday
43200 is 12 hours in seconds (if you use dates at midnight, a timezone change will occasionally put you one hour into the wrong day)
php at bucksvsbytes dot com
22-Jun-2004 07:15
strtotime (in PHP 4.2.2 anyway) doesn't seem to support fractional seconds, even though the underlying GNU routines document them. Example:
<?php strtotime('2004-06-13 09:20:00.0') ?> returns "12/31/69, 06:59:59" (INCORRECT due to decimal seconds)
<?php strtotime('2004-06-13 09:20:00') ?> returns "6/13/04, 09:20:00" (CORRECT, no decimal seconds)
briwood at berkeley dot edu
22-Apr-2004 07:12
Some verisions of Oracle return dates in this format by default: e.g. 02-APR-70
Best way around this is to use Oracle's to_char() function:
SELECT to_char(BIRTHDAY,'YYYY-MM-DD') FROM PEOPLE
(PHP 4.3.2 Debian Linux Kernal 2.4.8 #3)
Be very careful of an approach using strtotime() and date() to convert such timestamps. A strtotime() problem appears prior to 1969.
<?php
$dt = array('16-JUN-03','01-JAN-70', '03-MAY-69', '29-DEC-69', '01-JAN-68', '04-APR-38');
foreach ($dt as $d) {
print $d ."\n";
print "strtotime: " . strtotime($d) ."\n";
print "strtotime and date: " . date("Y-m-d", strtotime($d)) ."\n\n";
}
?>
OUTPUT:
16-JUN-03
strtotime: 1055746800
strtotime and date: 2003-06-16
01-JAN-70
strtotime: 28800
strtotime and date: 1970-01-01
03-MAY-69
strtotime: -20970000
strtotime and date: 1969-05-03
29-DEC-69
strtotime: -230400
strtotime and date: 1969-12-29
01-JAN-68
strtotime: -1
strtotime and date: 1969-12-31
04-APR-38
strtotime: -1
strtotime and date: 1969-12-31
aspies at hitwin dot com
19-Apr-2004 11:18
In PHP Version 4.2.2 the following statements are equal:
strtotime("next Monday", $date) = strtotime("first Monday", $date) or
strtotime("next Monday", $date) = strtotime("1 Monday", $date) or
strtotime("next Monday", $date) = strtotime("Monday", $date)
By PHP Version 4.3.3 this changed to:
strtotime("next Monday", $date) = strtotime("second Monday", $date) or
strtotime("next Monday", $date) = strtotime("2 Monday", $date)
Obviously the implementation changed according to the GNU standard.
(See also till\at\klimpong\dot\com 26-Feb-2004 03:51 and charlie at brown dot org 21-Jan-2004 05:24)
Be aware, that you have to correct older functions if you are upgrading your PHP-Version. So, for Example, I have to correct the following helpful function, that was posted somewhere earlier here:
################
# Returns date of the Monday for given number of Iso Week(1..53)
# and year. Output is UNIX-Timestamp
<?php
function get_monday ($week, $year="")
{
$first_date = strtotime("1 January ".($year ? $year : date("Y")));
$w_day = date("w", $first_date);
$d_week = 0;
switch($w_day)
{
case 1: $monday = $first_date;
break;
case 2:
case 3:
case 4: $d_week = 604800;
default:$monday = strtotime("Monday", $first_date)-$d_week;
};
$plus_week = "+".($week-1)." week";
return (strtotime($plus_week, $monday));
};
?>
cryogen at mac dot com
06-Apr-2004 02:39
I neglected to include the solution in my last post for using strtotime() with date-time data stored in GMT. Append the string "GMT" to all of your datetimes pulled from MySQL or other database that store date-times in the format "yyyy-mm-dd hh:ii:ss" just prior to converting them to a unix timestamp with strtotime(). This will ensure you get a valid GMT result for times during daylight savings.
EXAMPLE:
<?php
$date_time1 = strtotime("2004-04-04 02:00:00"); // returns bad value -1 due to DST
$date_time2 = strtotime("2004-04-04 02:00:00 GMT"); // works great!
?>
cryogen at mac dot com
06-Apr-2004 01:42
It appears that the strtotime() function returns a value of "-1" for the hour that is skipped during the summer daylight savings time (2:00 am on first Sunday of April). For example if you enter the following:
<?php
$new_dt = strtotime("2004-04-04 02:00:00");
if ($new_dt == -1) echo "Could not convert date-time!";
echo date("m/d/Y H:i:s", $new_dt);
?>
will print:
-----------
Could not convert date-time
12/31/1969 15:59:59
Any time between 02:00:00 and 2:59:59, which is the hour we "spring forward", strtotime() will produce the bad result. This is NOT true for the "fall back" on the last Sunday of October at 2:00 am when the clocks are set back an hour, which produces a correct result. This can cause problems if you are storing dates in GMT time, for example, in your database, and need to convert them to a unix timestamp for calculations in your PHP scripts. GMT time does not change during daylight savings time.
kiscix at hotmail dot com
05-Apr-2004 01:37
Sometime due to Timezone,
strtotime('last sunday') will return the last saturday.
To be sure that will never happen, use strtotime('last sunday 12:00:00')
kyle at frozenonline dot com
01-Jan-2004 06:24
I was having trouble parsing Apache log files that consisted of a time entry (denoted by %t for Apache configuration). An example Apache-date looks like: [21/Dec/2003:00:52:39 -0500]
Apache claims this to be a 'standard english format' time. strtotime() feels otherwise.
I came up with this function to assist in parsing this peculiar format.
<?php
function from_apachedate($date)
{
list($d, $M, $y, $h, $m, $s, $z) = sscanf($date, "[%2d/%3s/%4d:%2d:%2d:%2d %5s]");
return strtotime("$d $M $y $h:$m:$s $z");
}
?>
Hope it helps anyone else seeking such a conversion. |
|
|
|
|
|