首页 > 解决方案 > 将日期转换为正确的格式

问题描述

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

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

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

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

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

标签: powershell

解决方案


我会使用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)

推荐阅读