Example #1
0
func ExampleParse() {
	// longForm shows by example how the reference date would be
	// represented in the desired layout.
	const longForm = "Mon, January 2, 2006"
	d, _ := date.Parse(longForm, "Tue, February 3, 2013")
	fmt.Println(d)

	// shortForm is another way the reference date would be represented
	// in the desired layout.
	const shortForm = "2006-Jan-02"
	d, _ = date.Parse(shortForm, "2013-Feb-03")
	fmt.Println(d)

	// Output:
	// 2013-02-03
	// 2013-02-03
}
Example #2
0
func TestParse(t *testing.T) {
	// Test ability to parse a few common date formats
	cases := []struct {
		layout string
		value  string
		year   int
		month  time.Month
		day    int
	}{
		{date.ISO8601, "1969-12-31", 1969, time.December, 31},
		{date.ISO8601B, "19700101", 1970, time.January, 1},
		{date.RFC822, "29-Feb-00", 2000, time.February, 29},
		{date.RFC822W, "Mon, 01-Mar-04", 2004, time.March, 1},
		{date.RFC850, "Wednesday, 12-Aug-15", 2015, time.August, 12},
		{date.RFC1123, "05 Dec 1928", 1928, time.December, 5},
		{date.RFC1123W, "Mon, 05 Dec 1928", 1928, time.December, 5},
		{date.RFC3339, "2345-06-07", 2345, time.June, 7},
	}
	for _, c := range cases {
		d, err := date.Parse(c.layout, c.value)
		if err != nil {
			t.Errorf("Parse(%v) == %v", c.value, err)
		}
		year, month, day := d.Date()
		if year != c.year || month != c.month || day != c.day {
			t.Errorf("Parse(%v) == %v, want (%v, %v, %v)", c.value, d, c.year, c.month, c.day)
		}
	}

	// Test inability to parse ISO 8601 expanded year format
	badCases := []string{
		"+1234-05-06",
		"+12345-06-07",
		"-1234-05-06",
		"-12345-06-07",
	}
	for _, c := range badCases {
		d, err := date.Parse(date.ISO8601, c)
		if err == nil {
			t.Errorf("Parse(%v) == %v", c, d)
		}
	}
}