How to convert powershell UTC datetime object to EST - powershell

I have date time strings coming in, formatted like the following:
2017-08-03T12:30:00.000Z
I need to be able to convert these to EST. Every function I have tried throws one error or another, typically being:
"String was not recognized as a valid DateTime."
I have tried variations of the below:
$time = '2017-08-03T12:30:00.000Z'
[datetime]$datetime = $time
$culture = [Globalization.CultureInfo]::InvariantCulture
[DateTime]::ParseExact($datetime, 'MM-dd-yyyy HH:mm:ss', $culture)
I think it has something to do with how the Date Time string I am referencing has the **T** and then the UTC time, but can't figure out what to do about it. Maybe I should parse out the time, convert it and then reattach to the first part of the string, the date, and combine them together for the final output? Seems like way too much work and a solution which would cause potential errors in the future.

You should be able to convert a Zulu time string to a DateTime value simply by casting it. However, the resulting value will be in local time, so you should convert it back to UTC for further calculations:
$timestamp = '2017-08-03T12:30:00.000Z'
$datetime = ([DateTime]$timestamp).ToUniversalTime()
Then you can use the TimeZoneInfo class to convert the UTC timestamp to the desired timezone:
[TimeZoneInfo]::ConvertTimeBySystemTimeZoneId($datetime, 'Eastern Standard Time')
Use [TimeZoneInfo]::GetSystemTimeZones() | Select-Object Id, DisplayName to get a list of the recognized timezones.

Try using the static ConvertTimeBySystemTimeZoneId() method of the [System.TimeZoneInfo] class:
$time = '2017-08-03T12:30:00.000Z'
$result = [System.TimeZoneInfo]::ConvertTimeBySystemTimeZoneId((Get-Date -Date $time), 'Eastern Standard Time')
The returned $result is a [DateTime].
BTW, if you ever need to convert it back, here's how:
Get-Date -Date $result -Format FileDateTimeUniversal
Hope this helps.

Related

Powershell string to unix time with correct timezone

I'm collecting a timestamp value and trying to transform it to a Unix format.
To do that, I'm using ParseExact method, like so:
$FILETIME = "20220709101112"
$EPOCHTIME = [datetime]::ParseExact($FILETIME,"yyyyMMddHHmmss",$null) | Get-Date -UFormat "%s"
echo $EPOCHTIME
1657361472
Get-Date transforms the timestamp to Unix format correctly, but there's an issue.
The returned value uses the local timezone (UTC-3), not UTC-0.
Therefore, in another system that value might be displayed with the wrong timezone.
I've tried to add 3 hours, but it appended the number instead.
$EPOCHTIME = $EPOCHTIME + 10800
echo $EPOCHTIME
165736147210800
How can I convert that timestamp correctly?
Ok, so here's one way to do it (borrowing from https://stackoverflow.com/a/246529/3156906).
The key is to find the TimeZoneInfo for the timezone the $FILETIME string is local to, and use that to convert the local time to UTC before converting to a Unix epoch timestamp.
# datetime string that is local to UTC-3,
# (equivalent to "2022-07-09 13:11:12 UTC")
$FILETIME = "20220709101112";
# because there's no timezone component in the custom
# format string (e.g. "z" or "zz") this gets converted
# to a datetime with "Kind = DateTimeKind.Unspecified"
# (see https://learn.microsoft.com/en-us/dotnet/api/system.datetime.parseexact?view=net-6.0#system-datetime-parseexact(system-string-system-string-system-iformatprovider))
$TIMESTAMP = [datetime]::ParseExact($FILETIME, "yyyyMMddHHmmss", $null);
# DateTime : 09 July 2022 10:11:12
# Kind : Unspecified
# get a reference to the timezone the original date
# string is stored local to. I guessed this by looking
# at the results of "[TimeZoneInfo]::GetSystemTimeZones()"
# and taking a timezone with -3:00 from UTC and no daylight savings
# but maybe there's a better match for your source data
$tz = [TimeZoneInfo]::FindSystemTimeZoneById("SA Eastern Standard Time");
# Id : SA Eastern Standard Time
# DisplayName : (UTC-03:00) Cayenne, Fortaleza
# StandardName : SA Eastern Standard Time
# DaylightName : SA Eastern Summer Time
# BaseUtcOffset : -03:00:00
# SupportsDaylightSavingTime : False
# this is the magic bit - treat $TIMESTAMP as a local time in
# timezone $tz, and convert it to UTC using the BaseUtcOffset
# and daylight saving rules for $tz
$UTCTIME = [TimeZoneInfo]::ConvertTimeToUtc($TIMESTAMP, $tz);
# DateTime : 09 July 2022 13:11:12
# Kind : Utc
# now convert it to a unix epoch timestamp
$EPOCHTIME = $UTCTIME | Get-Date -UFormat "%s";
# 1657372272
Bonus Round
You get the Unix epoch timestamp 1657361472 because the current timezone on the computer where you're running your script is UTC, which is 3 hours offset from the timezone the string is local to.
Notes on DateTime.ParseExact Method
If s does not represent a time in a particular time zone and the parse
operation succeeds, the Kind property of the returned DateTime value is
DateTimeKind.Unspecified. If s does represent the time in a particular time
zone and format allows time zone information to be present (for example, if
format is equal to the "o", "r", or "u" standard format specifiers, or if it
contains the "z", "zz", or "zzz" custom format specifiers), the Kind
property of the returned DateTime value is DateTimeKind.Local.
This question has been answered in this post:
Get formatted universal date / time
Essentially, it depends on the version of PowerShell that you're using. If it's Powershell 7.1+, then you can do:
Get-Date -AsUTC -UFormat "%s"
Otherwise, if it's a lower version, you need to use
Get-Date ([datetime]::UtcNow) -UFormat "%s"

