PHP 7.1.21 Released

date

(PHP 4, PHP 5, PHP 7)

date로컬 날짜/시간을 형식화합니다

설명

string date ( string $format [, int $timestamp ] )

정수형으로 주어지는 timestamp나, timestamp가 주어지지 않았을 경우에는 현재 로컬 시간을 사용하여, 주어진 포맷 문자열에 따라 형식화한 문자열을 반환합니다. 즉 timestamp는 선택적이고, 기본값은 time()의 값입니다.

인수

format

출력하는 날짜 string의 형식. 아래 형식화 옵션을 참고하십시오.

다음 문자들을 format 인수 문자열로 인식합니다.
format 문자 설명 반환값 예시
--- ---
d 일, 앞에 0이 붙는 2 숫자 01에서 31
D 요일 글자 표현, 3 문자 Mon에서 Sun
j 앞에 0이 붙지 않는 일 1에서 31
l (소문자 'L') 요일의 완전한 글자 표현 Sunday에서 Saturday
N 요일의 ISO-8601 숫자 표현 (PHP 5.1.0에서 추가) 1(월요일)에서 7(일요일)
S 일 영어 접미사, 2 문자 st, nd, rd, th. j와 잘 맞습니다.
w 요일 숫자 표현 0(일요일)에서 6(토요일)
z 해당 연도 일차 (0에서 시작) 0에서 365
--- ---
W ISO-8601 주차, 주는 월요일에 시작 (PHP 4.1.0에서 추가) 예시: 42 (그 해의 42번째 주)
--- ---
F January나 March 같은 월의 완전한 글자 표현 January에서 December
m 0이 붙는 월 숫자 표현 01에서 12
M 월의 축약 글자 표현, 3 문자 Jan에서 Dec
n 0이 붙지 않는 월 숫자 표현 1에서 12
t 주어진 월의 일 수 28에서 31
--- ---
L 윤년 여부 윤년엔 1, 그 외엔 0
o ISO-8601 연도. Y와 같지만, ISO 주차(W)가 전해나 다음해에 해당하면, 그 연도를 사용합니다. (PHP 5.1.0에서 추가) 예시: 19992003
Y 연도의 완전한 숫자 표현, 4 숫자 예시: 19992003
y 연도의 두 숫자 표현 예시: 9903
시간 --- ---
a 오전과 오후의 소문자 am 또는 pm
A 오전과 오후의 대문자 AM 또는 PM
B 스와치 인터넷 시간 000에서 999
g 0이 붙지 않는 12시간 형식 시 1에서 12
G 0이 붙지 않는 24시간 형식 시 0에서 23
h 0이 붙는 12시간 형식 시 01에서 12
H 0이 붙는 24시간 형식 시 00에서 23
i 0이 붙는 분 00에서 59
s 초, 0이 붙음 00에서 59
u 마이크로초 (PHP 5.2.2에서 추가) 예시: 54321
시간대 --- ---
e 시간대 식별자 (PHP 5.1.0에서 추가) 예시: UTC, GMT, Atlantic/Azores
I (대문자 i) 일광 절약 시간 여부 일광 절약 시간이면 1, 아니면 0
O 그리니치 시간(GMT)과 시차 예시: +0200
P 시와 분 사이에 콜론이 들어가는 그리니치 시간(GMT)과 차이 예시: +02:00
T 시간대 축약어 예시: EST, MDT ...
Z 시간대 오프셋 초. UTC 서쪽은 항상 음수, UTC 동쪽은 항상 양수 -43200에서 50400
날짜/시간 표현 --- ---
c ISO 8601 날짜 (PHP 5에서 추가) 2004-02-12T15:19:21+00:00
r » RFC 2822 형식 날짜 예시: Thu, 21 Dec 2000 16:01:07 +0200
U 유닉스 에포치(January 1 1970 00:00:00 GMT)부터 초수 time() 참조

format 문자열로 인식되지 않는 문자는 그대로 출력합니다. Z 형식은 gmdate()를 이용할 때는 항상 0을 반환합니다.

Note:

이 함수는 integer 타임스탬프만 받아들이므로, u 형식 문자는 date_create()로 만들어진 사용자 기반 타임스탬프를 date_format() 함수에 이용할 때만 유용합니다.

