PHP의 시간대가 주어지면 현재 날짜를 얻습니까?
America/New_York
PHP 에서 Paul Eggert 형식 ( )의 시간대를 지정하여 오늘 날짜를 얻고 싶습니다 .
다른 답변은 시스템의 모든 날짜에 대한 시간대를 설정합니다. 사용자를 위해 여러 시간대를 지원하려는 경우 항상 잘 작동하는 것은 아닙니다.
짧은 버전은 다음과 같습니다.
<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');
PHP> = 5.2.0에서 작동
지원되는 시간대 목록 : php.net/manual/en/timezones.php
다음은 기존 시간과 사용자 설정에 따라 시간대를 설정 한 버전입니다.
<?php
$usersTimezone = 'America/New_York';
$date = new DateTime( 'Thu, 31 Mar 2011 02:05:59 GMT', new DateTimeZone($usersTimezone) );
echo $date->format('Y-m-d H:i:s');
다음은 프로세스를 좀 더 명확하게 보여주는 더 자세한 버전입니다.
<?php
// Date for a specific date/time:
$date = new DateTime('Thu, 31 Mar 2011 02:05:59 GMT');
// Output date (as-is)
echo $date->format('l, F j Y g:i:s A');
// Output line break (for testing)
echo "\n<br />\n";
// Example user timezone (to show it can be used dynamically)
$usersTimezone = 'America/New_York';
// Convert timezone
$tz = new DateTimeZone($usersTimezone);
$date->setTimeZone($tz);
// Output date after
echo $date->format('l, F j Y g:i:s A');
도서관
- Carbon — 매우 인기있는 날짜 라이브러리입니다.
- Chronos — 불변성에 초점을 맞춘 Carbon의 드롭 인 대체품입니다. 이것이 왜 중요한지 아래를 참조하십시오.
- jenssegers / date — 다국어 지원을 추가하는 Carbon의 확장입니다.
다른 많은 라이브러리를 사용할 수 있다고 확신하지만 이것들은 제가 익숙한 몇 가지입니다.
보너스 레슨 : 불변 날짜 객체
여기있는 동안 앞으로의 두통을 덜어 드리겠습니다. 오늘부터 1 주, 오늘부터 2 주를 계산한다고 가정 해 보겠습니다. 다음과 같은 코드를 작성할 수 있습니다.
<?php
// Create a datetime (now, in this case 2017-Feb-11)
$today = new DateTime();
echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";
$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));
echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
echo "\n<br>";
출력 :
2017-02-11
---
2017-03-04
2017-03-04
2017-03-04
흠 ... 그건 우리가 원했던 것이 아닙니다. DateTime
PHP에서 기존 객체를 수정 하면 업데이트 된 날짜가 반환 될뿐만 아니라 원래 객체도 수정됩니다.
이것이 DateTimeImmutable
들어오는 곳 입니다.
$today = new DateTimeImmutable();
echo $today->format('Y-m-d') . "\n<br>";
echo "---\n<br>";
$oneWeekFromToday = $today->add(DateInterval::createFromDateString('7 days'));
$twoWeeksFromToday = $today->add(DateInterval::createFromDateString('14 days'));
echo $today->format('Y-m-d') . "\n<br>";
echo $oneWeekFromToday->format('Y-m-d') . "\n<br>";
echo $twoWeeksFromToday->format('Y-m-d') . "\n<br>";
출력 :
2017-02-11
---
2017-02-11
2017-02-18
2017-02-25
이 두 번째 예에서는 예상했던 날짜를 얻습니다. DateTimeImmutable
대신을 사용하여 DateTime
우발적 인 상태 변형을 방지하고 잠재적 인 버그를 방지합니다.
Set the default time zone first and get the date then, the date will be in the time zone you specify :
<?php
date_default_timezone_set('America/New_York');
$date= date('m-d-Y') ;
?>
http://php.net/manual/en/function.date-default-timezone-set.php
If you have access to PHP 5.3, the intl extension is very nice for doing things like this.
Here's an example from the manual:
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/Los_Angeles',IntlDateFormatter::GREGORIAN );
$fmt->format(0); //0 for current time/date
In your case, you can do:
$fmt = new IntlDateFormatter( "en_US" ,IntlDateFormatter::FULL, IntlDateFormatter::FULL,
'America/New_York');
$fmt->format($datetime); //where $datetime may be a DateTime object, an integer representing a Unix timestamp value (seconds since epoch, UTC) or an array in the format output by localtime().
As you can set a Timezone such as America/New_York
, this is much better than using a GMT or UTC offset, as this takes into account the day light savings periods as well.
Finaly, as the intl extension uses ICU data, which contains a lot of very useful features when it comes to creating your own date/time formats.
I have created some simple function you can use to convert time to any timezone :
function convertTimeToLocal($datetime,$timezone='Europe/Dublin') {
$given = new DateTime($datetime, new DateTimeZone("UTC"));
$given->setTimezone(new DateTimeZone($timezone));
$output = $given->format("Y-m-d"); //can change as per your requirement
return $output;
}
<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>
참고URL : https://stackoverflow.com/questions/8006692/get-current-date-given-a-timezone-in-php
'programing' 카테고리의 다른 글
WinForms에서 도킹 순서를 제어하는 방법 (0) | 2020.11.06 |
---|---|
Eclipse에서 메서드를 빠르게 구현 / 재정의하는 방법은 무엇입니까? (0) | 2020.11.06 |
iOS 7에서 내비게이션 바의 높이는 얼마입니까? (0) | 2020.11.05 |
nullable 값이있는 구조체의 HashSet이 엄청나게 느린 이유는 무엇입니까? (0) | 2020.11.05 |
누군가 Shapeless 라이브러리가 무엇인지 설명해 줄 수 있습니까? (0) | 2020.11.05 |