2017-05-05 12:03:02 -0400 (Fri, 05 May 2017)
what time format is the above in powershell?? i need the same format to compare with today time in powershell.
Get-Date -format
2017-05-05 12:03:02 -0400 (Fri, 05 May 2017)
what time format is the above in powershell?? i need the same format to compare with today time in powershell.
Get-Date -format
Since this is a follow-up question, you should mention this.
To convert a string containing a datetime based on UTC with a timezone offset,
use [datetime]::ParseExact()
. You should change the RegEx from previous Q&A to only contain the datetime without the redundant information in parentheses.
[datetime]::ParseExact("2017-05-05 12:03:02 -0400","yyyy-MM-dd HH:mm:ss zzzzz",$Null)
This will convert to local time (and correctly include the DST aka daylight saving time at that date)
Sample output here with timezone +1 and DST active to:
2017-05-05 18:03:02 +02:00
Or more universal with .ToString('U')
and my German locale settings to:
Freitag, 5. Mai 2017 16:03:02
To get the difference to [datetime]::Now
simply subtract and choose a property from
> [datetime]::Now - [datetime]::ParseExact("2017-05-05 12:03:02 -0400","yyyy-MM-dd HHH:mm:ss zzzzz",$Null)
Days : 593
Hours : 20
Minutes : 15
Seconds : 35
Milliseconds : 615
Ticks : 513081356156056
TotalDays : 593,844162217657
TotalHours : 14252,2598932238
TotalMinutes : 855135,593593427
TotalSeconds : 51308135,6156056
TotalMilliseconds : 51308135615,6056
You can build more or less any format you like using the DateTime Format Strings and either the format operator (-f
) or the ToString()
method. For example:
(Get-Date).ToString("yyyy-MM-dd hh:mm:ss")
Which gives something like this:
2018-12-20 12:50:53
If you want to go the other way, you can do it like this:
Get-Date "2017-05-05 12:03:02 -0400"
This converts your string to an actual DateTime object, which can be directly compared to any other DateTime. So, to check if your target date is before now, for example, do something like this:
(Get-Date "2017-05-05 12:03:02 -0400") -lt (Get-Date)