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

[玩转系统] PowerShell 新纪元时间和日期时间转换

作者:精品下载站 日期:2024-12-14 16:57:07 浏览:11 分类:玩电脑

PowerShell 新纪元时间和日期时间转换


Unix 纪元时间是自 1970 年 1 月 1 日以来经过的秒数。在 PowerShell 中使用 Get-Date cmdlet 和 -UFormat %s 可以将日期时间转换为纪元时间。

要将纪元时间转换为日期时间,请使用 Microsoft .Net 类库 System.TimeSpan 将秒数添加到 1970 年 1 月 1 日的纪元时间日期中。

在本文中,我们将讨论如何在 PowerShell 中将纪元时间转换为日期时间以及将日期时间转换为 Unix 纪元时间。

PowerShell 将日期时间转换为纪元时间(Unix 时间)

使用 PowerShell 中的 Get-Date cmdlet 指定日期并将其转换为纪元时间。

# Convert the date time to Unix Epoch Time
Get-Date -Date "20-08-2020" -UFormat %s  

# Convert the current datetime to Unix Timestamp
Get-Date -UFormat %s 

在上面的 PowerShell 脚本中,Get-Date 命令使用 Date 参数指定自定义日期,并使用 UFormat %s 参数将指定日期到纪元时间。

在下一个示例中,Get-Date cmdlet 使用 UFormat %s 将当前 DateTime 转换为 Unix 纪元时间,并返回自 1970 年 1 月 1 日以来经过的总秒数。

上述获取纪元时间的 PowerShell 脚本的输出是:

[玩转系统] PowerShell 新纪元时间和日期时间转换

酷提示:如何在 PowerShell 中获取减去 1 天的日期!

PowerShell 将纪元时间转换为日期时间

在 PowerShell 中使用 Microsoft .Net 类库 System.TimeSpan 将 Unix 时间戳转换为 DateTime。

# Convert Unix Epoch time to DateTime. Add number of seconds to 01-01-1970
$cusDate = (Get-Date -Date "01-01-1970") + ([System.TimeSpan]::FromSeconds((1597881600)))

# Print the datetime
$cusDate

在上面的 PowerShell 脚本中,要将纪元时间转换为 DateTime,请将秒数添加到纪元时间日期 1970 年 1 月 1 日。

Get-Date 命令使用 Date 参数指定纪元时间日期,并使用串联添加秒数来获取日期。

上述 PowerShell 脚本的输出将 UNIX 纪元时间转换为日期时间并返回 DateTime。

PS C:\> $cusDate = (Get-Date -Date "01-01-1970") + ([System.TimeSpan]::FromSeconds((1597881600)))

PS C:\> $cusDate              
                                                                                          
20 August 2020 00:00:00

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

结论

我希望上面的文章可以帮助您了解如何在 PowerShell 中将 DateTime 转换为纪元时间以及如何将 Unix 时间戳转换为日期时间。

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

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

取消回复欢迎 发表评论:

关灯