Parse ISO 8601 time duration using Go (for instance PT90M) - go

Is there any easy way to convert an ISO 8601 string time duration (P(n)Y(n)M(n)DT(n)H(n)M(n)S) to time.Duration?
From Wikipedia on ISO 8601 durations:
For example, "P3Y6M4DT12H30M5S" represents a duration of "three years, six months, four days, twelve hours, thirty minutes, and five seconds".

There is no API in standard library for that, but there is a 3rd party library that can add ISO 8601 duration to a time.Time: https://godoc.org/github.com/senseyeio/duration#Duration.Shift.
ISO 8601 duration can not be generally converted to a time.Duration because it depends on the base time.Time.
https://play.golang.org/p/guybDGoJVrT
package main
import (
"fmt"
"time"
"github.com/senseyeio/duration"
)
func main() {
d, _ := duration.ParseISO8601("P1D")
today := time.Now()
tomorrow := d.Shift(today)
fmt.Println(today.Format("Jan _2")) // Nov 11
fmt.Println(tomorrow.Format("Jan _2")) // Nov 12
}

Finding existing solutions less than satisfactory I created my own module to parse ISO 8601 durations and convert them directly to a time.Duration. I hope you find it useful. :)
example usage: https://go.dev/play/p/Nz5akjy1c6W

Related

Understanding tz offset discrepancy on different systems

Hoping someone can see what I'm doing wrong, or misunderstanding.
I was using the time pkg in the Go Sandbox, to become familiar with how to use the timezone specific functions correctly.
Even though I already knew some of the offsets, I used the following site to double check myself : https://documentation.mersive.com/content/topics/api-timezones.htm.
In this case, when I ask for the offset for "America/New_York", I expect -14400.
However, when I ran the following on the Go Sandbox, I get -18000 instead:
https://play.golang.org/p/aU0JFHzueU1
americatz, err := time.LoadLocation("America/New_York")
if err != nil {
fmt.Println(err)
return
}
t := time.Now().In(americatz)
zone, offset := t.Zone()
fmt.Printf("%v :: %v\n", zone, offset)
I noticed that when I brought the same code over to a linux machine, it did exactly what I expected. I'm nervous, because I don't have a firm understanding why the two output's for a very common tz would be different.
I know enough that LoadLocation looks for a zipfile from the ZONEINFO env var. Otherwise it'll look in other system places like the $GOROOT/lib/time/zoneinfo.zip.
Is it really just plain and simple that the Go Server the code runs on vs the linux server have different zone info files? And if I want the exact same behavior across all systems... does this mean I need to always load in and set my own ZONEINFO variable? I feel like most people would expect -14400...
Thanks.
In the playground the time is set to "2009-11-10 23:00:00 UTC" because "This makes it easier to cache programs by giving them deterministic output." (from the 'About' box).
This can have an impact on the timezone offset due to daylight savings. The following will give the answer you are expecting:
today := time.Date(2020,10,16,0,0,0,0,americatz)
zone, offset = today.Zone()
fmt.Printf("%v :: %v\n", zone, offset)
Playground
Further detail:
Due to daylight savings the offset changes depending upon the time; for example:
time.Date(2020,10,16,0,0,0,0,americatz).Zone() will return an offest of -14400 whereas time.Date(2020,1,16,0,0,0,0,americatz).Zone() would return -18000.
It just so happens that the time that now() returns in the playground (2009-11-10) is EST (daylight savings ended Sunday, 1 November 2009, 2:00 a.m.) rather than EDT. If you run your test again in a month you will not see this difference because both times will be in EST.

Get complete UTC offset format

I need to get the UTC offset for a location. I am getting trouble with the inconsistency of the results from different values. All I need to get are values in the format +HHMM (e.g., +0100 for "Europe/Rome").
func main() {
loc, _:= time.LoadLocation("Asia/Kathmandu")
offset, others:= time.Now().In(loc).Zone()
fmt.Println(offset, others)
}
Playground
What I get:
"Asia/Kathmandu": +0545 (suitable)
"Asia/Ho_Chi_Minh": +07 (should be +0700)
"America/Phoenix": MST (should be -0700)
"Europe/Rome": CET (should be +0100)
Reference Timezone country names
The Zone() method you're using is working exactly as advertized.
Zone computes the time zone in effect at time t, returning the abbreviated name of the zone (such as "CET") and its offset in seconds east of UTC.
A better approach for you would be to use the Format method. Something like:
zone := time.Now().In(loc).Format("-0700")
Of course, be aware: Even this won't be 100% consistent, due to daylight savings time.