timestamp

선택적인 timestamp 인수는 timestamp가 주어지지 않았을 경우, 현재 로컬 시간을 기본값으로 가지는 integer 유닉스 타임스탬프입니다. 즉, 기본값은 time() 값입니다.

반환값

형식화된 날짜 문자열을 반환합니다. timestamp에 숫자가 아닌 값을 사용하면, FALSE를 반환하고 E_WARNING 등급 오류가 발생합니다.

오류/예외

모든 날짜/시간 함수 호출은 시간대가 유효하지 않을 때 E_NOTICE를, 시스템 설정이나 TZ 환경 변수를 사용할 때 E_STRICTE_WARNING 메세지를 생성합니다. date_default_timezone_set()을 참고하십시오.

변경점

버전 설명
5.1.0 유효한 타임스탬프 범위는 보통 Fri, 13 Dec 1901 20:45:54 GMT 에서 Tue, 19 Jan 2038 03:14:07 GMT 입니다. (이 날짜들은 32비트 부호 있는 정수의 최소값과 최대값에 해당합니다) 그러나, PHP 5.1.0 이전에는 몇몇 시스템에서 이 범위가 01-01-1970에서 19-01-2038로 제한되었습니다. (윈도우 등)
5.1.0

시간대 오류시 E_STRICTE_NOTICE가 발생합니다.

5.1.1 format 인수 지정에 사용할 수 있는 유용한 표준 날짜/시간 상수가 있습니다.

예제

Example #1 date() 예제코드

<?php
// 기본 시간대를 설정. PHP 5.1 부터 가능.
date_default_timezone_set('UTC');


// 출력 예시: Monday
echo date("l");

// 출력 예시: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');

// 출력: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " date("l"mktime(000712000));

/* 형식 인수로 상수 사용하기 */
// 출력 예시: Mon, 15 Aug 2005 15:12:46 UTC
echo date(DATE_RFC822);

// 출력 예시: 2000-07-01T00:00:00+00:00
echo date(DATE_ATOMmktime(000712000));
?>

format 문자열로 인식하는 문자 바로 앞에 백슬래시를 붙여서 이스케이프를 함으로써, 인식하는 것 막을 수 있습니다. 백슬래시가 붙는 문자가 이미 특별한 의미를 가지고 있다면, 백슬래시를 이스케이프해야 합니다.

Example #2 date()의 회피 문자

<?php
// 다음의 출력: Wednesday the 15th
echo date("l \\t\h\e jS");
?>

date()mktime()을 함께 사용함으로써 미래나 과거의 시간을 얻을 수 있습니다.

Example #3 date()mktime() 예제

<?php
$tomorrow  
mktime (0,0,0,date("m")  , date("d")+1date("Y"));
$lastmonth mktime (0,0,0,date("m")-1date("d"),   date("Y"));
$nextyear  mktime (0,0,0,date("m"),   date("d"),   date("Y")+1);
?>

Note:

이는 일광 절약 시간을 고려하기 때문에, 단순히 timestamp에 하루나 한달에 해당하는 초를 더하는 것보다 신뢰할 수 있습니다.

date() 형식화의 몇몇 예제. 모든 다른 문자들도 이스케이프 해야함에 주의하십시오. 현재 특별한 의미를 가진 어떤 것이 바람직하지 못한 결과를 가져올 수 있고, 앞으로의 PHP 버전에서는 다른 문자들도 지정될 수가 있습니다. 이스케이프 할 때는, \n이 줄바꿈으로 인식 되는 것과 같은 예을 피하기 위해서는 작은 따옴표를 사용해야만 합니다.

Example #4 date() 형식화

<?php
// Assuming today is: March 10th, 2001, 5:16:18 pm

$today date("F j, Y, g:i a");                 // March 10, 2001, 5:16 pm
$today date("m.d.y");                         // 03.10.01
$today date("j, n, Y");                       // 10, 3, 2001
$today date("Ymd");                           // 20010310
$today date('h-i-s, j-m-y, it is w Day');     // 05-16-17, 10-03-01, 1631 1618 6 Fripm01
$today date('\i\t \i\s \t\h\e jS \d\a\y.');   // It is the 10th day.
$today date("D M j G:i:s T Y");               // Sat Mar 10 17:16:18 MST 2001
$today date('H:m:s \m \i\s\ \m\o\n\t\h');     // 17:16:18 m is month
$today date("H:i:s");                         // 17:16:18
?>

