PHP Velho Oeste 2024

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 21 notes

up
120
Jimmy
12 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
ivijan dot stefan at gmail dot com
9 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
11
adityabhai at gmail dot com
10 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
6
FiraSEO
11 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
0
remindfwd at gmail dot com
2 years ago
To get one month back, then simply write:

```
$oneMonthBack = date( DateTime::ISO8601, strtotime('-1 month' ));
```

// results (for eg.)
// 2021-12-21T13:44:05+0000
up
3
Bas Vijfwinkel
12 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
5
SpikeDaCruz
18 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
2
Anonymous
10 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
1
matthew dot hotchen at worldfirst dot com
10 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
-1
bruslbn at gmail dot com
6 years 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
-2
ghotinet
13 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
-6
Charlie
8 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
-6
mirco dot babin at gmail dot com
5 years ago
One important thing you should remember is that the timestamp value returned by time() is time-zone agnostic and gets the number of seconds since 1 January 1970 at 00:00:00 UTC. This means that at a particular point in time, this function will return the same value in the US, Europe, India, Japan, ...

date() will format a time-zone agnostic timestamp according to the default timezone set with date_default_timezone_set(...). Local time. If you want to output as UTC time use:

<?php
function dateUTC($format, $timestamp = null)
{
    if (
$timestamp === null) $timestamp = time();

   
$tz = date_default_timezone_get();
   
date_default_timezone_set('UTC');

   
$result = date($format, $timestamp);

   
date_default_timezone_set($tz);
    return
$result;
}
/>
up
-9
david dot thomas at elliott-thomas dot com dot au
7 years 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
-8
rc at macshot dot de
7 years 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
-10
Anonymous
8 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
-7
Jaap
3 years ago
For users looking to format a unix timestamp with microseconds to mysql datetime, this function should do the trick:
<?php
       
function sqlDateTimeFromMicroTimestamp(int $microtimestamp):string{
           
$dt = new \DateTimeImmutable();
           
$normalTimestamp = (int)floor($microtimestamp / 1000000);
           
$sqlTimestampWithoutMicroseconds = $dt->setTimestamp($normalTimestamp)->format('Y-m-d H:i:s');
           
$sqlTimestampWithMicroseconds = $sqlTimestampWithoutMicroseconds . '.'. ($microtimestamp % 1000000);
            return
$sqlTimestampWithMicroseconds;
        }
?>
up
-13
bruslbn at gmail dot com
6 years 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
-8
mparsa1372 at gmail dot com
3 years ago
The example below formats today's date in three different ways:

<?php
echo "Today is " . date("Y/m/d") . "<br>";
echo
"Today is " . date("Y.m.d") . "<br>";
echo
"Today is " . date("Y-m-d") . "<br>";
echo
"Today is " . date("l");
?>
up
-21
bruslbn at gmail dot com
6 years 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
-28
arth dot inbox at gmail dot com
5 years ago
Looks like date('u') is not microseconds, but is positive difference from rest part.

php > echo (DateTime::createFromFormat('U.u', '-128649659.999998'))->format('Y-m-d H:i:s.u U.u');
1965-12-03 23:59:01.999998 -128649659.999998

`U.u` parsed and formatted same, but means not 1965-12-03 23:59:00.000002.
Other words correct timestamp for example above is (-128649659 + 0.999998). 

Less confusing format for it is: 

php > echo DateTime::createFromFormat('U\+0.u', '-128649660+0.000002')->format('Y-m-d H:i:s.u');
1965-12-03 23:59:00.000002

Is that bug or feature?
To Top