TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to GO

Golang Time: Now, Parse and Duration

Use the time package to get and modify times. Get Now, Year, Month and Day.
Time. Programs often handle times and dates. They read strings in from files, parse them, test them for validity. Times are changed.
With the time package, we access many usable funcs on the Time struct. These methods are reusable and tested. This is a clear advantage.
Now example. Let us start with this simple example. We import the "time" package in the import block at the top. We invoke the Now method from the time package. It returns a struct.

Year: With year we get an int equal to the year field in the Time struct. Here it returns 2015.

Month: This returns the month of the time struct as an int. When we use Println, its String method displays it in a readable way.

Day: This is the day field of the Time struct—not the total number of days in the time.

Golang program that uses time, Year, Month, Day package main import ( "fmt" "time" ) func main() { // Get the current time. t := time.Now() fmt.Println(t) // Print year, month and day of the current time. fmt.Println(t.Year()) fmt.Println(t.Month()) fmt.Println(t.Day()) } Output 2017-02-21 15:08:12.0658324 -0800 PST 2017 February 21
Parse. With this func we convert a string to a Time struct. Parse receives two strings: a form string and the value we are parsing.

Return: Parse() returns two things: the Time struct and an error (if any). We can use the blank identifier to ignore the error.

Quote: Parse parses a formatted string and returns the time value it represents. The layout defines the format by showing how the reference time, defined to be Mon Jan 2 15:04:05 -0700 MST 2006 would be interpreted if it were the value.

Time: golang.org
Golang program that uses time, Parse package main import ( "fmt" "time" ) func main() { // This is the value we are trying to parse. value := "January 28, 2015" // The form must be January 2,2006. form := "January 2, 2006" // Parse the string according to the form. t, _ := time.Parse(form, value) fmt.Println(t) } Output 2015-01-28 00:00:00 +0000 UTC
Sub, Duration. This example combines many time concepts. It uses Now() twice to measure the time required to run a piece of code. Then it uses Sub() to get a duration.

Seconds: This is a method on the duration that is returned by Sub. It is a floating-point number.

Minutes: This is like seconds, but divided by 60. It is mainly a convenience method.

Golang program that uses Sub, Duration, Seconds, Minutes package main import ( "fmt" "time" ) func main() { t0 := time.Now() // Do a slow operation. count := 0 for i := 0; i < 100000; i++ { for x := 0; x < i; x++ { count++ } } t1 := time.Now() // Display result. fmt.Println(count) // Get duration. d := t1.Sub(t0) fmt.Println("Duration", d) // Get seconds from duration. s := d.Seconds() fmt.Println("Seconds", s) // Get minutes from duration. m := d.Minutes() fmt.Println("Minutes", m) } Output 4999950000 Duration 1.8052613s Seconds 1.8052613000000002 Minutes 0.030087688333333334
Create Time, time.Date. To create a Time from ints (like the year, month and day) we call the time.Date func. The time.Date func returns a new Time instance.

Tip: Don't pass nil as the Location (the last argument). This will cause a panic. I found this out the hard way.

Golang program that uses time.Date to create Time package main import ( "fmt" "time" ) func main() { // Create a Date in 2006. t := time.Date(2006, 1, 1, 12, 0, 0, 0, time.UTC) fmt.Println(t) } Output 2006-01-01 12:00:00 +0000 UTC
Before, After. Does one Time come before another? With the Before() func we can determine temporal order. And with After(), we can test whether one time comes after another.
Golang program that uses Before, After package main import ( "fmt" "time" ) func main() { // T1 is a time earlier than t2. t1 := time.Date(2000, 1, 1, 12, 0, 0, 0, time.UTC) t2 := time.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC) // This is true: the first time is before the second. if t1.Before(t2) { fmt.Println(true) } // This is true. if t2.After(t1) { fmt.Println(true) } // This returns false. fmt.Println(t1.After(t2)) } Output true true false
Equal. With the Equal() func we see if two times indicate the same instant. Equal() adjusts for Locations. With the "==" operator, the Locations must also be equal.

Note: Equal() is a more conceptual time comparison, which accounts for Locations. The "==" operator just compares two Time instances.

Golang program that compares times with Equal package main import ( "fmt" "time" ) func main() { // These times are created with equal values. t1 := time.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC) t2 := time.Date(2015, 1, 1, 12, 0, 0, 0, time.UTC) // Compare times. if t1 == t2 { fmt.Println("Times are equal") } // Equal adjusts for locations. if t1.Equal(t2) { fmt.Println(true) } } Output Times are equal true
Sleep. This func receives a Duration. It then pauses execution on the current goroutine for that duration of time. Here we call sleep four times for 100 ms each time.

Duration: We construct the Duration from nanoseconds. One million nanoseconds is one millisecond. We multiply that by 100 for 100 ms.

Golang program that uses Sleep and Duration package main import ( "fmt" "time" ) func main() { for i := 0; i < 4; i++ { // Duration receives nanoseconds. // ... 100 million nanoseconds is 100 milliseconds. d := time.Duration(1000 * 1000 * 100) // Sleep for 100 ms. time.Sleep(d) fmt.Println(time.Now()) } } Output 2015-07-25 15:59:42.3227647 -0700 PDT 2015-07-25 15:59:42.4247739 -0700 PDT 2015-07-25 15:59:42.5249032 -0700 PDT 2015-07-25 15:59:42.6249464 -0700 PDT
Format. With Format we convert a Date into a string. As with Parse, we use the special date Jan 2, 2006 to indicate the formatting.

Here: We convert the result of Now() to a simple date format. The Format method returns a string.

Golang program that uses Format package main import ( "fmt" "time" ) func main() { // This date is used to indicate the layout. const layout = "Jan 2, 2006" // Format Now with the layout const. t := time.Now() res := t.Format(layout) fmt.Println(res) } Output Jul 27, 2015
Since. The Since() func is an easy way to compute the elapsed hours from a point in time. We do not need to use Now and Sub separately—Since() includes this logic for us.

Part 1: We create a new Date with time.Date. We specify 8 arguments to time.Date for this purpose.

Part 2: We invoke the time.Since() func and pass the date we just created to it. Time.Since accesses the current time.

Part 3: The program displays how many days have passed since the specified date in January 2018.

Golang program that uses time.Since func package main import ( "fmt" "time" ) func main() { // Part 1: get first day of 2018. t := time.Date(2018, 1, 1, 0, 0, 0, 0, time.UTC) fmt.Println(t) // Part 2: compute days since first day of 2018. timePassed := time.Since(t) // Part 3: display result. fmt.Println("Days passed:", timePassed.Hours() / 24) } Output 2018-01-01 00:00:00 +0000 UTC Days passed: 728.0187105963055
Benchmarks. The time module can be used to take benchmarks. We use Sub to get a difference (a duration) between two times returned by Now calls. An example is present on the map page.map
With the Time struct, we gain a way to represent a point in time (a Date). And with the methods in time, we can manipulate it. We cannot go back in time, but we can represent it.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf