【发布时间】:2015-10-16 13:53:27
【问题描述】:
我有一个带有类似值的 sql 列
PT2M52.37S
PT21.79S
PT53M29.68S
P
PT9S
是否有可能用一些MySQL 函数将上述格式转换为秒?
我已经搜索了所有内容,但没有找到与上述格式完全相同的内容。 我试过的任何日期 mysql 函数都不起作用。
有关此格式的更多信息:http://www.ostyn.com/standards/scorm/samples/ISOTimeForSCORM.htm
PHP 函数(它总是 P,第一个字符)
function scorm_format_duration($duration) {
// Fetch date/time strings.
$stryears = get_string('years');
$strmonths = get_string('nummonths');
$strdays = get_string('days');
$strhours = get_string('hours');
$strminutes = get_string('minutes');
$strseconds = get_string('seconds');
if ($duration[0] == 'P') {
// If timestamp starts with 'P' - it's a SCORM 2004 format
// this regexp discards empty sections, takes Month/Minute ambiguity into consideration,
// and outputs filled sections, discarding leading zeroes and any format literals
// also saves the only zero before seconds decimals (if there are any) and discards decimals if they are zero.
$pattern = array( '#([A-Z])0+Y#', '#([A-Z])0+M#', '#([A-Z])0+D#', '#P(|\d+Y)0*(\d+)M#',
'#0*(\d+)Y#', '#0*(\d+)D#', '#P#', '#([A-Z])0+H#', '#([A-Z])[0.]+S#',
'#\.0+S#', '#T(|\d+H)0*(\d+)M#', '#0*(\d+)H#', '#0+\.(\d+)S#',
'#0*([\d.]+)S#', '#T#' );
$replace = array( '$1', '$1', '$1', '$1$2 '.$strmonths.' ', '$1 '.$stryears.' ', '$1 '.$strdays.' ',
'', '$1', '$1', 'S', '$1$2 '.$strminutes.' ', '$1 '.$strhours.' ',
'0.$1 '.$strseconds, '$1 '.$strseconds, '');
} else {
// Else we have SCORM 1.2 format there
// first convert the timestamp to some SCORM 2004-like format for conveniency.
$duration = preg_replace('#^(\d+):(\d+):([\d.]+)$#', 'T$1H$2M$3S', $duration);
// Then convert in the same way as SCORM 2004.
$pattern = array( '#T0+H#', '#([A-Z])0+M#', '#([A-Z])[0.]+S#', '#\.0+S#', '#0*(\d+)H#',
'#0*(\d+)M#', '#0+\.(\d+)S#', '#0*([\d.]+)S#', '#T#' );
$replace = array( 'T', '$1', '$1', 'S', '$1 '.$strhours.' ', '$1 '.$strminutes.' ',
'0.$1 '.$strseconds, '$1 '.$strseconds, '' );
}
$result = preg_replace($pattern, $replace, $duration);
return $result;
}
【问题讨论】:
-
上述格式是 ISO 格式。我在问是否有任何准备使用的功能。如果是手动的,我什至不知道我们有什么样的不同可能性。在第一个示例中,虽然是 2 分 52 秒和 37 毫秒。
-
@GordonLinoff 是的,就是这样。
-
ISO-8601 涉及多种格式。这些看起来像durations。 IMX,大多数时候人们谈论 ISO-8601 和数据库,他们在谈论 ISO 日期或日期时间。您也许可以使用
STR_TO_DATE(),但使用这种不同的格式可能不会很漂亮.. -
似乎有人让它与
STR_TO_DATE()here一起工作,他们的完整命令是SELECT STR_TO_DATE('PT13M22S', 'PT%iM%sS');,但遗憾的是它对我不起作用,不知道为什么。
标签: mysql sql datetime iso8601