【问题标题】:Convert human readable duration to Time Format SQL SERVER 2014将人类可读的持续时间转换为时间格式 SQL SERVER 2014
【发布时间】:2017-01-24 22:23:44
【问题描述】:

我有这个数据。

"2mn 56s", "30s 83ms", "2h 10mn"

如何将这些转换为时间格式:

hh:mn:ss - "00:02:56", "00:00:30", "02:10:00"

【问题讨论】:

  • 你能分享一下你的努力吗?

标签: javascript tsql sql-server-2012


【解决方案1】:

在 JavaScript 中,你可以使用String#replace 方法。

var str = '"2mn 56s", "30s 83ms", "2h 10mn"';

console.log(
  str.replace(/"(?:(\d)+h\s*)?(?:(\d+)mn\s*)?(?:(\d+)s\s*)?[^"]*"?/g, function(_, m1, m2, m3) {
    return [m1, m2, m3].map(v => ('00' +( v || '')).slice(-2)).join(':')
  })
)

Regex explanation here.

【讨论】:

  • @Rajesh : 可以忽略不计 :)
  • 我想知道.reduce 会更适合,但我不知道它会跳过undefined 值。 JSFiddle.
  • @Rajesh:与reduce,做这样的事情:jsfiddle.net/db0xr7bd/2
【解决方案2】:

我以后不会以这种格式存储TIME。话虽如此,根据您的示例数据,这里是一个 SQL Server 解决方案。取消注释 @t1 变量以查看不同的测试用例。

declare @t1 varchar(16)

--set @t1 = '2h 10mn'
set @t1 = '2mn 56s'
--set @t1 = '30s 83ms'

--this places your data in a time format. This is ideal in most cases so you can actually use datetime functions on the data
select
    case 
        when left(@t1, charindex(' ',@t1)) like '%h' 
        then convert(time,convert(varchar,left(@t1,charindex('h',@t1) - 1)) + ':' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 2) + ':00')   
    end,
    case 
        when left(@t1, charindex(' ',@t1)) like '%mn' 
        then convert(time,'00:' + convert(varchar,left(@t1,charindex('mn',@t1) - 1)) + ':' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 1))
    end,
    case 
        when left(@t1, charindex(' ',@t1)) like '%s'
        then convert(time,'00:00:' + convert(varchar,left(@t1,charindex('s',@t1) - 1)) + '.' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 2))
    end


--if you only want it in the hh:mm:ss then you can use the below. This rounds your milliseconds properly

select
    case 
        when left(@t1, charindex(' ',@t1)) like '%h' 
        then convert(time(0),convert(varchar,left(@t1,charindex('h',@t1) - 1)) + ':' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 2) + ':00')    
    end,
    case 
        when left(@t1, charindex(' ',@t1)) like '%mn' 
        then convert(time(0),'00:' + convert(varchar,left(@t1,charindex('mn',@t1) - 1)) + ':' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 1))
    end,
    case 
        when left(@t1, charindex(' ',@t1)) like '%s'
        then convert(time(0),'00:00:' + convert(varchar,left(@t1,charindex('s',@t1) - 1)) + '.' + substring(@t1,charindex(' ', @t1) + 1,len(@t1) - charindex(' ', @t1) - 2))
    end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-01
    • 2010-12-11
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    相关资源
    最近更新 更多