다른 언어로 날짜를 형식화 하기 위해서는, date() 대신에 setlocale()strftime() 함수를 사용해야 합니다.

주의

Note:

날짜의 문자 표현에서 타임스탬프를 만드려면, strtotime()을 사용할 수 있습니다. 추가적으로, 몇몇 데이터베이스는 날짜 형식에서 타임스탬프로 바꾸는 함수를 가지고 있습니다. (MySQL의 » UNIX_TIMESTAMP 등)

Tip

PHP 5.1부터 요청의 시작 타임스탬프가 $_SERVER['REQUEST_TIME']에 존재합니다.

참고

  • getlastmod() - 페이지를 수정한 최종 시간을 얻습니다
  • gmdate() - Format a GMT/UTC date/time
  • mktime() - Get Unix timestamp for a date
  • strftime() - Format a local time/date according to locale settings
  • time() - Return current Unix timestamp

add a note add a note

User Contributed Notes 33 notes

up
109
Jimmy
6 years ago
Things to be aware of when using week numbers with years.

<?php
echo date("YW", strtotime("2011-01-07")); // gives 201101
echo date("YW", strtotime("2011-12-31")); // gives 201152
echo date("YW", strtotime("2011-01-01")); // gives 201152 too
?>

BUT

<?php
echo date("oW", strtotime("2011-01-07")); // gives 201101
echo date("oW", strtotime("2011-12-31")); // gives 201152
echo date("oW", strtotime("2011-01-01")); // gives 201052 (Year is different than previous example)
?>

Reason:
Y is year from the date
o is ISO-8601 year number
W is ISO-8601 week number of year

Conclusion:
if using 'W' for the week number use 'o' for the year.
up
20
adityabhai at gmail dot com
4 years ago
For Microseconds, we can get by following:

echo date('Ymd His'.substr((string)microtime(), 1, 8).' e');

Thought, it might be useful to someone !
up
21
FiraSEO
5 years ago
this how you make an HTML5 <time> tag correctly

<?php

echo '<time datetime="'.date('c').'">'.date('Y - m - d').'</time>';

?>

in the "datetime" attribute you should put a machine-readable value which represent time , the best value is a full time/date with ISO 8601 ( date('c') ) ,,, the attr will be hidden from users

and it doesn't really matter what you put as a shown value to the user,, any date/time format is okay !

This is very good for SEO especially search engines like Google .
up
6
david dot thomas at elliott-thomas dot com dot au
1 year ago
Prior to PHP 5.6.23,  Relative Formats for the start of the week aligned with PHP's (0=Sunday,6=Saturday). Since 5.6.23,  Relative Formats for the start of the week align with ISO-8601 (1=Monday,7=Sunday). (http://php.net/manual/en/datetime.formats.relative.php)

This can produce different, and seemingly incorrect, results depending on your PHP version and your choice of 'w' or 'N' for the Numeric representation of the day of the week:

<?php
echo "Today is Sun 2 Oct 2016, day ",date('w',strtotime('2016-10-02'))," of this week. "
echo
"Day ",date('w',strtotime('2016-10-02 Monday next week'))," of next week is ",date('d M Y',strtotime('2016-10-02 Monday next week')),"<br />";

echo
"Today is Sun 2 Oct 2016, day ",date('N',strtotime('2016-10-02'))," of this week. "
echo
"Day ",date('w',strtotime('2016-10-02 Monday next week'))," of next week is ",date('d M Y',strtotime('2016-10-02 Monday next week'));
?>

Prior to PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 10 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 10 Oct 2016

Since PHP 5.6.23, this results in:

Today is Sun 2 Oct 2016, day 0 of this week. Day 1 of next week is 03 Oct 2016
Today is Sun 2 Oct 2016, day 7 of this week. Day 1 of next week is 03 Oct 2016
up
14
ivijan dot stefan at gmail dot com
3 years ago
If you have a problem with the different time zone, this is the solution for that.
<?php
// first line of PHP
$defaultTimeZone='UTC';
if(
date_default_timezone_get()!=$defaultTimeZone)) date_default_timezone_set($defaultTimeZone);

// somewhere in the code
function _date($format="r", $timestamp=false, $timezone=false)
{
   
$userTimezone = new DateTimeZone(!empty($timezone) ? $timezone : 'GMT');
   
$gmtTimezone = new DateTimeZone('GMT');
   
$myDateTime = new DateTime(($timestamp!=false?date("r",(int)$timestamp):date("r")), $gmtTimezone);
   
$offset = $userTimezone->getOffset($myDateTime);
    return
date($format, ($timestamp!=false?(int)$timestamp:$myDateTime->format('U')) + $offset);
}

/* Example */
echo 'System Date/Time: '.date("Y-m-d | h:i:sa").'<br>';
echo
'New York Date/Time: '._date("Y-m-d | h:i:sa", false, 'America/New_York').'<br>';
echo
'Belgrade Date/Time: '._date("Y-m-d | h:i:sa", false, 'Europe/Belgrade').'<br>';
echo
'Belgrade Date/Time: '._date("Y-m-d | h:i:sa", 514640700, 'Europe/Belgrade').'<br>';
?>
This is the best and fastest solution for this problem. Working almost identical to date() function only as a supplement has the time zone option.
up
7
matthew dot hotchen at worldfirst dot com
4 years ago
FYI: there's a list of constants with predefined formats on the DateTime object, for example instead of outputting ISO 8601 dates with:

<?php
echo date('c');
?>

or

<?php
echo date('Y-m-d\TH:i:sO');
?>

You can use

<?php
echo date(DateTime::ISO8601);
?>

instead, which is much easier to read.
up
7
Anonymous
4 years ago
It's common for us to overthink the complexity of date/time calculations and underthink the power and flexibility of PHP's built-in functions.  Consider http://php.net/manual/en/function.date.php#108613

<?php
function get_time_string($seconds)
{
    return
date('H:i:s', strtotime("2000-01-01 + $seconds SECONDS"));
}
up
3
Anonymous
2 years ago
If timestamp is a string, date converts it to an integer in a possibly unexpected way:

<?php
echo (int)'0x10'; //0
echo intval('0x10'); //0
echo date('s', '0x10'); //gives 16
//however, no octal conversion:
echo date('s', '010'); //gives 10
?>

