|
| 1 | +package utils |
| 2 | + |
| 3 | +import "time" |
| 4 | + |
| 5 | +const ( |
| 6 | + // DateTimeLayout is the layout string for datetime format. |
| 7 | + DateTimeLayout = "2006-01-02 15:04:05" |
| 8 | + |
| 9 | + // DateTimeLayoutWithMS is the layout string for datetime format with milliseconds. |
| 10 | + DateTimeLayoutWithMS = "2006-01-02 15:04:05.000" |
| 11 | + |
| 12 | + // DateTimeLayoutWithMSAndTZ is the layout string for datetime format with milliseconds and timezone. |
| 13 | + DateTimeLayoutWithMSAndTZ = "2006-01-02T15:04:05.000Z" |
| 14 | + |
| 15 | + // TimeLayout is the layout string for time format. |
| 16 | + TimeLayout = "15:04:05" |
| 17 | + |
| 18 | + // DateLayout is the layout string for date format. |
| 19 | + DateLayout = "2006-01-02" |
| 20 | +) |
| 21 | + |
| 22 | +// FormatDateTime formats the given time to string |
| 23 | +func FormatDateTime(t time.Time, format string) string { |
| 24 | + switch format { |
| 25 | + case DateTimeLayoutWithMS: |
| 26 | + return t.Format(DateTimeLayoutWithMS) |
| 27 | + case DateTimeLayoutWithMSAndTZ: |
| 28 | + return t.UTC().Format(DateTimeLayoutWithMSAndTZ) |
| 29 | + case TimeLayout: |
| 30 | + return t.Format(TimeLayout) |
| 31 | + case DateLayout: |
| 32 | + return t.Format(DateLayout) |
| 33 | + default: |
| 34 | + return t.Format(DateTimeLayout) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +// ParseDateTime parses the given string to time |
| 39 | +func ParseDateTime(s string, format string) (time.Time, error) { |
| 40 | + switch format { |
| 41 | + case DateTimeLayoutWithMS: |
| 42 | + return time.Parse(DateTimeLayoutWithMS, s) |
| 43 | + case DateTimeLayoutWithMSAndTZ: |
| 44 | + return time.Parse(DateTimeLayoutWithMSAndTZ, s) |
| 45 | + case TimeLayout: |
| 46 | + return time.Parse(TimeLayout, s) |
| 47 | + case DateLayout: |
| 48 | + return time.Parse(DateLayout, s) |
| 49 | + default: |
| 50 | + return time.Parse(DateTimeLayout, s) |
| 51 | + } |
| 52 | +} |
0 commit comments