Skip to content

proposal: time: a better way to validate a time instance #66029

@amarjeetanandsingh

Description

@amarjeetanandsingh

Proposal Details

With current time pkg api, what is a good way to validate if a given input date is valid or not?

Suppose a scenario we have given three ints 2021, 02 and 29, for year,month,day and need to validate if it represents a valid date or not.

This can be achieved by writing a small helper function like

func isValidDate(year, month, day int) bool {
	t := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.UTC)
	y, m, d := t.Date()

	return y == year && m == time.Month(month) && d == day
}

Or maybe another way could be -

func isValidDate(year, month, day int) bool {
	dateStr := fmt.Sprintf("%d-%d-%d", year, month, day)
	_, err := time.Parse("2006-1-2", dateStr)
	return err == nil
}

What approach would u recommend for this? Or is this use case worthy enough to be added in the time pkg?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions