Go printing date to console - go

I'm trying to pint the month, day, and year, separately to the console.
I need to be able to access each section of the date individually. I can get the whole thing using time.now() from the "time" package but I'm stuck after that.
Can anyone show me where I am going wrong please?

You're actually pretty close :) Then return value from time.Now() is a Time type, and looking at the package docs here will show you some of the methods you can call (for a quicker overview, go here and look under type Time). To get each of the attributes you mention above, you can do this:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Println(t.Month())
fmt.Println(t.Day())
fmt.Println(t.Year())
}
If you are interested in printing the Month as an integer, you can use the Printf function:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
fmt.Printf("%d\n", t.Month())
}

Day, Month and Year can be extracted from a time.Time type with the Date() method. It will return ints for both day and year, and a time.Month for the month. You can also extract the Hour, Minute and Second values with the Clock() method, which returns ints for all results.
For example:
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
y, mon, d := t.Date()
h, m, s := t.Clock()
fmt.Println("Year: ", y)
fmt.Println("Month: ", mon)
fmt.Println("Day: ", d)
fmt.Println("Hour: ", h)
fmt.Println("Minute: ", m)
fmt.Println("Second: ", s)
}
Please remember that the Month variable (mon) is returned as a time.Month, and not as a string, or an int. You can still print it with fmt.Print() as it has a String() method.
Playground

You can just parse the string to get year, month, & day.
package main
import (
"fmt"
"strings"
)
func main() {
currTime := time.Now()
date := strings.Split(currTime.String(), " ")[0]
splits := strings.Split(date, "-")
year := splits[0]
month := splits[1]
day := splits[2]
fmt.Printf("%s-%s-%s\n", year, month, day)
}

Related

golang timestamp in RFC3339 format

how do we convert time.now() in time.Time( RFC3339) format?
Eg:
var t time.Time
timeNow= time.Now()
I want to assign timeNow to t
Golang has support for various time formats.
package main
import (
"fmt"
"time"
)
func main() {
t := time.Now()
r := t.Format(time.RFC3339)
fmt.Println("time.Now() ", t)
fmt.Println("RFC3339 ", r)
}

Any easier ways to get the current datestamp

I have this code here but I don't think it's elegant. In fact I think it's kind of messy. Does anyone have a better/cleaner/concise code than this? I just need the timestamp of the day.
package main
import (
"os"
"fmt"
"io"
"time"
"strconv"
)
const (
layoutISO = "2006-01-02"
layoutUS = "January 2, 2006"
)
func main() {
year, month, day := time.Now().Date()
dayStr := strconv.Itoa(day)
if len(dayStr) == 1 {
dayStr = "0"+dayStr
}
mthStr := strconv.Itoa(int(month))
if len(mthStr) == 1 {
mthStr = "0"+mthStr
}
layout := strconv.Itoa(year)+"-"+mthStr+"-"+dayStr
fmt.Printf("%v\n",layout)
t, err := time.Parse(layoutISO, layout)
if err != nil {
fmt.Println(err)
}
fmt.Println(t.Unix())
}
This is the answer #Marc suggested. Thanks.
fmt.Printf("Value = %v\n",time.Date(year, month, day, 0,0,0,0, time.UTC).Unix())
I don't fully understand what you're asking, but here are some ways to get the current date and time information.
fmt.Println("current date and time:", time.Now().Format("2 January 2006 15:04:05"))
fmt.Println("current time:", time.Now().Format("15:04:05"))
fmt.Println("current date:", time.Now().Format("2 January 2006"))
https://play.golang.org/p/U2PKjivNzXa

How to parse this date 2018-10-22T2250?

How to parse this strange datetime 2018-10-22T2250 in golang?
I couldn't find date layout
You can create your own custom format. In production, you should also handle the error.
package main
import (
"fmt"
"time"
)
func main() {
timeString := "2018-10-22T2250"
timeFormat := "2006-01-02T1504"
t, _ := time.Parse(timeFormat, timeString)
fmt.Println(t)
}
Playground link
This returns the time in UTC. You may need to adjust to another timezone, depending on your source.
//init the location
loc, _ := time.LoadLocation("Asia/Shanghai")
//localize the time
localTime := t.In(loc)

Why these two time.Time instances are same for UTC and different for another location?

