Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Simple Example & Uses Of Time Package in Go

This Go tutorial help to understand time package of golang. Go provides extensive support for times and duration.Time package have many builtin function that help to solve daily common programming issues, which was other programming language do not have.

You can get more information of time() package from Official website.We will provide simple example to get current date,past date, Format date etc.

The package:

import (
	"fmt"
	"time"
)

How to get Current Date and Time In go

We will use now() method to get current date and time, You can change format in UTC using UTC() method.

now := time.Now()
//get local timezone time
fmt.Println("local time is :", now.Local())
/get UTC timezone time
fmt.Println("UTC time is :", now.UTC())

How to Create Past Date and Time In go

We will use Date() method to parse passed date into timezone format, You can change timezone as well.

then := time.Date(2016, 06, 12, 24, 46, 37, 4355433, time.UTC)
fmt.Println("Then time in UTC FORMAT is :", then)

How to get Year, Month and Day

We will use year(), month() and day() method to get time year,month and day.

fmt.Println("Now year is :", now.Year())
fmt.Println("Now Month is :", now.Month())
fmt.Println("Now Day is :", now.Day())

How To Get Weekday Name in GO

The Day() method return the number of day but not name, Weekday() method return the name of the day.

fmt.Println("Then Weekday is :", then.Weekday())

How To Get Date Difference in GO

The Sub() method return the duration of between two date.You can convert duration into Hour, Minute, Seconds and Milliseconds.

now := time.Now().UTC()
then := time.Date(2016, 06, 12, 24, 46, 37, 4355433, time.UTC)
fmt.Println("Then time in UTC FORMAT is :", then)
fmt.Println("Then year is :", then.Year())
fmt.Println("Then Month is :", then.Month())
fmt.Println("Then Day is :", then.Day())
fmt.Println("Then Weekday is :", then.Weekday())

diff := now.Sub(then)
fmt.Println("Difference in hour :", diff.Hours())
fmt.Println("Difference in day :", diff.Hours())
fmt.Println("Number of days :", int(diff.Hours()/24))

Output :

The post Simple Example & Uses Of Time Package in Go appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

Simple Example & Uses Of Time Package in Go

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×