Home > database >  Convert four character date string to a date string
Convert four character date string to a date string

Time:04-25

I am receiving the expiry date as a four-letter string like this, "1226" I need to create a date string from that data.

so far I can get the month and year. tried using time.Parse method was mentioned in the docs but I couldn't figure it out.

func main() {

    dateData := "1226"
    month := dateData[:2]
    year := dateData[2:]
    t, _ := time.Parse("2006-01-02", fmt.Sprintf("20%s-%s-00", year, month))
    fmt.Println(t)
    // expected output is "2026-12-01", and also it's better if we could add one month to this one. then it will become "2027-01-01"

}

CodePudding user response:

I am receiving the expiry date as a four-letter string like this, "1226"


expected output is "2026-12-01

package main

import (
    "fmt"
    "time"
)

func main() {
    date := "1226"
    if len(date) == 4 {
        date = date[0:2]   "20"   date[2:4]
    }
    t, err := time.Parse("012006", date)
    fmt.Println(t, err)
}

https://go.dev/play/p/fwfBux1AZQO

2026-12-01 00:00:00  0000 UTC <nil>

it's better if we could add one month to this one. then it will become "2027-01-01"

package main

import (
    "fmt"
    "time"
)

func main() {
    date := "1226"
    if len(date) == 4 {
        date = date[0:2]   "20"   date[2:4]
    }
    t, err := time.Parse("012006", date)
    if err == nil {
        t = t.AddDate(0, 1, 0)
    }
    fmt.Println(t, err)
}

https://go.dev/play/p/xCAyxPdRjib

2027-01-01 00:00:00  0000 UTC <nil>

CodePudding user response:

Does this work for you?

https://go.dev/play/p/hrwVa_CvGYL


func DateStringFromTime(t time.Time) string {
    return (strings.Split(fmt.Sprint(t), " "))[0]
}

func TimeFromMMYY(dateData string) (time.Time, error) {

    t := time.Time{}

    if len(dateData) != 4 {
        return t, errors.New("bad date string")
    }

    month := dateData[:2]
    year := dateData[2:]
    m, err := strconv.Atoi(month)
    if err != nil {
        return t, err
    }

    y, err := strconv.Atoi(year)
    if err != nil {
        return t, err
    }

    loc := time.UTC // or time.Local
    t = time.Date(2000 y, time.Month(m), 1, 0, 0, 0, 0, loc)

    return t, nil
}
func main() {

    dateData := "1226"

    t, _ := TimeFromMMYY(dateData)

    fmt.Println(DateStringFromTime(t)) // prints 2026-12-01

    // add a month
    t = t.AddDate(0, 1, 0)
    fmt.Println(DateStringFromTime(t)) // prints 2027-01-01
}
  •  Tags:  
  • go
  • Related