tpphu / golang-training

Golang for Backend Developer with Nordic Coder
https://nordiccoder.com/khoa-hoc/golang-for-backend-dev/
131 stars 50 forks source link

Thảo luận về parse chuỗi ngày tháng về kiểu dữ liệu time #6

Closed tpphu closed 5 years ago

tpphu commented 5 years ago

Cho các bạn một chuỗi sau Thứ Sáu, 15/3/2019, 11:11 hãy parse chuỗi này về kiểu dữ liệu time của Golang.

hiepndd commented 5 years ago

Hi anh @tpphu Em khong biet cach parse string co chua utf8 sang time, nen em nghi ra cach nay

func DateFormat(input string) interface{} {
    convertDate := map[string]string{
        "Thứ Hai":  "Mon",
        "Thứ Ba":   "Tue",
        "Thứ Tư":   "Web",
        "Thứ Năm":  "Thus",
        "Thứ Sáu":  "Fri",
        "Thứ Bảy":  "Sat",
        "Chủ Nhật": "Sun",
    }
    location, err := time.LoadLocation("Asia/Ho_Chi_Minh")
    if err != nil {
        fmt.Println("Opps: ", err)
        return nil
    }
    split := strings.Split(input, ",")
    split[0] = convertDate[split[0]]
    layout := "Mon 02-1-2006 03:04"
    time, err := time.ParseInLocation(layout, strings.Join(split, ""), location)
    if err != nil {
        fmt.Println("Opps: ", err)
        return nil
    }
    return time
}
func TestDateFormat(t *testing.T) {
    got := DateFormat("Thứ Sáu, 15-3-2019, 11:11")
    if _, ok := got.(time.Time); !ok {
        t.Errorf("want type 'time.Time' but got type '%T'", got)
    }
}
tpphu commented 5 years ago

Chỗ xử lý này hay @hiepndd rating 5* nha. Nhưng thật ra anh nghĩ, cho em convert cái thứ chỗ này không cần thiết, nên bỏ nó luôn, có ngày có giờ thì tự nó có thứ, và có ngày có giờ thì đã convert sang kiểu time được rồi. Em có nghĩ thế không?