我的目标是在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" |
谢谢。
答案 0 :(得分:1)
您可以使用
进行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
答案 1 :(得分:0)
SELECT dt + INTERVAL timezone HOUR;
将timezone
小时增加DATETIME dt
。我假设timezone
是一个有符号整数。