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

前端 未结 7 1803
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 19:18

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)
相关标签:
7条回答
  • 2020-12-30 20:20

    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!

    0 讨论(0)
提交回复
热议问题