从4位军事时间转换为标准时间

时间:2015-11-19 20:12:55

标签: sql-server tsql

我正在使用SQL Server 2016,我正在尝试将军事时间转换为标准时间。军事时间是一个4位整数,我正在尝试获得标准时间格式(00:00 am / pm)。

我运行了一个简单的CASE语句,使其成为标准但没有':'和'am / pm'。

CASE
  WHEN  SA_BEGTIME between 0 and 1259 then SA_BEGTIME  
  WHEN SA_BEGTIME between 1300 and 2400 then  SA_BEGTIME - 1200

  ELSE ''

END as Time

Results

如何将其转换为格式正确:'00:00 am / pm'

谢谢!

5 个答案:

答案 0 :(得分:3)

您可以将其拆分为具有整数除法和模数的部分,将其转换为VARCHAR,然后将其转换为TIME:

<?php 
  $to = 'mail@example.com';
  $name = $_POST['email'];
  and so on ..
  ..
  ..
  mail(mail@example.com, name, (here goes email, name, subject, textarea, tel) as message in new lines);
    and somewhere i have to write from what emial im sending to example@gmail.com and what is it's password i guess
?>

或者您可以使用新的TIMEFROMPARTS()函数(SQL Server 2012 +):

declare @x int = 109

select cast(cast(@x / 100 as varchar(2)) + ':' + cast(@x % 100 as varchar(2)) as time)

然后您可以根据需要对其进行格式化。

答案 1 :(得分:1)

假设您的数据存储为整数,并且假设没有存储无效时间(即2400以上或以下的值),您可以使用以下内容:

declare @TheTime int = 900
select right(convert(varchar(20),
         cast(stuff(right('0000' + convert(varchar(4),@TheTime),4),3,0,':')
        as datetime),100),7)
-------
 9:00AM

对不起解决方案的密度。这就是我所做的:

  1. 将@TheTime转换为varchar(4)
  2. 在前面添加一串零
  3. 从这个新字符串中取出最右边的4个字符
  4. 在此新字符串
  5. 的中间填充冒号
  6. 将字符串转换为日期时间
  7. 使用100作为样式指示器转换回字符串以获取AM / PM
  8. 获取字符串中最右边的7个字符。
  9. 我确信有更优雅的方式,但这个方法对我很有用。

答案 2 :(得分:1)

我正在使用@BaconBits提供的解决方案,但我不得不进行调整,因为2400是一个有效的表示,但它失败了。这是经过调整的解决方案:

declare @x int = 2400
select TIMEFROMPARTS((@x / 100) % 24,@x % 100, 0, 0, 0)

答案 3 :(得分:0)

我需要将一个军事时间的datetime字段转换为AM / PM格式的时间。效果很好。

Left(convert(varchar(20), cast(MyDateField as time),100),7)

答案 4 :(得分:-1)

您可以使用转换来获得适当的时间表示。

declare @mt varchar(4) = '1500'

select convert(varchar, cast(left(@mt, 2) + ':' + right(@mt, 2) as time), 0)
相关问题