Why running Golang's time.Now() at OpenWRT always get UTC time?

I wrote a Golang program that runs on OpenWRT.
package main
import (
"fmt"
"time"
)
func main(){
fmt.Println(time.Now())
}
When I run this program on my Macbook, I always get the correct local time.
However, when running this program on OpenWRT, I always get UTC time.
I have set the time zone and time of OpenWRT. When I execute uci show system, I can see the right time zone. When I execute date the right local time can be display correctly.
So my question is, how do I get the correct local time using Golang's time.Now() on OpenWRT?
The root of my problem is that my OpenWRT lacks the zoneinfo package. So I run opkg update && opkg install zoneinfo-xxx first.
This is part of go/src/time/zoneinfo_unix.go:
func initLocal() {
// consult $TZ to find the time zone to use.
// no $TZ means use the system default /etc/localtime.
// $TZ="" means use UTC.
// $TZ="foo" means use /usr/share/zoneinfo/foo.
...
}
According to this file, if there is no "TZ" variable, Golang will use the time zone pointed to by /etc/localtime when calling time.Now().
Then I set time zone at /etc/config/system (option zonename 'xxxxxx') and run /etc/init.d/system restart. Finally, I can get the correct time.Now().
OpenWRT stores the time zone inside a file named /etc/TZ. If this file is missing or empty, OpenWRT assumes the local time equals UTC time. Source
how do I get the correct local time using Golang's time.Now() on
OpenWRT?
Specifying the Time Zone with TZ
The is the value you must add to or substract from the local time to get the UTC time. This offset will be positive if the local time zone is west of the Prime Meridian and negative if it is east.

How to convert between timezones in Go? [duplicate]

This question already has answers here:
Convert UTC to "local" time in Go
(3 answers)
Closed 7 years ago.
For example time.Now() has a timezone of UTC.
utcNow := time.Now()
fmt.Println(utcNow)
Outputs
2009-11-10 23:00:00 +0000 UTC
How do I convert this time to Japan Standard time?
It looks like you're running that in the Go playground, which is why the time is automatically set to UTC (it's also always set to November 2009 when a program is launched).
If you run time.Now() on your own machine, it should pick up the local region. Alternatively, if you want to force the time to be in a specific timezone, you can use a time.Location object along with the time.Time.In function.
l, err := time.LoadLocation("Asia/Tokyo") // Look up a location by it's IANA name.
if err != nil {
panic(err) // You can handle this gracefully.
}
fmt.Println(utcNow.In(l))
Note that it's still showing the same moment in time, but now with JST's offset.
For more information, look at the go documentation for the time package. http://golang.org/pkg/time

Trying to make sense of Windows timestamps....

I'm in a situation that involves the manual reconstruction of raw data, to include MFT records and other Windows artifacts. I understand that timestamps in MFT records are 64-bit integers, big endian, and are calculated by the number of 100 nanosecond intervals since 01/01/1601 00:00:00 UTC. I am also familiar with Windows email header timestamps, which consist of two 32-bit values that combine to form a single 64-bit value, also calculated by the number of 100 nanosecond intervals since 01/01/1601 00:00:00 UTC.
But there are other Windows timestamps with different epochs, such as SQL Server timestamps, which I believe use a date in the 1800's. I cannot find much documentation on all of this. What timestamps are used in Windows other than the two listed above? How do you break them down?
Here is some code for decoding Windows timestamps:
static string microsoftDateToISODate(const uint64_t &time) {
/**
* See comment above for more information on
* SECONDS_BETWEEN_WIN32_EPOCH_AND_UNIX_EPOCH
*
* Convert UNIX time_t to ISO8601 format
*/
time_t tmp = (time / ONE_HUNDRED_NANO_SEC_TO_SECONDS)
- SECONDS_BETWEEN_WIN32_EPOCH_AND_UNIX_EPOCH;
struct tm time_tm;
gmtime_r(&tmp, &time_tm);
char buf[256];
strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S", &time_tm);
return string(buf);
}
And your reference for Mac timestamps is:
Apple Mac and Unix timestamps
http://developer.apple.com/library/mac/#qa/qa1398/_index.html

Resources