I'm expecting these two time.Time instances are the same. But, I'm not sure why I got the compare result is false.
package main
import (
"fmt"
"time"
)
func main() {
t := int64(1497029400000)
locYangon, _ := time.LoadLocation("Asia/Yangon")
dt := fromEpoch(t).In(locYangon)
locYangon2, _ := time.LoadLocation("Asia/Yangon")
dt2 := fromEpoch(t).In(locYangon2)
fmt.Println(dt2 == dt)
}
func fromEpoch(jsDate int64) time.Time {
return time.Unix(0, jsDate*int64(time.Millisecond))
}
Playground
If I change "Asia/Yangon" to "UTC", they are the same.
package main
import (
"fmt"
"time"
)
func main() {
t := int64(1497029400000)
locYangon, _ := time.LoadLocation("UTC")
dt := fromEpoch(t).In(locYangon)
locYangon2, _ := time.LoadLocation("UTC")
dt2 := fromEpoch(t).In(locYangon2)
fmt.Println(dt2 == dt)
}
func fromEpoch(jsDate int64) time.Time {
return time.Unix(0, jsDate*int64(time.Millisecond))
}
Playground
Note: I'm aware of Equal method (in fact, I fixed with Equal method.) But after more testing, I found some interesting case which is "UTC" location vs "Asia/Yangon" location. I'm expecting either both equal or both not equal.
Update: Add another code snippet with "UTC".
Update2: Update title to be more precise (I hope it will help to avoid duplication)
LoadLocation seems to return a pointer to a new value every time.
Anyway, the good way to compare dates is Equal:
fmt.Println(dt2.Equal(dt))
Playground: https://play.golang.org/p/9GW-LSF0wg.

Calculate number of days between two dates?

How can I calculate the number of days between two dates? In the code below I should get the number of hours, which means that I should only need to divide by 24. However, the result I get is something like -44929.000000. I'm only looking a day or two back so I would expect 24 or 48 hours.
package main
import (
"fmt"
"time"
)
func main() {
timeFormat := "2006-01-02"
t, _ := time.Parse(timeFormat, "2014-12-28")
fmt.Println(t)
// duration := time.Since(t)
duration := time.Now().Sub(t)
fmt.Printf("%f", duration.Hours())
}
Here's the executable Go code: http://play.golang.org/p/1MV6wnLVKh
Your program seems to work as intended. I'm getting 45.55 hours. Have you tried to run it locally?
Playground time is fixed, time.Now() will give you 2009-11-10 23:00:00 +0000 UTC always.
package main
import (
"fmt"
"time"
)
func main() {
date := time.Now()
fmt.Println(date)
format := "2006-01-02 15:04:05"
then,_ := time.Parse(format, "2007-09-18 11:58:06")
fmt.Println(then)
diff := date.Sub(then)
//func Since(t Time) Duration
//Since returns the time elapsed since t.
//It is shorthand for time.Now().Sub(t).
fmt.Println(diff.Hours())// number of Hours
fmt.Println(diff.Nanoseconds())// number of Nanoseconds
fmt.Println(diff.Minutes())// number of Minutes
fmt.Println(diff.Seconds())// number of Seconds
fmt.Println(int(diff.Hours()/24))// number of days
}
Here is the running code https://play.golang.org/p/Vbhh1cBKnh
the below code gives the list of all the days along with the number of days between the from date and to date:
you can click on the link for the code in
Go PlayGround:https://play.golang.org/p/MBThBpTqjdz
to := time.Now()
from := to.AddDate(0, -1, 0)
fmt.Println("toDate", to)
fmt.Println("fromDate", from)
days := to.Sub(from) / (24 * time.Hour)
fmt.Println("days", int(days))
noofdays := int(days)
for i := 0; i <= noofdays; i++ {
fmt.Println(from.AddDate(0, 0, i))
}
One caveat to be mindful of when using this technique of timeOne.Sub(timeTwo).Hours() / 24 is that daylights savings can cause a day to contain only 23 hours, throwing this calculation off slightly.
Happy programmer's day
package main
import (
"fmt"
"time"
)
func main() {
loc, _ := time.LoadLocation("UTC")
now := time.Now().In(loc)
firstDate := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, loc)
diff := now.Sub(firstDate)
fmt.Printf("The difference between %s and today %s es %d days\n", now.String(), firstDate.String(), int(diff.Hours()/24)+1)
// Just a joke
if ( int(diff.Hours()/24)+1 == 256 ) {
fmt.Printf("¡Happy programmer's day!")
} else {
fmt.Printf("On my computer it works...!?")
}
}

Resources