将日期转换为正确的格式

时间:2019-08-22 17:19:40

标签: powershell

我的CSV文件的日期格式不正确19-08-22:01:00(yy-MM-dd:HH:mm)

当我在excel中打开它时,它没有以日期格式显示。因此,我想使用powershell转换此值。

我尝试使用以下命令对其进行更改。但是没用

$d = '19-08-22:01:00'
get-date $d

有人可以帮助我将日期转换为Excel可以识别为日期的正确格式。

2 个答案:

答案 0 :(得分:4)

我会使用DateTime.ParseExact()

$OldDate = '19-08-22:01:00'

# We need a provider so we pick the invariant one.
$Provider = [CultureInfo]::InvariantCulture

$OldDateFormat = 'yy-MM-dd:HH:mm'
# This format works well with Excel, assuming you use . and not , as a radix
$NewDateFormat = 'yyyy-MM-dd HH:mm:ss.fff'

$NewDate = [DateTime]::ParseExact($OldDate, $OldDateFormat, $Provider)
$NewDate.ToString($NewDateFormat)

答案 1 :(得分:0)

如果您唯一的目标是修复格式,则只需将第一个冒号替换为空格:

$d -replace '(?<=-\d{1,2}):', ' '