2017-03-26 7 views
0

文字列を時間オブジェクトに解析しようとしています。問題は、マイクロ秒の用語の桁数が変化し、解析が中断されることです。変数のマイクロ秒でのGoの解析エラーのエラー

package main 

import (
    "fmt" 
    "time" 
) 

func main() { 
    timeText := "2017-03-25T10:01:02.1234567Z" 
    layout := "2006-01-02T15:04:05.0000000Z" 
    t, _ := time.Parse(layout, timeText) 
    fmt.Println(t) 
} 

しかし、マイクロ秒の桁数がレイアウトと一致しないため、これは、エラーが発生します:たとえば、これは正常に動作します

package main 

import (
    "fmt" 
    "time" 
) 

func main() { 
    timeText := "2017-03-25T10:01:02.123Z" // notice only 3 microseconds digits here 
    layout := "2006-01-02T15:04:05.0000000Z" 
    t, _ := time.Parse(layout, timeText) 
    fmt.Println(t) 
} 

私はこの問題を解決するにはどうすればよいマイクロ秒の期間となるようまだ解析されていますが、何桁あるかは関係ありません。代わり秒以下の形式でゼロの

答えて

1

使用9S、for exampledocsから

timeText := "2017-03-25T10:01:02.1234567Z" 
layout := "2006-01-02T15:04:05.99Z" 
t, _ := time.Parse(layout, timeText) 
fmt.Println(t) //prints 2017-03-25 10:01:02.1234567 +0000 UTC 

// Fractional seconds can be printed by adding a run of 0s or 9s after 
// a decimal point in the seconds value in the layout string. 
// If the layout digits are 0s, the fractional second is of the specified 
// width. Note that the output has a trailing zero. 
do("0s for fraction", "15:04:05.00000", "11:06:39.12340") 

// If the fraction in the layout is 9s, trailing zeros are dropped. 
do("9s for fraction", "15:04:05.99999999", "11:06:39.1234") 
+0

どのように多くの9代、私が使用する必要がありますか? – BlueSky

+1

1つ以上は任意の桁数を受け入れます。 – Mark