简体   繁体   English

了解Go中的time.Parse函数

[英]Understanding the time.Parse function in Go

I am currently porting code from go to c# and came across this (simplified) piece of code. 我目前正在将代码从go移植到c#,并遇到了这段(简化的)代码。 I do know that it converts a given string 171228175744.085 using a given format 060102150405 . 我知道它转换给定的字符串171228175744.085使用给定的格式060102150405

The official docs only have examples using common formats like 2017-Feb-1 , not this format (a possible timestamp?) 官方文档仅包含使用常见格式(如2017-Feb-1示例,而不使用此格式(可能的时间戳?)。

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. 我确实知道这将导致时间2017-12-28 17:57:44.085 +0000 UTC ,但是我不知道如何,因为我不知道字符串171228175744.085和布局代表什么。 I do know that some of this information is GPS related. 我确实知道其中一些信息与GPS有关。 So, my question is: Does anyone know how to do this in c#? 因此,我的问题是:有人知道如何在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. 围绕time.Format的文档解释了格式的含义。

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: 您的示例中的格式字符串: 060102150405告诉时间解析器查找以下内容:

  • 06: year 06:年
  • 01: month 01:月
  • 02: day of the month 02:每月的某天
  • 15: hour of the day 15:一天中的小时
  • 04: minute 04:分钟
  • 05: second 05:第二

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 . 如果仔细看,您会发现数字没有被重用,因此当您说06 ,解析器会将其匹配到2006

In C#, you can use datetime.ParseExact . 在C#中,可以使用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) (注意:我没有尝试过上面的C#代码段。您可能需要对其进行调整)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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