How can i get the time stamp for this hour 0 minute 0 second?

3,494 views
Skip to first unread message

singochina

unread,
Jun 8, 2011, 11:51:25 PM6/8/11
to golang-nuts
Hi All,

I got a question, for example, currect time is 6/9/2011 11:50:34, and
i wanna got the time stamp for this hour 0 minute 0 second (6/9/2011
11:00:00), may i ask which method can i use under package time?

Regards,
Singo

Fabian Reinartz

unread,
Jun 9, 2011, 12:36:51 AM6/9/11
to singochina, golang-nuts
Basically you can eliminate everything that is not a full hour by dividing and throwing away the rest. So this should work quite good.

package main

import (
"time"
"fmt"
)

func main() {
seconds := time.Seconds() / 3600
fmt.Print(time.SecondsToLocalTime(seconds * 3600))
}

I just reduced the current seconds to full hours. From that value I just create a local time string to print it. Of course I have to multiply it by 3600 again to get the seconds of the full hours.

singochina

unread,
Jun 9, 2011, 2:01:04 AM6/9/11
to golang-nuts
Thanks a lot

On Jun 9, 12:36 pm, Fabian Reinartz <fab.reina...@googlemail.com>
wrote:

Rob 'Commander' Pike

unread,
Jun 9, 2011, 2:13:00 AM6/9/11
to singochina, golang-nuts
fmt.Println(time.LocalTime().Format("1/2/2006 15:00"))

-rob

roger peppe

unread,
Jun 9, 2011, 5:46:02 AM6/9/11
to Fabian Reinartz, singochina, golang-nuts

that won't work in general, as time zones may be on
sub-hour intervals (also i suppose it's possible that the time
package might account for leap seconds at some point).

rob's approach works great.

Fabian Reinartz

unread,
Jun 9, 2011, 10:12:28 AM6/9/11
to roger peppe, golang-nuts
Yes, Rob's solution is cleaner and better. My approach was just the first and fastest that came to my mind as I didn't know that you can use Format() in this case. But I don't know what you mean with sub-hour intervals.

roger peppe

unread,
Jun 9, 2011, 10:22:36 AM6/9/11
to Fabian Reinartz, golang-nuts

some time zones are not a whole multiple of hours from UTC.
(e.g. afghanistan is UTC+4:30)

thus taking time.Seconds and rounding down to the nearest whole hour
may not round down to the correct local hour.

Reply all
Reply to author
Forward
0 new messages