当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] PowerShell - 将日期时间转换为字符串

作者:精品下载站 日期:2024-12-14 17:01:52 浏览:16 分类:玩电脑

PowerShell - 将日期时间转换为字符串


PowerShell DateTime 对象具有将日期时间转换为字符串的内置方法。 DateTime 对象的 ToString() 方法将 DateTime 转换为字符串表示形式。此方法接受参数,您可以在其中指定字符串的格式。

ToString() 方法允许您指定 DateTime 对象的字符串表示形式。您可以指定日期时间格式,例如 "ddMMyyyy"、"dd-MM- yyyy hh:mm:ss ”等等…

在本文中,我们将讨论如何在 PowerShell 中将日期转换为字符串,并使用 ToString 方法以默认格式和自定义格式格式化日期对象。

PowerShell 将日期转换为字符串

在 PowerShell 中要将日期转换为字符串,请使用以下脚本,该脚本使用 DateTime 对象的 ToString() 方法。

# Get the date
$date = Get-Date 

# Convert the datetime to string
$str = $date.ToString()                                                                    

# Print the string represention for the datetime object
$str                                                                                       

# Use the custom format to specify the datetime format

$str = $date.ToString("ddMMyyyy") 

# Use the custom format to specify datetime format
$str = $date.ToString("dd-MM-yyyy hh:mm:ss")

在上面的 PowerShell 脚本中,PowerShell 中的 Get-Date cmdlet 获取当前日期并将其存储在 $date 变量中。使用 DateTime 对象的 ToString() 方法,它将 DateTime 转换为 PowerShell 中的字符串。

ToString() 方法中指定的自定义格式,如 "ddMMyyyy""dd-MM-yyyy hh:mm:ss" 将日期转换为PowerShell 中的字符串。

上述将日期转换为字符串的 PowerShell 脚本的输出为:

[玩转系统] PowerShell - 将日期时间转换为字符串

将日期时间对象转换为字符串的另一种方法是使用 -f 运算符。 -f 运算符执行 {0:dd-MM-yyyy} 中指定的字符串格式设置。

$str = '{0:dd-MM-yyyy}' -f (Get-Date '19-01-2023') 

在上面的 PowerShell 脚本中,Get-Date cmdlet 获取指定日期的日期时间对象,并将该日期时间对象传递给 -f 运算符,后者使用字符串格式来在 PowerShell 中将日期转换为字符串。

上述 PowerShell 脚本的输出是:

C:$str = '{0:dd-MM-yyyy}' -f (Get-Date '19-01-2023') 

PS C:\> $str
19-01-2023

在 PowerShell 中使用 ToShortDateString() 将日期转换为字符串

DateTime 对象具有 ToShortDateString() 方法,可将日期时间对象转换为 PowerShell 中的字符串。

# Get the date
$date = Get-Date 

# Use ToShortDateString() to convert datetime to string
$str = $date.ToShortDateString() 

# Print the string
$str

在上面的 PowerShell 脚本中,PowerShell 中的 Get-Date cmdlet 获取当前日期并将其存储在 $date 变量中。使用 DateTime 对象的 ToShortDateString() 方法将日期转换为字符串格式。

上述 PowerShell 脚本的输出是:

PS C:\> $str = $date.ToShortDateString()                                                           
PS C:\> $str                                                                                       
03-02-2023

酷提示:如何在 PowerShell 中将字符串转换为日期!

结论

我希望上面关于如何使用 ToString()、ToShortDateString() 和 -f 运算符等 DateTime 方法将日期时间转换为字符串的文章对您有所帮助。

PowerShell 中的 ToString() 方法以默认和自定义日期格式格式化日期对象。

您可以在 ShellGeek 主页上找到有关 PowerShell Active Directory 命令和 PowerShell 基础知识的更多主题。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