Computer scienceProgramming languagesGolangPackages and modulesStandard libraryTime package

Parsing and formatting time

Parsing module

Report a typo

You work in a development team. The front-end developer creates a registration form and goes on vacation. Unfortunately, the form has a mistake with the date of birth field. It's just a text field without input format. And now, new users have various layouts of dates saved in the database.

You need to fix this! You might get the date inputs from users in one of the following ways:

  • year.month.day
  • year-month-day
  • year/month/day

Take notice that the date input can also contain errors! You need to print the date in the correct layout: year/month/day; To do this, you can use the CorrectFormat constant.

Finally, if the date input has an error, print the message: Date format is invalid.

Sample Input 1:

1995.05.12

Sample Output 1:

1995/05/12
Write a program in Go
package main

import (
"fmt"
"time"
)

const CorrectFormat = "2006/01/02"

func main() {
var inputDate string
fmt.Scan(&inputDate)

if outputDate, err := time.Parse("2006.01.02", inputDate); err == nil {
fmt.Println(outputDate.Format(CorrectFormat))
} else if outputDate, err := time.Parse(?, inputDate); err == nil {
fmt.Println(outputDate.Format(?))
} else if outputDate, err := time.Parse("2006/01/02", ?); err == nil {
fmt.Println(outputDate.Format(?))
} else {
fmt.Println("Date format is invalid")
}
}
___

Create a free account to access the full topic