By default, env supports anything that implements the `TextUnmarshaler` interface, which includes `time.Time`. The upside is that depending on the format you need, you don't need to change anything. The downside is that if you do need time in another format, you'll need to create your own type and
()
| 209 | // The downside is that if you do need time in another format, you'll need to |
| 210 | // create your own type and implement `TextUnmarshaler`. |
| 211 | func ExampleParse_customTimeFormat() { |
| 212 | // type MyTime time.Time |
| 213 | // |
| 214 | // func (t *MyTime) UnmarshalText(text []byte) error { |
| 215 | // tt, err := time.Parse("2006-01-02", string(text)) |
| 216 | // *t = MyTime(tt) |
| 217 | // return err |
| 218 | // } |
| 219 | |
| 220 | type Config struct { |
| 221 | SomeTime MyTime `env:"SOME_TIME"` |
| 222 | } |
| 223 | os.Setenv("SOME_TIME", "2021-05-06") |
| 224 | var cfg Config |
| 225 | if err := Parse(&cfg); err != nil { |
| 226 | fmt.Println(err) |
| 227 | } |
| 228 | fmt.Print(cfg.SomeTime) |
| 229 | // Output: {0 63755856000 <nil>} |
| 230 | } |
| 231 | |
| 232 | // Parse using extra options. |
| 233 | func ExampleParseWithOptions_customTypes() { |