获取当前日期,给定 PHP 中的时区?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8006692/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 03:45:58  来源:igfitidea点击:

Get current date, given a timezone in PHP?

phpdatetimezone

提问by einstein

I want to get todays date given a time zone in Paul Eggert format(America/New_York) in PHP?

我想America/New_York在 PHP 中以 Paul Eggert 格式()给定时区的情况下获取今天的日期?

回答by Andy Fleming

The other answers set the timezone for all dates in your system. This doesn't always work well if you want to support multiple timezones for your users.

其他答案为系统中的所有日期设置时区。如果您想为用户支持多个时区,这并不总是有效。

Here's the short version:

这是简短的版本:

<?php
$date = new DateTime("now", new DateTimeZone('America/New_York') );
echo $date->format('Y-m-d H:i:s');

Works in PHP >= 5.2.0

适用于 PHP >= 5.2.0

List of supported timezones: php.net/manual/en/timezones.php

支持的时区列表:php.net/manual/en/timezones.php



Here's a version with an existing time and setting timezone by a user setting

这是一个具有现有时间并由用户设置设置时区的版本

<?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');


Here is a more verbose version to show the process a little more clearly

这是一个更详细的版本,以更清楚地显示该过程

<?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');


Libraries

图书馆

  • Carbon— A very popular date library.
  • Chronos— A drop-in replacement for Carbon focused on immutability. See below on why that's important.
  • jenssegers/date— An extension of Carbon that adds multi-language support.
  • Carbon— 一个非常流行的日期库。
  • Chronos— 专注于不变性的 Carbon 替代品。请参阅下文,了解为什么这很重要。
  • jenssegers/date— Carbon 的扩展,增加了多语言支持。

I'm sure there are a number of other libraries available, but these are a few I'm familiar with.

我确信还有许多其他库可用,但这些是我熟悉的一些。



Bonus Lesson: Immutable Date Objects

额外课程:不可变日期对象

While you're here, let me save you some future headache. Let's say you want to calculate 1 week from today and 2 weeks from today. You might write some code like:

当你在这里时,让我为你省去一些未来的麻烦。假设您要计算距今天 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>";

The output:

输出:

2017-02-11 
--- 
2017-03-04 
2017-03-04 
2017-03-04

Hmmmm... That's not quite what we wanted. Modifying a traditional DateTimeobject in PHP not only returns the updated date but modifies the original object as well.

嗯……那不是我们想要的。DateTime在 PHP 中修改传统对象不仅会返回更新日期,还会修改原始对象。

This is where DateTimeImmutablecomes in.

这是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>";

The output:

输出:

2017-02-11 
--- 
2017-02-11 
2017-02-18 
2017-02-25 

In this second example, we get the dates we expected back. By using DateTimeImmutableinstead of DateTime, we prevent accidental state mutations and prevent potential bugs.

在第二个示例中,我们得到了预期的日期。通过使用DateTimeImmutable代替DateTime,我们可以防止意外的状态突变并防止潜在的错误。

回答by Ghost-Man

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

http://php.net/manual/en/function.date-default-timezone-set.php

回答by F21

If you have access to PHP 5.3, the intl extensionis very nice for doing things like this.

如果您可以访问 PHP 5.3,intl 扩展非常适合做这样的事情。

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.

由于您可以设置时区,例如America/New_York,这比使用 GMT 或 UTC 偏移要好得多,因为这也考虑了夏令时。

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.

最后,由于 intl 扩展使用 ICU 数据,其中包含许多在创建您自己的日期/时间格式时非常有用的功能。

回答by Vipul Lakhtariya

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;
}

回答by Kyle

<?php
date_default_timezone_set('GMT-5');//Set New York timezone
$today = date("F j, Y")
?>