Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In golang, Time.Format() removes trailing zeros from fractional part

Tags:

go

How can I prevent go's Time.Format() from removing trailing zeros from fractional part? I have following unit tests that fails.

package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.999-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}

Output:

$ go test
--- FAIL: TestTimeFormatting (0.00s)
    main_test.go:14: Invalid timestamp formating, expected 2017-01-02T03:04:05.600+00:00, got 2017-01-02T03:04:05.6+00:00
FAIL
exit status 1
FAIL    _/home/sasa/Bugs/go-formatter   0.001s

Any idea how to solve this?

like image 849
Sasa Avatar asked Nov 07 '17 18:11

Sasa


People also ask

How do I get rid of trailing zeros?

A better way to remove trailing zeros is to multiply by 1 . This method will remove trailing zeros from the decimal part of the number, accounting for non-zero digits after the decimal point. The only downside is that the result is a numeric value, so it has to be converted back to a string.

How do I change the format of time in Golang?

Golang supports time formatting and parsing via pattern-based layouts. To format time, we use the Format() method which formats a time. Time object. We can either provide custom format or predefined date and timestamp format constants are also available which are shown as follows.

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”.

Which is valid go time format literal?

Golang Time Format YYYY-MM-DD.


1 Answers

Ah, is was there in documentation. One should use 000 instead of 999 if you want to keep zeros.

package main

import (
    "testing"
    "time"
)

func TestTimeFormatting(t *testing.T) {
    timestamp := time.Date(2017, 1,2, 3, 4, 5, 600000*1000, time.UTC)
    timestamp_string := timestamp.Format("2006-01-02T15:04:05.000-07:00")
    expected := "2017-01-02T03:04:05.600+00:00"

    if expected != timestamp_string {
        t.Errorf("Invalid timestamp formating, expected %v, got %v", expected, timestamp_string)
    }
}
like image 107
Sasa Avatar answered Sep 20 '22 22:09

Sasa