0

I have a file with dates in the format dd.mm.yyyy (e.g. 31.12.2019). I want to transform into format yyyy-mm-dd (e.g. 2019-12-31).

In Notepad++ I can do a Search and Replace with these strings using back references:

Search:

(\d{2}).(\d{2}).(\d{4})

Replace:

\3-\2-\1

How would I do this with Go?

0

2 Answers 2

1

You could do it by slicing your input string, and assembling the parts in different order:

func transform(s string) string {
    d, m, y := s[:2], s[3:5], s[6:]
    return y + "-" + m + "-" + d
}

Note: the above function does not validate the input, it could panic if the input is shorter than 6 bytes.

If you need input validation (including date validation), you could use the time package to parse the date, and format it into your expected output:

func transform2(s string) (string, error) {
    t, err := time.Parse("02.01.2006", s)
    if err != nil {
        return "", err
    }
    return t.Format("2006-01-02"), nil
}

Testing the above functions:

fmt.Println(transform("31.12.2019"))
fmt.Println(transform2("31.12.2019"))

Output (try it on the Go Playground):

2019-12-31
2019-12-31 <nil>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, transform2 will probably do the job. The file structure is not so easy like: Bremen;Osterferien;2017;10.04.2017 - 22.04.2017 Bremen;Pfingstferien;2017;26.05.2017;06.06.2017 Bremen;Herbstferien;2017;02.10.2017 - 14.10.2017;30.10.2017 So I first have to capture all dates, then transform them and then write them back to the string with some replace method. Is this the correct strategy?
@Blockhuette You can split the lines using strings.Split(), and you'll have the date. Then you can use the trasformation presented here. You may also read / process the file as a CSV using encoding/csv, then you'll have the "cells" by reading the lines.
0

regex might be overkill since you have such well defined input. how about this:

  var dmy = strings.Split("31.12.2019",".")
  var mdy = []string{dmy[1],dmy[0],dmy[2]}
  fmt.Println(strings.Join(mdy, "-"))

https://play.golang.org/p/Ak3TlCAGHUv

1 Comment

var mdy = []string{dmy[2],dmy[1],dmy[0]} //suggestion

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.