简体   繁体   中英

Understanding the time.Parse function in Go

I am currently porting code from go to c# and came across this (simplified) piece of code. I do know that it converts a given string 171228175744.085 using a given format 060102150405 .

The official docs only have examples using common formats like 2017-Feb-1 , not this format (a possible timestamp?)

I do know that this will result in the time beeing 2017-12-28 17:57:44.085 +0000 UTC , but I do not have a clue how, because I have no information what the string 171228175744.085 and layout represent. I do know that some of this information is GPS related. So, my question is: Does anyone know how to do this in c#?

package main

import (
    "fmt"
    "time"
)

func main() {
    t, err := time.Parse("060102150405", "171228175744.085")
    if err == nil{
        fmt.Println(t)
    }

}

The docs around time.Format explain what the format means.

Quoting:

Format returns a textual representation of the time value formatted
according to layout, which defines the format by showing how the 
reference time, defined to be

Mon Jan 2 15:04:05 -0700 MST 2006

The format string in your example: 060102150405 tells the time parser to look for the following:

  • 06: year
  • 01: month
  • 02: day of the month
  • 15: hour of the day
  • 04: minute
  • 05: second

This is a convenient way of telling the parser how it should interpret each number. If you look carefully, you'll see that numbers are not reused so when you say 06 , the parser matches it to 2006 .

In C#, you can use datetime.ParseExact . Something along the lines of:

DateTime.ParseExact(dateString, "yyMMddhhmmss", some_provider);

(note: I have not tried the C# snippet above. You may need to adjust it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM