在MariaDB中是否相当于sprintf('%+ 03d:00',$ my_number)?

问题描述 投票:1回答:2

我的目标是在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 timezone mariadb
2个回答
1
投票

你可以用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


0
投票
SELECT  dt + INTERVAL timezone HOUR;

timezone小时添加到DATETIME dt。我假设timezone是有符号整数。

© www.soinside.com 2019 - 2024. All rights reserved.