我的目标是在SQL(MySQL或MariaDB)中将TimeZone从数字格式转换为字符串(如-10到“-10:00”)。
实际上我想要(在PHP中):
echo sprintf('%+03d:00', $timezone);
| In | Out |
|-----|----------|
| -10 | "-10:00" |
| -2 | "-02:00" |
| 2 | "+02:00" |
| 10 | "+10:00" |
有一种方法可以在SQL语法中使用它吗?
我开始写:
SELECT CONCAT(CONVERT(timezone), CHAR), ":00");
但输出并不像预期的那样:
| In | Out |
|-----|----------|
| -10 | "-10:00" |
| -2 | "-2:00" |
| 2 | "2:00" |
| 10 | "10:00" |
提前致谢。
你可以用MySQL进行MySQL / MariaDB转换
(
CONCAT(
CASE
# sign condition check
WHEN (ABS(timezone) = timezone) = 0
THEN "-"
ELSE "+"
END
, LPAD(ABS(timezone), 2, '0')
, ":00"
)
) AS alias
查询测试数据
SELECT
timezone AS 'In'
, (
CONCAT(
CASE
# sign condition check
WHEN (ABS(timezone) = timezone) = 0
THEN "-"
ELSE "+"
END
, LPAD(ABS(timezone), 2, '0')
, ":00"
)
) AS 'Out'
FROM (
SELECT -10 as timezone
UNION ALL
SELECT -2 AS timezone
UNION ALL
SELECT 2 AS timezone
UNION ALL
SELECT 10 AS timezone
) AS test_data;
结果
| In | Out |
| --- | ------ |
| -10 | -10:00 |
| -2 | -02:00 |
| 2 | +02:00 |
| 10 | +10:00 |
见demo
SELECT dt + INTERVAL timezone HOUR;
将timezone
小时添加到DATETIME dt
。我假设timezone
是有符号整数。