(PHP 5.6.16)
up
1
Charlie
2 years ago
For HTML5 datetime-local HTML input controls (http://www.w3.org/TR/html-markup/input.datetime-local.html) use format example: 1996-12-19T16:39:57

To generate this, escape the 'T', as shown below:

<?php
date
('Y-m-d\TH:i:s');
?>
up
5
mel dot boyce at gmail dot com
12 years ago
I've been flicking through the comments looking for some succinct date code and have noticed an alarming number of questions and over-burdened examples related to date mathematics. One of the most useful skills you can utilize when performing date math is taking full advantage of the UNIX timestamp. The UNIX timestamp was built for this kind of work.

An example of this relates to a comment made by james at bandit-dot-co-dot-en-zed. James was looking for a way to calculate the number of days which have passed since a certain date. Rather than using mktime() and a loop, James can subtract the current timestamp from the timestamp of the date in question and divide that by the number of seconds in a day:
<?php
$days
= floor((time() - strtotime("01-Jan-2006"))/86400);
print(
"$days days have passed.\n");
?>

Another usage could find itself in a class submitted by Kyle M Hall which aids in the creation of timestamps from the recent past for use with MySQL. Rather than the looping and fine tuning of a date, Kyle can use the raw UNIX timestamps (this is untested code):
<?php
$ago
= 14; // days
$timestamp = time() - ($ago * 86400);
?>

Hopefully these two examples of "UNIX-style" timestamp usage will help those finding date mathematics more elusive than it should be.
up
2
Bas Vijfwinkel
6 years ago
Note that some formatting options are different from MySQL.
For example using a 24 hour notation without leading zeros is the option '%G' in PHP but '%k' in MySQL.
When using dynamically generated date formatting string, be careful to generate the correct options for either PHP or MySQL.
up
0
tekintian at gmail dot com
5 months ago
<?php

/**
*  计算两个日期相隔时间:年、月、日、时、分、秒 总计天数
* @author TekinTian <tekintian#gmail.com>
* @param string $start_time 开始时间 必须 [格式如:2011-11-5 10:01:01]
* @param string $end_time 结束时间 选填,不提供默认未当前时间 [格式如:2012-12-01 10:01:01]
* @return array Array ( [y] => 年 [m] => 月 [d] => 日 [h] => 时 [i] => 分 [s] => 秒 [a] => 合计天数 )
*/
function get_date_diff($start_time,$end_time=''){
   
$end_time = ($end_time=='')?date("Y-m-d H:i:s"):$end_time;
   
$datetime1 = new \DateTime($start_time);
   
$datetime2 = new \DateTime($end_time);
   
$interval = $datetime1->diff($datetime2);
   
$time['y'] = $interval->format('%y');
   
$time['m'] = $interval->format('%m');
   
$time['d'] = $interval->format('%d');
   
$time['h'] = $interval->format('%H');
   
$time['i'] = $interval->format('%i');
   
$time['s'] = $interval->format('%s');
   
$time['a'] = $interval->format('%a');    // 两个时间相差总天数
   
return $time;
}

//demo use
// echo '<pre>';
print_r(get_date_diff('2016-10-15 10:01:56'));
// echo '</pre>';
up
0
bruslbn at gmail dot com
6 months ago
In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

if($year%4 == 0 && $year%100 != 0) {
    $leapYear = 1;
} elseif($year%400 == 0) {
    $leapYear = 1;                          
} else {
    $leapYear = 0;
}
up
0
bruslbn at gmail dot com
6 months ago
In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

if($year%4 == 0 && $year%100 != 0) {
    $leapYear = 1;
} elseif($year%400 == 0) {
    $leapYear = 1;                          
} else {
    $leapYear = 0;
}
up
3
ghotinet
7 years ago
Most spreadsheet programs have a rather nice little built-in function called NETWORKDAYS to calculate the number of business days (i.e. Monday-Friday, excluding holidays) between any two given dates. I couldn't find a simple way to do that in PHP, so I threw this together. It replicates the functionality of OpenOffice's NETWORKDAYS function - you give it a start date, an end date, and an array of any holidays you want skipped, and it'll tell you the number of business days (inclusive of the start and end days!) between them.

I've tested it pretty strenuously but date arithmetic is complicated and there's always the possibility I missed something, so please feel free to check my math.

The function could certainly be made much more powerful, to allow you to set different days to be ignored (e.g. "skip all Fridays and Saturdays but include Sundays") or to set up dates that should always be skipped (e.g. "skip July 4th in any year, skip the first Monday in September in any year"). But that's a project for another time.

<?php

function networkdays($s, $e, $holidays = array()) {
   
// If the start and end dates are given in the wrong order, flip them.   
   
if ($s > $e)
        return
networkdays($e, $s, $holidays);

   
// Find the ISO-8601 day of the week for the two dates.
   
$sd = date("N", $s);
   
$ed = date("N", $e);

   
// Find the number of weeks between the dates.
   
$w = floor(($e - $s)/(86400*7));    # Divide the difference in the two times by seven days to get the number of weeks.
   
if ($ed >= $sd) { $w--; }        # If the end date falls on the same day of the week or a later day of the week than the start date, subtract a week.

    // Calculate net working days.
   
$nwd = max(6 - $sd, 0);    # If the start day is Saturday or Sunday, add zero, otherewise add six minus the weekday number.
   
$nwd += min($ed, 5);    # If the end day is Saturday or Sunday, add five, otherwise add the weekday number.
   
$nwd += $w * 5;        # Add five days for each week in between.

    // Iterate through the array of holidays. For each holiday between the start and end dates that isn't a Saturday or a Sunday, remove one day.
   
foreach ($holidays as $h) {
       
$h = strtotime($h);
        if (
$h > $s && $h < $e && date("N", $h) < 6)
           
$nwd--;
    }

    return
$nwd;
}

$start = strtotime("1 January 2010");
$end = strtotime("13 December 2010");

// Add as many holidays as desired.
$holidays = array();
$holidays[] = "4 July 2010";            // Falls on a Sunday; doesn't affect count
$holidays[] = "6 September 2010";        // Falls on a Monday; reduces count by one

echo networkdays($start, $end, $holidays);    // Returns 246

?>

Or, if you just want to know how many work days there are in any given year, here's a quick function for that one:

<?php

function workdaysinyear($y) {
   
$j1 = mktime(0,0,0,1,1,$y);
    if (
date("L", $j1)) {
        if (
date("N", $j1) == 6)
            return
260;
        elseif (
date("N", $j1) == 5 or date("N", $j1) == 7)
            return
261;
        else
            return
262;
    }
    else {
        if (
date("N", $j1) == 6 or date("N", $j1) == 7)
            return
260;
        else
            return
261;
    }
}

?>
up
0
rc at macshot dot de
1 year ago
At least in PHP 5.5.38 date('j.n.Y', 2222222222) gives a result of 2.6.2040.

So date is not longer limited to the minimum and maximum values for a 32-bit signed integer as timestamp.
up
1
bakerj417 at gmail dot com
6 years ago
If you are having an issue getting u to work so is everyone else. The solution that I am using which I found on another site(so not taking credit) is to use this:

     date("Y/m/d H:i:s"). substr((string)microtime(), 1, 6);

that will give you:

     yyyy/mm/dd hh:ii:ss.uuuuuu

hope this helps someone in need!

thanks all
up
3
SpikeDaCruz
12 years ago
The following function will return the date (on the Gregorian calendar) for Orthodox Easter (Pascha).  Note that incorrect results will be returned for years less than 1601 or greater than 2399. This is because the Julian calendar (from which the Easter date is calculated) deviates from the Gregorian by one day for each century-year that is NOT a leap-year, i.e. the century is divisible by 4 but not by 10.  (In the old Julian reckoning, EVERY 4th year was a leap-year.)

This algorithm was first proposed by the mathematician/physicist Gauss.  Its complexity derives from the fact that the calculation is based on a combination of solar and lunar calendars.

<?php
function getOrthodoxEaster($date){
 
/*
   Takes any Gregorian date and returns the Gregorian
   date of Orthodox Easter for that year.
  */
 
$year = date("Y", $date);
 
$r1 = $year % 19;
 
$r2 = $year % 4;
 
$r3 = $year % 7;
 
$ra = 19 * $r1 + 16;
 
$r4 = $ra % 30;
 
$rb = 2 * $r2 + 4 * $r3 + 6 * $r4;
 
$r5 = $rb % 7;
 
$rc = $r4 + $r5;
 
//Orthodox Easter for this year will fall $rc days after April 3
 
return strtotime("3 April $year + $rc days");
}
?>
up
0
Tim Connolly
6 years ago
Here's my solution for looking up the month number by name (used when parsing an 'ls'):

<?php
 
for($m=1;$m<=12;$m++){
   
$month=date("M",mktime(0,0,0,$m,1,2000));
   
$mon["$month"]=$m;
  }
?>
up
0
Just.Kevin
9 years ago
In order to determine if a year is a leap year an earlier poster suggested simply checking to see if the year is a multiple of four:

<?php
function is_leapyear_broken($year = 2004) {
return (
$year%4)==0;
}
?>

While this will work for the majority of years it will not work on years that are multiples of 100 but not multiples of 400 i.e.(2100).
A function not using php's date() function that will also account for this small anomaly in leap years:

<?php
function is_leapyear_working($year = 2004) {
    if(((
$year%4==0) && ($year%100!=0)) || $year%400==0) {
        return
true;
    }
    return
false;
}
?>

While is_leapyear_working will not return true for the few non-leap years divisible by four I couldn't tell you if this is more or less efficient than using php's date() as an even earlier poster suggested:

<?php
function is_leapyear($year = 2004) {
$is_leap = date('L', strtotime("$year-1-1"));
return
$is_leap;
}
?>
up
-1
ccb_bc at hotmail dot com
6 months ago
<?php
   
/**
    * Convert Date formats:
    */

    // $date '1989/11/25'
    // $date '1989-11-25'
    // $date '1989.11.25'
   
if(preg_match("/^[0-9]{4}(\/|-|.)(0[1-9]|1[0-2])(\/|-|.)(0[1-9]|[1-2][0-9]|3[0-1])$/", $date)){
        return
substr($date, 8, 2).substr($date, 7,1).substr($date, 5,2).substr($date, 4,1).substr($date, 0,4);
       
// Result: '25/11/1989' - OR - '25-11-1989' - OR - '25.11.1989'
   
}

   
// $date = '25/11/1989'
    // $date = '25-11-1989'
    // $date = '25.11.1989'
   
if(preg_match("/^(0[1-9]|[1-2][0-9]|3[0-1])(\/|-|.)(0[1-9]|1[0-2])(\/|-|.)[0-9]{4}$/", $date)){
        return
substr($date, 6, 4).substr($date, 5,1).substr($date, 3,2).substr($date, 2,1).substr($date, 0,2);
       
// Result: '1989/11/25' - OR - '1989-11-25' - OR - '1989.11.25'
   
}
?>
up
-3
Anonymous
4 years ago
To quickly convert date("N") to a 0 based index with Sunday being represented as 0, you can run it against modulus 7:

<?php
$first_of_month_index
= date('N', strtotime('4/1/1990')) % 7;
?>
up
-6
eduardo at digmotor dot com dot br
9 years ago
Thanks to tcasparr at gmail dot com for the great idea (at least for me) ;)
I changed the code a little to replicate the functionality of date_parse_from_format, once I don't have PHP 5.3.0 yet. This might be useful for someone. Hope you don't mind changing your code tcasparr at gmail dot com.

