Any easier ways to get the current datestamp - go

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

Related

How to get a day of week from civil.Date

How can I get a day of week from civil.Date using the type civil.Date such as Monday, Sunday.
date := civil.Date{
Year: 2021,
Month: time.May,
Day: 1}
I am looking for the equivalent to Weekday() function of 'time' package.
Any alternative way is also welcomed.
How about
package main
import (
"fmt"
"os"
"time"
"cloud.google.com/go/civil"
)
func main() {
date := civil.Date{
Year: 2021,
Month: time.September,
Day: 5,
}
t, err := time.Parse(time.RFC3339, date.String()+"T00:00:00Z")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
fmt.Println(t.Weekday().String())
}

Go time.Parse() getting "month out of range" error

I'm new to Go and I was creating a little console script. You can check my code here:
package main
import (
"bufio"
"fmt"
"os"
"time"
)
func main() {
reader := bufio.NewReader(os.Stdin)
fmt.Println("Calculate")
fmt.Print("Hours and minutes: ")
start, _, _ := reader.ReadLine()
begin, err := time.Parse("2016-12-25 00:00:00", "2016-12-25 "+string(start)+":00")
if err != nil {
fmt.Println(err)
}
fmt.Println(begin)
}
I've seen a related question but I couldn't understand why.
This is the error I'm getting after running my code:
parsing time "2016-12-25 22:40:00": month out of range
0001-01-01 00:00:00 +0000 UTC
Any ideas on what am I doing wrong?
Thanks
You're using the wrong reference time in the layout parameter of time.Parse which should be Jan 2, 2006 at 3:04pm (MST)
Change your begin line to the following and it will work:
begin, err := time.Parse("2006-01-02 15:04:05", "2016-12-25 "+string(start)+":00")
func Parse
To avoid having to remember the special date, I usually wrap the logic in a
function:
package main
import (
"fmt"
"time"
)
func parseDate(value string) (time.Time, error) {
layout := time.RFC3339[:len(value)]
return time.Parse(layout, value)
}
func main() {
start := "15:04"
d, e := parseDate("2016-12-25T" + start)
if e != nil {
panic(e)
}
fmt.Println(d)
}

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...!?")
}
}

How to get hours difference between two dates

I'm working for first time on Go, in this case i have a string on UTC format, I would like to know, how can I get the difference in hours between my date and the time now.
This is my current string
v := "2014-05-03 20:57 UTC"
Use time.Parse and time.Since:
package main
import (
"fmt"
"time"
)
const (
// See http://golang.org/pkg/time/#Parse
timeFormat = "2006-01-02 15:04 MST"
)
func main() {
v := "2014-05-03 20:57 UTC"
then, err := time.Parse(timeFormat, v)
if err != nil {
fmt.Println(err)
return
}
duration := time.Since(then)
fmt.Println(duration.Hours())
}
Have a look at the time package.
package main
import "fmt"
import "time"
func main() {
a, err := time.Parse("2006-01-02 15:04 MST", "2014-05-03 20:57 UTC")
if err != nil {
// ...
return
}
delta := time.Now().Sub(a)
fmt.Println(delta.Hours())
}

Go printing date to console

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)
}

Resources