package apiTime import ( "encoding/json" "fmt" "log" "net/http" "strconv" "time" ) type dateTimeResponse struct { Year int `json:"year,omitempty"` Month int `json:"month,omitempty"` Day int `json:"day,omitempty"` Hour int `json:"hour,omitempty"` Minute int `json:"minute,omitempty"` Seconds int `json:"seconds,omitempty"` MilliSeconds int `json:"milliSeconds,omitempty"` DateTime string `json:"dateTime,omitempty"` Date string `json:"date,omitempty"` Time string `json:"time,omitempty"` TimeZone string `json:"timeZone,omitempty"` DayOfWeek string `json:"dayOfWeek,omitempty"` DstActive bool `json:"dstActive,omitempty"` } func TimeCurrentZone(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Language", "en") w.Header().Set("Content-Type", "application/json; charset=utf-8") timeZone := "" vals := r.URL.Query() parameters, ok := vals["timeZone"] if ok && len(parameters) == 1 { timeZone = parameters[0] } if timeZone == "" { w.WriteHeader(400) fmt.Fprint(w, "{\"error\": \"invalid value for timeZone\"}") return } loc, err := time.LoadLocation(timeZone) if err != nil { w.WriteHeader(400) fmt.Fprint(w, "{\"error\": \"invalid value for timeZone\"}") return } log.Printf("%q %q\n", loc.String(), r.RemoteAddr) w.WriteHeader(200) fmt.Fprint(w, getDateTimeResponseAsJSONString(loc)) } func getDateTimeResponse(loc *time.Location) dateTimeResponse { t := time.Now().In(loc) return dateTimeResponse{ Year: t.Year(), Month: int(t.Month()), Day: t.Day(), Hour: t.Hour(), Minute: t.Minute(), Seconds: t.Second(), MilliSeconds: func(i int64, err error) int { return int(i) }(strconv.ParseInt(strconv.Itoa(t.Nanosecond())[:3], 10, 0)), DateTime: t.Format(time.RFC3339), Date: fmt.Sprintf("%02d/%02d/%04d", t.Month(), t.Day(), t.Year()), Time: fmt.Sprintf("%02d:%02d", t.Hour(), t.Minute()), TimeZone: loc.String(), DayOfWeek: t.Weekday().String(), DstActive: t.IsDST(), } } func getDateTimeResponseAsJSONString(loc *time.Location) string { r, _ := json.Marshal(getDateTimeResponse(loc)) return string(r) }