开发者

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

开发者 https://www.devze.com 2022-12-22 14:52 出处:网络
For a check i need yesterday\'s date at 10:00pm in a variable. I get yesterdays Date and current Time with

For a check i need yesterday's date at 10:00pm in a variable.

I get yesterdays Date and current Time with

$a = (get-date).AddDays(-1)

But how do i manipulate the time to 22.00 and leave the variable still as Date-Object?开发者_JAVA技巧


Use DateTime.Today as opposed to DateTime.Now (which is what Get-Date returns) because Today is just the date with 00:00 as the time, and now is the moment in time down to the millisecond. (from masenkablast)

> [DateTime]::Today.AddDays(-1).AddHours(22)
Thursday, March 11, 2010 10:00:00 PM


I see this topic, but in my case I was looking for a way to improve the format. Using UFormat and adding -1 day

(get-date (get-date).addDays(-1) -UFormat "%Y%m%d-%H%M")


(Get-Date (Get-Date -Format d)).AddHours(-2)


I saw in at least one other place that people don't realize Date-Time takes in times as well, so I figured I'd share it here since it's really short to do so:

Get-Date # Following the OP's example, let's say it's Friday, March 12, 2010 9:00:00 AM
(Get-Date '22:00').AddDays(-1) # Thursday, March 11, 2010 10:00:00 PM

It's also the shortest way to strip time information and still use other parameters of Get-Date. For instance you can get seconds since 1970 this way (Unix timestamp):

Get-Date '0:00' -u '%s' # 1268352000

Or you can get an ISO 8601 timestamp:

Get-Date '0:00' -f 's' # 2010-03-12T00:00:00

Then again if you reverse the operands, it gives you a little more freedom with formatting with any date object:

'The sortable timestamp: {0:s}Z{1}Vs measly human format: {0:D}' -f (Get-Date '0:00'), "`r`n"
# The sortable timestamp: 2010-03-12T00:00:00Z
# Vs measly human format: Friday, March 12, 2010

However if you wanted to both format a Unix timestamp (via -u aka -UFormat), you'll need to do it separately. Here's an example of that:

'ISO 8601: {0:s}Z{1}Unix: {2}' -f (Get-Date '0:00'), "`r`n", (Get-Date '0:00' -u '%s')
# ISO 8601: 2010-03-12T00:00:00Z
# Unix: 1268352000

Hope this helps!


Format in other syntax is possible in this way

[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")


When I was to get yesterday with just the date in the format Year/Month/Day I use:

$Variable = Get-Date((get-date ).AddDays(-1))  -Format "yyyy-MM-dd"


Yet another way to do this:

(Get-Date).AddDays(-1).Date.AddHours(22)


Another possible method but Unix timestamp

 ([int64](Get-Date -UFormat %s) - [int64](New-TimeSpan -Hours 1).TotalSeconds)
0

精彩评论

暂无评论...
验证码 换一张
取 消