函数文档

parse_w3cdtf()

💡 云策文档标注

概述

parse_w3cdtf() 是一个用于解析 W3C 日期时间格式字符串的 PHP 函数,将其转换为 Unix 时间戳。函数通过正则表达式匹配日期时间格式,并处理时区偏移以返回 GMT 时间戳。

关键要点

  • 函数使用正则表达式匹配 W3C 日期时间格式,如 "2023-12-31T23:59:59+08:00" 或 "2023-12-31T23:59:59Z"
  • 解析成功后,使用 gmmktime() 计算 GMT 时间戳,并根据时区偏移进行调整
  • 如果匹配失败,函数返回 -1 表示错误

代码示例

Source function parse_w3cdtf ( $date_str ) {

	# regex to match W3C date/time formats
	$pat = "/(d{4})-(d{2})-(d{2})T(d{2}):(d{2})(:(d{2}))?(?:([-+])(d{2}):?(d{2})|(Z))?/";

	if ( preg_match( $pat, $date_str, $match ) ) {
		list( $year, $month, $day, $hours, $minutes, $seconds) =
			array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);

		# calc epoch for current date assuming GMT
		$epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);

		$offset = 0;
		if ( $match[11] == 'Z' ) {
			# zulu time, aka GMT
		}
		else {
			list( $tz_mod, $tz_hour, $tz_min ) =
				array( $match[8], $match[9], $match[10]);

			# zero out the variables
			if ( ! $tz_hour ) { $tz_hour = 0; }
			if ( ! $tz_min ) { $tz_min = 0; }

			$offset_secs = (($tz_hour*60)+$tz_min)*60;

			# is timezone ahead of GMT?  then subtract offset
			#
			if ( $tz_mod == '+' ) {
				$offset_secs = $offset_secs * -1;
			}

			$offset = $offset_secs;
		}
		$epoch = $epoch + $offset;
		return $epoch;
	}
	else {
		return -1;
	}
}

📄 原文内容

Source

function parse_w3cdtf ( $date_str ) {

	# regex to match W3C date/time formats
	$pat = "/(d{4})-(d{2})-(d{2})T(d{2}):(d{2})(:(d{2}))?(?:([-+])(d{2}):?(d{2})|(Z))?/";

	if ( preg_match( $pat, $date_str, $match ) ) {
		list( $year, $month, $day, $hours, $minutes, $seconds) =
			array( $match[1], $match[2], $match[3], $match[4], $match[5], $match[7]);

		# calc epoch for current date assuming GMT
		$epoch = gmmktime( $hours, $minutes, $seconds, $month, $day, $year);

		$offset = 0;
		if ( $match[11] == 'Z' ) {
			# zulu time, aka GMT
		}
		else {
			list( $tz_mod, $tz_hour, $tz_min ) =
				array( $match[8], $match[9], $match[10]);

			# zero out the variables
			if ( ! $tz_hour ) { $tz_hour = 0; }
			if ( ! $tz_min ) { $tz_min = 0; }

			$offset_secs = (($tz_hour*60)+$tz_min)*60;

			# is timezone ahead of GMT?  then subtract offset
			#
			if ( $tz_mod == '+' ) {
				$offset_secs = $offset_secs * -1;
			}

			$offset = $offset_secs;
		}
		$epoch = $epoch + $offset;
		return $epoch;
	}
	else {
		return -1;
	}
}