<?php
/*******************************************************
* Simple function to take in a date format and return array of associated
* formats for each date element
*
* @return array
* @param string $strFormat
*
* Example: Y/m/d g:i:s becomes
* Array
* (
*     [year] => Y
*     [month] => m
*     [day] => d
*     [hour] => g
*     [minute] => i
*     [second] => s
* )
*
*  This function is needed for  PHP < 5.3.0
********************************************************/
function dateParseFromFormat($stFormat, $stData)
{
   
$aDataRet = array();
   
$aPieces = split('[:/.\ \-]', $stFormat);
   
$aDatePart = split('[:/.\ \-]', $stData);
    foreach(
$aPieces as $key=>$chPiece)   
    {
        switch (
$chPiece)
        {
            case
'd':
            case
'j':
               
$aDataRet['day'] = $aDatePart[$key];
                break;
               
            case
'F':
            case
'M':
            case
'm':
            case
'n':
               
$aDataRet['month'] = $aDatePart[$key];
                break;
               
            case
'o':
            case
'Y':
            case
'y':
               
$aDataRet['year'] = $aDatePart[$key];
                break;
           
            case
'g':
            case
'G':
            case
'h':
            case
'H':
               
$aDataRet['hour'] = $aDatePart[$key];
                break;   
               
            case
'i':
               
$aDataRet['minute'] = $aDatePart[$key];
                break;
               
            case
's':
               
$aDataRet['second'] = $aDatePart[$key];
                break;           
        }
       
    }
    return
$aDataRet;
}
?>

