在 PowerShell 中将秒转换为 hh:mm:ss,fff 格式 [英] Convert seconds to hh:mm:ss,fff format in PowerShell

查看:100
本文介绍了在 PowerShell 中将秒转换为 hh:mm:ss,fff 格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串,表示以秒和毫秒为单位的时间.我想将其转换为hh:mm:ss,fff"格式的字符串.

I have a string representing a time in seconds and milliseconds. I want to convert it to a string in the format "hh:mm:ss,fff".

我的解决方案仍然存在不足 10 小时显示为一位小数而不是两位小数的缺陷:

My solution still has the flaw that hours less than 10 are shown with one decimal instead of two:

PS> $secs = "7000.6789"
PS> $ts =  [timespan]::fromseconds($s)
PS> $res = "$($ts.hours):$($ts.minutes):$($ts.seconds),$($ts.milliseconds)"
PS> $res
PS> 1:56:40,679

实现这一目标的正确方法是什么?我确信 -f 和 datetime 有更优雅的方式.

What is the right way to achieve this? I'm sure there is a more elegant way with -f and datetime.

推荐答案

在 PowerShell 4.0 中

In PowerShell 4.0

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
("{0:hh\:mm\:ss\,fff}" -f $ts)

输出:01:56:40,679

在 PowerShell 2.0 中

In PowerShell 2.0

$s = "7000.6789"
$ts =  [timespan]::fromseconds($s)
"{0:hh:mm:ss,fff}" -f ([datetime]$ts.Ticks)

输出:01:56:40,679

然后回到另一条路...

And to go back the other way...

$text = "01:56:40,679"
$textReformat = $text -replace ",","."
$seconds = ([TimeSpan]::Parse($textReformat)).TotalSeconds
$seconds

输出:7000.679

这篇关于在 PowerShell 中将秒转换为 hh:mm:ss,fff 格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