Powershell string to unix time with correct timezone - powershell

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"

Related

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.

Current timestamp in ISO 8601 UTC time (ie: 2013-11-03T00:45:54+02:00)

Can someone please help me how to format timestamp in ISO 8601 UTC time?
I want the date to be formatted like this 2020-10-03T00:45:54+02:00
I have tried this in App Script.
Utilities.formatDate(new Date(), "UTC", "yyyy-MM-dd'T'HH:mm:ssZZZ");
It is getting this output 2020-10-03T08:50:18+0000
I want the timezone to be formatted like this TwoDigitHours : Minutes
Use Date.toISOString() for UTC ISO8601 string:
/*<ignore>*/console.config({maximize:true,timeStamps:false,autoScroll:false});/*</ignore>*/
console.log(new Date().toISOString())
<!-- https://meta.stackoverflow.com/a/375985/ --> <script src="https://gh-canon.github.io/stack-snippet-console/console.min.js"></script>
Utilities.formatDate accepts 3 arguments:
Date object
Timezone
SimpleDateFormat string
For, ISO8601 timestring use X instead of Z
For a specific timezone, use that timezone(GMT+2) as second argument instead of UTC
Utilities.formatDate(new Date(),"GMT+2" , "yyyy-MM-dd'T'HH:mm:ssXXX");
Alternatively, Use Session.getScriptTimeZone() or Spreadsheet.getSpreadsheetTimeZone() instead for the second argument:
Utilities.formatDate(new Date(),Session.getScriptTimeZone(), "yyyy-MM-dd'T'HH:mm:ssXXX");
//Or
Utilities.formatDate(new Date(),Spreadsheet.getSpreadsheetTimeZone(), "yyyy-MM-dd'T'HH:mm:ssXXX");

How to convert powershell UTC datetime object to EST

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.

Get last monday date

I want to get the last Monday date for the given date. For example If my input is 190113 I want the output as 190107 which is last Monday.
if {$current_date == "Mon"} {
set startday [clock seconds]
set startday [clock format $startday -format %y%m%d]
puts $startday
} else {
puts "no monday today"
#I don't know how to get last monday date
}
This can be done fairly simply, by taking advantage of the fact that clock scan has quite a complex parser, and you can supply a timestamp that everything is relative to via the -base option. Also, both clock scan and clock format take -format options so that you can specify exactly what is going on in your input and output data.
proc getLastMonday {baseDate} {
set base [clock scan $baseDate -format "%y%m%d"]
set timestamp [clock scan "12:00 last monday" -base $base]
return [clock format $timestamp -format "%y%m%d"]
# This would work as a one-liner, provided you like long lines
}
Demonstrating:
puts [getLastMonday 190113]; # ==> 190107
puts [getLastMonday 190131]; # ==> 190128
Reference: https://www.tcl.tk/man/tcl/TclCmd/clock.htm#M22
Here's a sample code-snippet for the purpose. Added inline comments for understanding:
proc get_last_monday_date {date} {
# Get the end timestamp for the specified date
set end_timestamp [clock scan ${date}-23:59:59 -format %y%m%d-%H:%M:%S]
# Get day of the week for the current date
set day_of_week [clock format $end_timestamp -format %u]
# Sunday may report as 0 or 7. If 0, change to 7
# if {$day_of_week == 0} {
# set day_of_week 7
# }
# Monday is 1st day of the week. Monday = 1.
# Find how many days to go back in time
set delta_days [expr $day_of_week - 1]
# Multiply the delta by 24 hours and subtract from end of the day timestamp
# Get the timestamp for the result. That's last Monday's timestamp.
return [clock format [clock add $end_timestamp -[expr $delta_days * 24] hours] -format %D]
}
puts "Last Monday for 01-Jan-2019: [get_last_monday_date 190101]"
puts "Last Monday for 06-Jan-2019: [get_last_monday_date 190106]"
puts "Last Monday for 15-Jan-2019: [get_last_monday_date 190115]"
puts "Last Monday for 31-Jan-2019: [get_last_monday_date 190131]"
Execution output:
Last Monday for 01-Jan-2019: 12/31/2018
Last Monday for 06-Jan-2019: 12/31/2018
Last Monday for 15-Jan-2019: 01/14/2019
Last Monday for 31-Jan-2019: 01/28/2019