-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1507-ReformatDate.go
More file actions
83 lines (72 loc) · 2.59 KB
/
1507-ReformatDate.go
File metadata and controls
83 lines (72 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package main
// 1507. Reformat Date
// Given a date string in the form Day Month Year, where:
// Day is in the set {"1st", "2nd", "3rd", "4th", ..., "30th", "31st"}.
// Month is in the set {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}.
// Year is in the range [1900, 2100].
// Convert the date string to the format YYYY-MM-DD, where:
// YYYY denotes the 4 digit year.
// MM denotes the 2 digit month.
// DD denotes the 2 digit day.
// Example 1:
// Input: date = "20th Oct 2052"
// Output: "2052-10-20"
// Example 2:
// Input: date = "6th Jun 1933"
// Output: "1933-06-06"
// Example 3:
// Input: date = "26th May 1960"
// Output: "1960-05-26"
// Constraints:
// The given dates are guaranteed to be valid, so no error handling is necessary.
import "fmt"
import "strings"
func reformatDate(date string) string {
mm := map[string]string{
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06",
"Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12",
}
arr := strings.Split(date, " ")
proccessDay := func(d string) string {
arr := []rune{}
for _, v := range d {
if v >= '0' && v <= '9' {
arr = append(arr, v)
}
}
if len(arr) == 1 { // 1-9日的处理前面加 "0"
return fmt.Sprintf("0%v",string(arr))
}
return string(arr)
}
return fmt.Sprintf("%v-%v-%v", arr[2], mm[arr[1]], proccessDay(arr[0]))
}
func reformatDate1(date string) string {
mm := map[string]string{
"Jan": "01", "Feb": "02", "Mar": "03", "Apr": "04", "May": "05", "Jun": "06",
"Jul": "07", "Aug": "08", "Sep": "09", "Oct": "10", "Nov": "11", "Dec": "12",
}
arr := strings.Split(date, " ")
day, month, year := arr[0][:len(arr[0])-2], mm[arr[1]], arr[2]
if len(day) == 1 {
day = "0" + day
}
return year + "-" + month + "-" + day
}
func main() {
// Example 1:
// Input: date = "20th Oct 2052"
// Output: "2052-10-20"
fmt.Println(reformatDate("20th Oct 2052")) // "2052-10-20"
// Example 2:
// Input: date = "6th Jun 1933"
// Output: "1933-06-06"
fmt.Println(reformatDate("6th Jun 1933")) // "1933-06-06"
// Example 3:
// Input: date = "26th May 1960"
// Output: "1960-05-26"
fmt.Println(reformatDate("26th May 1960")) // "1960-05-26"
fmt.Println(reformatDate1("20th Oct 2052")) // "2052-10-20"
fmt.Println(reformatDate1("6th Jun 1933")) // "1933-06-06"
fmt.Println(reformatDate1("26th May 1960")) // "1960-05-26"
}