2017-01-24 4 views

答えて

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.

+0

@Rajesh:それは無視できるかもしれません:) –

+0

私は '.reduce'がうまくいけばいいと思っていましたが、' undefined'の値をスキップすることはわかりませんでした。 [JSFiddle](https://jsfiddle.net/RajeshDixit/db0xr7bd/1/)。 – Rajesh

+1

@Rajesh: 'reduce'で、次のようなことをしてください:https://jsfiddle.net/db0xr7bd/2/ –

1

私は将来的にこの形式で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 
関連する問題