Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

Parse iso8601 duration strings, and use to shift dates/times.

License

NotificationsYou must be signed in to change notification settings

senseyeio/duration

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

23 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Parse ISO8601 duration strings, and use to shift dates/times.

Basic Example

package mainimport ("fmt""time""github.com/senseyeio/duration")funcmain() {d,_:=iso8601.ParseISO8601("P1D")today:=time.Now()tomorrow:=d.Shift(today)fmt.Println(today.Format("Jan _2"))fmt.Println(tomorrow.Format("Jan _2"))}

Why Does This Package Exist

Why can't we just use atime.Duration andtime.Add?

A very reasonable question.

The code below repeatedly adds 24 hours to atime.Time. You might expect the time on that date to stay the same, butthere are not always 24 hours in a day. When the clocks change in New York, the time will skew by an hour. As you can see from the output, duration.Duration.Shift() can increment the date without shifting the time.

package mainimport ("fmt""time""github.com/senseyeio/duration")funcmain() {loc,_:=time.LoadLocation("America/New_York")d,_:=iso8601.ParseISO8601("P1D")t1,_:=time.ParseInLocation("Jan 2, 2006 at 3:04pm","Jan 1, 2006 at 3:04pm",loc)t2:=t1fori:=0;i<365;i++ {t1=t1.Add(24*time.Hour)t2=d.Shift(t2)fmt.Printf("time.Add:%d    Duration.Shift:%d\n",t1.Hour(),t2.Hour())}}// Outputs// time.Add:15    Duration.Shift:15// time.Add:15    Duration.Shift:15// time.Add:15    Duration.Shift:15// ...// time.Add:16    Duration.Shift:15// time.Add:16    Duration.Shift:15// time.Add:16    Duration.Shift:15// ...

Months are tricky. Shifting by months usestime.AddDate(), which is great. However, be aware of how differing days in the month are accommodated. Dates will 'roll over' if the month you're shifting to has fewer days. e.g. if you start on Jan 30th and repeat every "P1M", you'll get this:

Jan 30, 2006Mar 2, 2006Apr 2, 2006May 2, 2006Jun 2, 2006Jul 2, 2006Aug 2, 2006Sep 2, 2006Oct 2, 2006Nov 2, 2006Dec 2, 2006Jan 2, 2007

About

Parse iso8601 duration strings, and use to shift dates/times.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp