Aga
Aga

Reputation: 1394

Bringing to a common date

I would like to comapre two dates which are strings: "2021-05-30T15:00:00", "2021-05-30" and return true when the day is the same. I want to ignore hour.

"2021-05-30T15:00:00" => 2021-05-30  
"2021-05-30" => 2021-05-30  
2021-05-30 == 2021-05-30  // true

To achieve this I made two functions which format date. timeParser is for date with hour. simplifyDate is for string date without hour.

const dateFormat = "2006-01-02T15:04:05"
const simpleDateFormat = "2006-01-02"

const departureTime = "2021-05-30T15:00:00"
const startDate = "2021-05-30"


func timeParser(format, value string) time.Time {
    parsed, err := time.Parse(format, value)
    if err != nil {
        fmt.Println("timeParser Error: ", err)
    }
    return parsed
}

func simplifyDate(value string) time.Time {
    parsed, err := time.Parse(dateFormat, value)
    parsed.Format(simpleDateFormat)
    if err != nil {
        fmt.Println("timeParser Error: ", err)
    }
    return parsed
}


isStartDate := simplifyDate(departureTime) == timeParser(simpleDateFormat, startDate) // return false 

fmt.Println("simplifyDate(departureTime)", simplifyDate(departureTime)) //2021-05-30 15:00:00 +0000 UTC
fmt.Println("timeParser(simpleDateFormat, startDate)", timeParser(simpleDateFormat, startDate)) // 2021-05-30 00:00:00 +0000 UTC

In timeParser and simplifyDate I try to format date into DD-MM-YYYY as simpleDateFormat = "2006-01-02" is. But I get date with hours and zeros at the end like 2021-05-30 00:00:00 +0000 UTC, 2021-05-30 15:00:00 +0000 UTC. Can you point out what am I doing wrong?

Upvotes: 0

Views: 48

Answers (2)

Zombo
Zombo

Reputation: 1

Given the circumstances, it seems you could just do string comparison:

package main

func compare(s, t string) bool {
   if len(s) > 10 {
      s = s[:10]
   }
   if len(t) > 10 {
      t = t[:10]
   }
   return s == t
}

func main() {
   for _, each := range []struct {
      s, t string
      res bool
   } {
      {"", "", true},
      {"", "2021-05-30T15:00:00", false},
      {"2021-05-30T15:00:00", "", false},
      {"2021-05-30T15:00:00", "2021-05-30", true},
   } {
      if compare(each.s, each.t) == each.res {
         println("pass")
      } else {
         println("fail")
      }
   }
}

Upvotes: 1

Hymns For Disco
Hymns For Disco

Reputation: 8405

After parsing the dates, you don't need to format them to compare them. The time.Time type has some methods that will help you here.

Try something like this:

// time1 and time2 are your raw time.Time values
return (time1.Year() == time2.Year()) && (time1.YearDay() == time2.YearDay())

Time.Year

Year returns the year in which t occurs.

Time.YearDay

YearDay returns the day of the year specified by t, in the range [1,365] for non-leap years, and [1,366] in leap years.

Upvotes: 1

Related Questions