Also, if you need to change the format of dates:

<?php
function changeDateFormat($stDate,$stFormatFrom,$stFormatTo)
{
 
// When PHP 5.3.0 becomes available to me
  //$date = date_parse_from_format($stFormatFrom,$stDate);
  //For now I use the function above
 
$date = dateParseFromFormat($stFormatFrom,$stDate);
  return
date($stFormatTo,mktime($date['hour'],
                                   
$date['minute'],
                                   
$date['second'],
                                   
$date['month'],
                                   
$date['day'],
                                   
$date['year']));
}

?>
up
-8
Anonymous
9 years ago
Correct format for a MySQL DATETIME column is
<?php $mysqltime = date ("Y-m-d H:i:s", $phptime); ?>
up
-4
Hayley Watson
1 year ago
If you see the number 86400 in a date calculation, think very hard before deciding that it is correct. Not all days have 86,400 seconds in them. In many places, some days have only 82,800 seconds and some have 90,000. Occasionally, there are even fewer or even more.

Assuming that now plus 86,400 seconds is equivalent to some time tomorrow can sometimes be wrong. It might actually be the day after tomorrow or still today.

It's called Daylight Saving.
up
-1
olivertappin at gmail dot com
4 months ago
If looking for a simple way to return the week number, using Sunday as the first day of the week, please bear in mind you will need to cater for the addition when you reach the end of the year.

