Fatima Fahad
Fatima Fahad

Reputation: 105

Parse Date dynamically

I have a case in which I can have both Date alone or with Date + Time Zone . So when I parse it with TimeZone like this

dateString := "2021-03-11T00:00:00Z"
time1, _ := time.Parse(time.RFC3339,dateString);
   
fmt.Println(time1);
 

It gives accurate answer but when I dynamically It gets Date like

dateString := "2021-03-11"
time1, _ := time.Parse(time.RFC3339,dateString);
   
fmt.Println(time1);   //gives this 0001-01-01 00:00:00 +0000 UTC

while In both cases I just want date like this "2021-03-11". what is best way to achieve this

Upvotes: 0

Views: 2780

Answers (1)

Eli Bendersky
Eli Bendersky

Reputation: 273466

To parse just the date, you can use "2006-01-02" as the layout to time.Parse.

See the official docs for how these layouts are handled and what time.Parse expects.

As @zerkms says in a comment, if you check the error from time.Parse you'll know whether it succeeded or not, so you can try something else. Rough code sketch:

dateString := "2021-03-11"
time1, err := time.Parse(time.RFC3339, dateString)
if err != nil {
    time1, err = time.Parse("2006-01-02", dateString)
    if err != nil {
        log.Fatal("cannot parse using either layout:", err)
    }
}

fmt.Println(time1)

In real life I'd probably wrap it in a function that tries parsing both ways before it gives up and returns an error.

Upvotes: 3

Related Questions