#1 PHP 时间处理

2011-05-02

date/time/strtotime

time()  # 获得当前时间戳
date(fmtStr, timestamp)

strtotime("+1 day")
strtotime("next Thursday")
strtotime("last Thursday")
# 字符串 => 时间戳
php -r 'var_dump(strtotime("today"));' # 零点
php -r 'var_dump(strtotime("2011"));'
php -r 'var_dump(strtotime("2011-12"));'
php -r 'var_dump(strtotime("2011-12-13"));'
php -r 'var_dump(strtotime("2011-12-13 06:00:00"));'

# 时间戳 => 字符串
php -r 'var_dump(date("Y-m-d H:i:s", 0));'

DateTime

  • DateTimeInterface
  • DateTime
  • DateTimeImmutable
  • DateTimeZone
  • DateInterval
  • DatePeriod 实现 Traversable 接口
// DateTimeInterface::ATOM = "Y-m-d\TH:i:sP";
// DateTimeInterface::COOKIE = "l, d-M-Y H:i:s T";
// DateTimeInterface::ISO8601 = "Y-m-d\TH:i:sO";
// DateTimeInterface::RFC822 = "D, d M y H:i:s O";
// DateTimeInterface::RFC850 = "l, d-M-y H:i:s T";
// DateTimeInterface::RFC1036 = "D, d M y H:i:s O";
// DateTimeInterface::RFC1123 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC7231 = "D, d M Y H:i:s \G\M\T";
// DateTimeInterface::RFC2822 = "D, d M Y H:i:s O";
// DateTimeInterface::RFC3339 = "Y-m-d\TH:i:sP";
// DateTimeInterface::RFC3339_EXTENDED = "Y-m-d\TH:i:s.vP";
// DateTimeInterface::RSS = "D, d M Y H:i:s O";
// DateTimeInterface::W3C = "Y-m-d\TH:i:sP";

$dateTime = new DateTime();

foreach ([
    'ATOM',
    'COOKIE',
    'ISO8601',
    'RFC822',
    'RFC850',
    'RFC1036',
    'RFC1123',
    'RFC2822',
    'RFC3339',
    'RFC3339_EXTENDED',
    'RSS',
    'W3C',
] as $format) {
    eval("print 'DateTimeInterface::$format\t'.\$dateTime->format(DateTimeInterface::$format).\"\n\";");
}
  • public static createFromFormat(string $format, string $datetime, ?DateTimeZone $timezone = null): DateTime|false

  • public format(string $format): string

  • public modify(string $modifier): DateTime|false

  • public add(DateInterval $interval): DateTime
  • public sub(DateInterval $interval): DateTime

  • public diff(DateTimeInterface $targetObject, bool $absolute = false): DateInterval

  • public getOffset(): int

  • public getTimestamp(): int
  • public setTimestamp(int $timestamp): DateTime
  • public getTimezone(): DateTimeZone|false
  • public setTimezone(DateTimeZone $timezone): DateTime
  • public setDate(int $year, int $month, int $day): DateTime
  • public setISODate(int $year, int $week, int $dayOfWeek = 1): DateTime
  • public setTime(int $hour, int $minute, int $second = 0, int $microsecond = 0): DateTime
$d = new DateTime('2011-01-01T15:03:01.012345Z');
echo $d->format('Y-m-d\TH:i:s.u'); // 2011-01-01T15:03:01.012345

$d->modify('+1 month');
$d->add(new DateInterval("P1M"));

$publishDate = DateTime::createFromFormat('m/d/Y', '1/10/2014');
echo $publishDate->getTimestamp();