<?php

function getSundayWeekNumber(\DateTimeInterface $date): int
{
   
$weekNumber = (int)$date->format('W');

    if (
$date->format('w') === '0') { // Sunday
       
$weekNumber += 1;
        if (
53 === $weekNumber) { // If the week is now 53, subtract 52
           
$weekNumber -= 52;
        }
    }

    return
$weekNumber;
}
up
-1
bruslbn at gmail dot com
6 months ago
In order to define leap year you must considre not only that year can be divide by 4!

The correct alghoritm is:

if (year is not divisible by 4) then (it is a common year)
else if (year is not divisible by 100) then (it is a leap year)
else if (year is not divisible by 400) then (it is a common year)
else (it is a leap year)

So the code should look like this:

if($year%4 == 0 && $year%100 != 0) {
    $leapYear = 1;
} elseif($year%400 == 0) {
    $leapYear = 1;                          
} else {
    $leapYear = 0;
}
up
-11
@PeteWilliams
7 years ago
If you want to use HTML5's <date> tag, the following code will generate the machine-readable value for the 'datetime' attribute:

<?php

/**
* formats the date passed into format required by 'datetime' attribute of <date> tag
* if no intDate supplied, uses current date.
* @param intDate integer optional
* @return string
**/
function getDateTimeValue( $intDate = null ) {

   
$strFormat = 'Y-m-d\TH:i:s.uP';
   
$strDate = $intDate ? date( $strFormat, $intDate ) : date( $strFormat ) ;
   
    return
$strDate;
}

echo
getDateTimeValue();

?>
up
-6
erick900623 at gmail dot com
9 months ago
Ayuda...

Tengo una fecha asignada con la function date("w"), y exactamente a las 5 pm la fecha cambia al siguiente dia. Ej

date("w") - Lunes
y a las 5pm del Lunes cambia a Martes.

Que puede estar pasando
up
-7
rico at redant dot nl
1 year ago
Since PHP 5.6.23 en 7.0.8 the support for requesting the weeknumber for a given date, where the first day of the week is Sunday, has been removed.
For those of us still needing it, here is simple hack to get the job done.

    private function getWeeknumberSundayFirstDayOfWeek(\DateTimeInterface $date)
    {
        if ($date->format('w') === 0) // Sunday
            return (int)$date->format('W') - 1;

        return (int)$date->format('W');
    }
up
-21
Al Roker
2 years ago
When using 'U' to return a UNIX time stamp, you may not get what you expect. In the following example, we try to get the current Unix time stamp for a user in a different timezone.

<?php
// Doesn't work
$timezone = new \DateTimeZone($userTimeZone);
$date = new \DateTime('@' . time(), $timezone);
$date->setTimezone($timezone);
$now = $date->format('U');
?>

$now will return the same (the server's current) Unix time stamp regardless which timezone your user is in.

To get the actual Unix time stamp based on a time zone, replace format('U') as in the following example;

<?php
// This works
$timezone = new \DateTimeZone($userTimeZone);
$date = new \DateTime('@' . time(), $timezone);
$date->setTimezone($timezone);
$now = $date->getTimestamp() + $date->getOffset();
?>
up
-49
crackbeforesoft at gmail dot com
10 months ago
I am glad and wonder about the topic creation. I am visiting this page from a long time ago. This is totally perspective clear ideas. This is sure that the information you shared is clearly identive and fabulous for keeping it in minds. http://crackswar.com/audacity-pro-crack/
up
-49
crackbeforesoft at gmail dot com
10 months ago
I am glad and wonder about the topic creation. I am visiting this page from a long time ago. This is totally perspective clear ideas. This is sure that the information you shared is clearly identive and fabulous for keeping it in minds. http://crackswar.com/audacity-pro-crack/
To Top