How to load datetime value from a string in FileDateTime format in powershell?

Get-Date -Format FileDateTime
gives something like this:
20211027T1306219297
Is it possible to import such a string into a datetime variable?
Something like?
$date = Get-Date "20211027T1306219297"
You can use [datetime]::ParseExact method with yyyyMMddTHHmmssffff as format argument.
$date = [datetime]::ParseExact("20211027T1306219297", 'yyyyMMddTHHmmssffff', $null)
This is because FileDateTime internally uses yyyyMMddTHHmmssffff format which is documented here.
FileDateTime.
A file or path-friendly representation of the current date and time in
local time, in 24-hour format. The format is yyyyMMddTHHmmssffff
(case-sensitive, using a 4-digit year, 2-digit month, 2-digit day, the
letter T as a time separator, 2-digit hour, 2-digit minute, 2-digit
second, and 4-digit millisecond). For example: 20190627T0840107271.

PowerShell time conversion to UTC from a GMT+1 string

i use PowerShell for scripting some stuff.
Actual i got a string from a logfile - this one i prepared a timestamp like this example:
$timestamp = $timestampDate + " " + $timestampTime
#timestamp: 2020.11.16 06:03:27
This timestamp is a GMT+1 timestamp from my timezone but i need it in UTC (wintertime).
So i try:
get-date('2020.11.16 06:03:27') -f "yyyy.MM.dd hh:mm:ss z"
2020.11.16 06:03:27 +1
Get-Date('2020.11.16 06:03:27') -Format FileDateTimeUniversal
20201116T0503270000Z
Now i try how i could format the result to 2020.11.16 05:03:27 in a easy way without string manipulation (my DB field is without timezone)
Thanks a lot.

convert given string datetime2(7) in powershell

I am getting date time in string format 2020-08-19T08:00:53.643Z .
I need to convert this into datetime2(7) format i.e 2020-01-20 21:10:11.4866667.
how can I do that with powershell
currently I am using this
$lastExectedTime= Get-Date $temp -Format "yyyy-MM-dd HH:mm:ss.fffffff"
I am using something similar to Daniel Björks answer (using Parse method from [datetime])
C:\> ([datetime]::Parse("2020-08-19T08:00:53.643Z")).ToString("yyyy-MM-dd HH:mm:ss.fffffff")
2020-08-19 10:00:53.6430000
You can do like this:
([DateTime]"2020-08-19T08:00:53.643Z").ToString("yyyy-MM-dd HH:mm:ss.fffffff")

Can't convert value from datatable to datetime

Using powershell 5.1
I have a function called that returns a string representing a date like this
"4/22/2019 12:00:00 AM"
function Get-LastLogTime() {
$lastRunDate = Get-SQLData "." "AdHoc" "SELECT TOP 1 o.LogTime FROM dbo.FAQlog o WHERE o.RecordsSent = 1 ORDER BY o.LogTime DESC"
return $lastRunDate
}
Where LogTime is the usual Datetime SQL type and Get-SQLData is another function that returns a datatable.
If I just check the return value, I get something like this
LogTime
-------
4/22/2019 12:00:00 AM
Ok, great, but I need to compare this date to the current date. So, I do something like this but i get an error on the line trying to convert $testDate to datetime.
# test
$testDate = Get-LastLogTime
([DateTime]$testDate) -lt (Get-Date)
If I just do a simple comparison at the command line, it works, eg.
([DateTime]"4/22/2019 12:00:00 AM" ) -lt (Get-Date)
It works with
([DateTime]"4/22/2019 12:00:00 AM" )
Because you are casting DateTime on a String.
Return value of Get-LastLogTime is not a string probably and casting it to a Datetime does not work.
get-LastLogTime | get-member will show you the methods you have available on the returned data type such as, for instance, ToString, and that can be used to perform the comparison.