Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

time.Time Round to Day

Tags:

go

I have a timestamp coming in, I wonder if there's a way to round it down to the start of a day in PST. For example, ts: 1305861602 corresponds to 2016-04-14, 21:10:27 -0700, but I want to round it to a timestamp that maps to 2016-04-14 00:00:00 -0700. I read through the time.Time doc but didn't find a way to do it.

like image 379
J Freebird Avatar asked May 02 '16 18:05

J Freebird


People also ask

How to round time in Golang?

The Time. Round() function in Go language is used to find the output of rounding the stated time “t” to the closest multiple of the given duration “d” from the zero time. And the behavior of rounding for mid-values is to round up.

How do you round up days in Python?

Python's Built-in round() Function Python has a built-in round() function that takes two numeric arguments, n and ndigits , and returns the number n rounded to ndigits . The ndigits argument defaults to zero, so leaving it out results in a number rounded to an integer.

How do I use time in Golang?

Golang == operator compares not only time instant but also the Location and the monotonic clock reading. time. Duration has a base type int64. Duration represents the elapsed time between two instants as an int64 nanosecond count”.

How do you add time in Golang?

Add() function in Go language is used to add the stated time and duration. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Here, “t” is the stated time and “d” is the duration that is to be added to the time stated.


1 Answers

The simple way to do this is to create new Time using the previous one and only assigning the year month and day. It would look like this;

rounded := time.Date(toRound.Year(), toRound.Month(), toRound.Day(), 0, 0, 0, 0, toRound.Location()) 

here's a play example; https://play.golang.org/p/jnFuZxruKm

like image 140
evanmcdonnal Avatar answered Sep 27 '22 16:09

evanmcdonnal