Web Go 日期时间示例
Web Go 日期时间示例,包括获取当前时间、格式化、解析和时区操作
💻 获取当前时间 go
🟢 simple
⭐⭐
使用Go time包获取当前系统时间和日期,具有各种精度级别
⏱️ 20 min
🏷️ go, web, datetime, time
Prerequisites:
Basic Go, time package
// Web Go Get Current Time Examples
// Getting current system time and date with various precision
package main
import (
"fmt"
"time"
)
// 1. Basic Current Time
// GetCurrentTime gets current date and time
func GetCurrentTime() time.Time {
return time.Now()
}
// GetCurrentDate gets current date only
func GetCurrentDate() time.Time {
now := time.Now()
return time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
}
// GetCurrentTimeOnly gets current time only
func GetCurrentTimeOnly() time.Time {
now := time.Now()
return time.Date(0, 1, 1, now.Hour(), now.Minute(), now.Second(), now.Nanosecond(), time.UTC)
}
// GetUnixTimestamp gets current Unix timestamp
func GetUnixTimestamp() int64 {
return time.Now().Unix()
}
// GetUnixTimestampMillis gets current Unix timestamp in milliseconds
func GetUnixTimestampMillis() int64 {
return time.Now().UnixMilli()
}
// GetUnixTimestampNanos gets current Unix timestamp in nanoseconds
func GetUnixTimestampNanos() int64 {
return time.Now().UnixNano()
}
// 2. Time with Timezone
// GetUTC gets current UTC time
func GetUTC() time.Time {
return time.Now().UTC()
}
// GetLocal gets current local time
func GetLocal() time.Time {
return time.Now()
}
// GetLocationByName gets time in specific location
func GetLocationByName(location string) (time.Time, error) {
loc, err := time.LoadLocation(location)
if err != nil {
return time.Time{}, err
}
return time.Now().In(loc), nil
}
// GetTimezoneOffset gets timezone offset in seconds
func GetTimezoneOffset() int {
_, offset := time.Now().Zone()
return offset
}
// GetTimezoneName gets timezone name
func GetTimezoneName() string {
_, name := time.Now().Zone()
return name
}
// 3. High Precision Time
// GetPrecisionTime gets time with high precision
func GetPrecisionTime() time.Time {
return time.Now()
}
// GetMonotonicTime gets monotonic time (cannot go backwards)
func GetMonotonicTime() time.Duration {
start := time.Now()
// Simulate some work
return time.Since(start)
}
// 4. Time Components
// GetCurrentYear gets current year
func GetCurrentYear() int {
return time.Now().Year()
}
// GetCurrentMonth gets current month (1-12)
func GetCurrentMonth() time.Month {
return time.Now().Month()
}
// GetCurrentDay gets current day of month (1-31)
func GetCurrentDay() int {
return time.Now().Day()
}
// GetCurrentHour gets current hour (0-23)
func GetCurrentHour() int {
return time.Now().Hour()
}
// GetCurrentMinute gets current minute (0-59)
func GetCurrentMinute() int {
return time.Now().Minute()
}
// GetCurrentSecond gets current second (0-59)
func GetCurrentSecond() int {
return time.Now().Second()
}
// GetCurrentNanosecond gets current nanosecond (0-999999999)
func GetCurrentNanosecond() int {
return time.Now().Nanosecond()
}
// GetTimeComponents gets all time components as map
func GetTimeComponents() map[string]interface{} {
now := time.Now()
return map[string]interface{}{
"year": now.Year(),
"month": int(now.Month()),
"day": now.Day(),
"hour": now.Hour(),
"minute": now.Minute(),
"second": now.Second(),
"nanosecond": now.Nanosecond(),
"weekday": int(now.Weekday()),
}
}
// 5. Week and Day Information
// GetCurrentWeekday gets current weekday (0=Sunday, 6=Saturday)
func GetCurrentWeekday() time.Weekday {
return time.Now().Weekday()
}
// GetCurrentISOWeekday gets current ISO weekday (1=Monday, 7=Sunday)
func GetCurrentISOWeekday() int {
wd := time.Now().Weekday()
if wd == time.Sunday {
return 7
}
return int(wd)
}
// GetWeekOfYear gets current week of year
func GetWeekOfYear() int {
_, week := time.Now().ISOWeek()
return week
}
// GetYearOfWeek gets ISO year
func GetYearOfWeek() int {
year, _ := time.Now().ISOWeek()
return year
}
// GetDayOfYear gets current day of year
func GetDayOfYear() int {
now := time.Now()
startOfYear := time.Date(now.Year(), 1, 1, 0, 0, 0, 0, now.Location())
return int(now.Sub(startOfYear).Hours()/24) + 1
}
// GetWeekdayName gets current weekday name
func GetWeekdayName() string {
return time.Now().Weekday().String()
}
// GetMonthName gets current month name
func GetMonthName() string {
return time.Now().Month().String()
}
// 6. Time Strings
// GetTimeString gets current time as string
func GetTimeString() string {
now := time.Now()
return fmt.Sprintf("%02d:%02d:%02d", now.Hour(), now.Minute(), now.Second())
}
// GetDateString gets current date as string
func GetDateString() string {
now := time.Now()
return fmt.Sprintf("%04d-%02d-%02d", now.Year(), now.Month(), now.Day())
}
// GetDateTimeString gets current datetime as string
func GetDateTimeString() string {
now := time.Now()
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d",
now.Year(), now.Month(), now.Day(),
now.Hour(), now.Minute(), now.Second())
}
// GetISO8601 gets ISO 8601 formatted time
func GetISO8601() string {
return time.Now().Format(time.RFC3339)
}
// GetRFC1123 gets RFC 1123 formatted time
func GetRFC1123() string {
return time.Now().Format(time.RFC1123)
}
// 7. Relative Time
// GetTimeSinceEpoch gets seconds since Unix epoch
func GetTimeSinceEpoch() float64 {
return float64(time.Now().UnixNano()) / 1e9
}
// GetTimeUntilMidnight gets seconds until midnight
func GetTimeUntilMidnight() float64 {
now := time.Now()
midnight := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location())
return midnight.Sub(now).Seconds()
}
// GetTimeSinceMidnight gets seconds since midnight
func GetTimeSinceMidnight() float64 {
now := time.Now()
midnight := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
return now.Sub(midnight).Seconds()
}
// GetDaysInMonth gets number of days in current month
func GetDaysInMonth() int {
now := time.Now()
firstDay := time.Date(now.Year(), now.Month(), 1, 0, 0, 0, 0, time.UTC)
lastDay := firstDay.AddDate(0, 1, -1)
return lastDay.Day()
}
// IsLeapYear checks if current year is leap year
func IsLeapYear() bool {
year := time.Now().Year()
if year%4 != 0 {
return false
} else if year%100 != 0 {
return true
} else {
return year%400 == 0
}
}
// IsLeapYearFor checks if given year is leap year
func IsLeapYearFor(year int) bool {
if year%4 != 0 {
return false
} else if year%100 != 0 {
return true
} else {
return year%400 == 0
}
}
// 8. Time Measurements
// StartMeasurement starts time measurement
func StartMeasurement() time.Time {
return time.Now()
}
// EndMeasurement ends time measurement and returns duration
func EndMeasurement(start time.Time) time.Duration {
return time.Since(start)
}
// MeasureFunction measures function execution time
func MeasureFunction(fn func()) time.Duration {
start := time.Now()
fn()
return time.Since(start)
}
// 9. Multiple Time Representations
// GetAllTimeFormats gets time in all common formats
func GetAllTimeFormats() map[string]interface{} {
now := time.Now()
return map[string]interface{}{
"unix": now.Unix(),
"unix_millis": now.UnixMilli(),
"unix_nanos": now.UnixNano(),
"iso8601": now.Format(time.RFC3339),
"rfc1123": now.Format(time.RFC1123),
"rfc3339": now.Format(time.RFC3339),
"date": GetDateString(),
"time": GetTimeString(),
"datetime": GetDateTimeString(),
"year": now.Year(),
"month": int(now.Month()),
"day": now.Day(),
"hour": now.Hour(),
"minute": now.Minute(),
"second": now.Second(),
}
}
// 10. Time Arithmetic
// AddDays adds days to current time
func AddDays(days int) time.Time {
return time.Now().AddDate(0, 0, days)
}
// AddMonths adds months to current time
func AddMonths(months int) time.Time {
return time.Now().AddDate(0, months, 0)
}
// AddYears adds years to current time
func AddYears(years int) time.Time {
return time.Now().AddDate(years, 0, 0)
}
// AddHours adds hours to current time
func AddHours(hours float64) time.Time {
return time.Now().Add(time.Duration(hours) * time.Hour)
}
// AddMinutes adds minutes to current time
func AddMinutes(minutes float64) time.Time {
return time.Now().Add(time.Duration(minutes) * time.Minute)
}
// AddSeconds adds seconds to current time
func AddSeconds(seconds float64) time.Time {
return time.Now().Add(time.Duration(seconds) * time.Second)
}
// 11. Time Comparison
// IsBefore checks if current time is before given time
func IsBefore(t time.Time) bool {
return time.Now().Before(t)
}
// IsAfter checks if current time is after given time
func IsAfter(t time.Time) bool {
return time.Now().After(t)
}
// IsBetween checks if current time is between start and end
func IsBetween(start, end time.Time) bool {
now := time.Now()
return now.After(start) && now.Before(end)
}
// Usage Examples
func main() {
fmt.Println("=== Web Go Get Current Time Examples ===
")
// 1. Basic time
fmt.Println("--- 1. Basic Current Time ---")
fmt.Printf("Current datetime: %v
", GetCurrentTime())
fmt.Printf("Current date: %v
", GetCurrentDate())
fmt.Printf("Unix timestamp: %d
", GetUnixTimestamp())
fmt.Printf("Timestamp (ms): %d
", GetUnixTimestampMillis())
// 2. Timezone
fmt.Println("
--- 2. Timezone Information ---")
fmt.Printf("UTC: %v
", GetUTC())
fmt.Printf("Local: %v
", GetLocal())
fmt.Printf("Timezone offset: %d seconds
", GetTimezoneOffset())
fmt.Printf("Timezone name: %s
", GetTimezoneName())
// 3. Components
fmt.Println("
--- 3. Time Components ---")
fmt.Printf("Components: %v
", GetTimeComponents())
// 4. Week/Day info
fmt.Println("
--- 4. Week and Day Information ---")
fmt.Printf("Weekday: %s
", GetWeekdayName())
fmt.Printf("Month: %s
", GetMonthName())
fmt.Printf("Week of year: %d
", GetWeekOfYear())
fmt.Printf("Day of year: %d
", GetDayOfYear())
// 5. String formats
fmt.Println("
--- 5. String Formats ---")
fmt.Printf("Time: %s
", GetTimeString())
fmt.Printf("Date: %s
", GetDateString())
fmt.Printf("DateTime: %s
", GetDateTimeString())
fmt.Printf("ISO8601: %s
", GetISO8601())
fmt.Printf("RFC1123: %s
", GetRFC1123())
// 6. Relative time
fmt.Println("
--- 6. Relative Time ---")
fmt.Printf("Until midnight: %.0f seconds
", GetTimeUntilMidnight())
fmt.Printf("Since midnight: %.0f seconds
", GetTimeSinceMidnight())
fmt.Printf("Days in month: %d
", GetDaysInMonth())
fmt.Printf("Is leap year: %t
", IsLeapYear())
// 7. Time measurement
fmt.Println("
--- 7. Time Measurement ---")
start := StartMeasurement()
time.Sleep(100 * time.Millisecond)
elapsed := EndMeasurement(start)
fmt.Printf("Elapsed: %v
", elapsed)
// 8. All formats
fmt.Println("
--- 8. All Formats ---")
formats := GetAllTimeFormats()
for key, value := range formats {
fmt.Printf("%s: %v
", key, value)
}
// 9. Time arithmetic
fmt.Println("
--- 9. Time Arithmetic ---")
fmt.Printf("Tomorrow: %v
", AddDays(1))
fmt.Printf("Next month: %v
", AddMonths(1))
fmt.Printf("Next year: %v
", AddYears(1))
fmt.Printf("In 24 hours: %v
", AddHours(24))
// 10. Location
fmt.Println("
--- 10. Time in Different Locations ---")
if ny, err := GetLocationByName("America/New_York"); err == nil {
fmt.Printf("New York: %v
", ny)
}
if london, err := GetLocationByName("Europe/London"); err == nil {
fmt.Printf("London: %v
", london)
}
if tokyo, err := GetLocationByName("Asia/Tokyo"); err == nil {
fmt.Printf("Tokyo: %v
", tokyo)
}
fmt.Println("
=== All Get Current Time Examples Completed ===")
}
💻 时间格式化 go
🟡 intermediate
⭐⭐⭐
使用各种格式代码和自定义模式将time.Time对象格式化为字符串
⏱️ 25 min
🏷️ go, web, datetime, formatting
Prerequisites:
Intermediate Go, time package, format layouts
// Web Go Time Formatting Examples
// Converting time.Time objects to formatted strings
package main
import (
"fmt"
"time"
)
// 1. Standard Format Codes
// FormatYear formats year in various ways
func FormatYear(t time.Time) map[string]string {
return map[string]string{
"full": fmt.Sprintf("%04d", t.Year()),
"short": fmt.Sprintf("%02d", t.Year()%100),
}
}
// FormatMonth formats month in various ways
func FormatMonth(t time.Time) map[string]string {
return map[string]string{
"numeric": fmt.Sprintf("%02d", t.Month()),
"name": t.Month().String(),
"name_short": t.Format("Jan"),
"numeric_zero": fmt.Sprintf("%d", t.Month()),
}
}
// FormatDay formats day in various ways
func FormatDay(t time.Time) map[string]string {
return map[string]string{
"numeric": fmt.Sprintf("%02d", t.Day()),
"with_ordinal": fmt.Sprintf("%d%s", t.Day(),
getOrdinal(t.Day())),
"name": t.Weekday().String(),
"name_short": t.Format("Mon"),
}
}
func getOrdinal(day int) string {
switch day {
case 1, 21, 31:
return "st"
case 2, 22:
return "nd"
case 3, 23:
return "rd"
default:
return "th"
}
}
// FormatTime formats time in various ways
func FormatTime(t time.Time) map[string]string {
return map[string]string{
"24h": fmt.Sprintf("%02d:%02d:%02d", t.Hour(), t.Minute(), t.Second()),
"12h": t.Format("03:04:05 PM"),
"24h_short": fmt.Sprintf("%02d:%02d", t.Hour(), t.Minute()),
"12h_short": t.Format("03:04 PM"),
"hour_24": fmt.Sprintf("%02d", t.Hour()),
"hour_12": t.Format("3"),
"minute": fmt.Sprintf("%02d", t.Minute()),
"second": fmt.Sprintf("%02d", t.Second()),
"period": t.Format("PM"),
}
}
// 2. Common Date Formats
// FormatISO8601 formats as ISO 8601
func FormatISO8601(t time.Time) string {
return t.Format(time.RFC3339)
}
// FormatRFC1123 formats as RFC 1123
func FormatRFC1123(t time.Time) string {
return t.Format(time.RFC1123)
}
// FormatRFC3339 formats as RFC 3339
func FormatRFC3339(t time.Time) string {
return t.Format(time.RFC3339)
}
// FormatRFC822 formats as RFC 822
func FormatRFC822(t time.Time) string {
return t.Format(time.RFC822)
}
// FormatANSIC formats as ANSIC
func FormatANSIC(t time.Time) string {
return t.Format(time.ANSIC)
}
// FormatUnixDate formats as Unix date
func FormatUnixDate(t time.Time) string {
return t.Format(time.UnixDate)
}
// 3. Regional Formats
// FormatUSDate formats as US date (MM/DD/YYYY)
func FormatUSDate(t time.Time) string {
return fmt.Sprintf("%02d/%02d/%04d", t.Month(), t.Day(), t.Year())
}
// FormatEUDate formats as European date (DD/MM/YYYY)
func FormatEUDate(t time.Time) string {
return fmt.Sprintf("%02d/%02d/%04d", t.Day(), t.Month(), t.Year())
}
// FormatISODate formats as ISO date (YYYY-MM-DD)
func FormatISODate(t time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d", t.Year(), t.Month(), t.Day())
}
// FormatChineseDate formats as Chinese date (YYYY年MM月DD日)
func FormatChineseDate(t time.Time) string {
return fmt.Sprintf("%04d年%02d月%02d日", t.Year(), t.Month(), t.Day())
}
// FormatJapaneseDate formats as Japanese date (YYYY年MM月DD日)
func FormatJapaneseDate(t time.Time) string {
return fmt.Sprintf("%04d年%02d月%02d日", t.Year(), t.Month(), t.Day())
}
// FormatKoreanDate formats as Korean date (YYYY년 MM월 DD일)
func FormatKoreanDate(t time.Time) string {
return fmt.Sprintf("%04d년 %02d월 %02d일", t.Year(), t.Month(), t.Day())
}
// 4. Custom Formats
// FormatReadable formats in human-readable form
func FormatReadable(t time.Time) string {
return fmt.Sprintf("%s, %s %d, %s at %02d:%02d %s",
t.Weekday(),
t.Month(),
t.Day(),
t.Year(),
t.Hour()%12,
t.Minute(),
getAMPM(t))
}
func getAMPM(t time.Time) string {
if t.Hour() < 12 {
return "AM"
}
return "PM"
}
// FormatCompact formats in compact form
func FormatCompact(t time.Time) string {
return fmt.Sprintf("%04d%02d%02d_%02d%02d%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
}
// FormatWithTimezone formats with timezone info
func FormatWithTimezone(t time.Time) string {
return fmt.Sprintf("%04d-%02d-%02d %02d:%02d:%02d %s",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second(),
t.Format("MST"))
}
// FormatFriendly formats in friendly relative form
func FormatFriendly(t time.Time) string {
now := time.Now()
diff := now.Sub(t)
if diff < time.Minute {
return "just now"
} else if diff < time.Hour {
minutes := int(diff.Minutes())
if minutes == 1 {
return "1 minute ago"
}
return fmt.Sprintf("%d minutes ago", minutes)
} else if diff < 24*time.Hour {
hours := int(diff.Hours())
if hours == 1 {
return "1 hour ago"
}
return fmt.Sprintf("%d hours ago", hours)
} else if diff < 30*24*time.Hour {
days := int(diff.Hours() / 24)
if days == 1 {
return "1 day ago"
}
return fmt.Sprintf("%d days ago", days)
} else {
return FormatISODate(t)
}
}
// 5. Duration Formatting
// FormatDuration formats duration in human-readable form
func FormatDuration(d time.Duration) string {
hours := int(d.Hours())
minutes := int(d.Minutes()) % 60
seconds := int(d.Seconds()) % 60
if hours > 0 {
return fmt.Sprintf("%dh %dm %ds", hours, minutes, seconds)
} else if minutes > 0 {
return fmt.Sprintf("%dm %ds", minutes, seconds)
} else {
return fmt.Sprintf("%ds", seconds)
}
}
// FormatDurationPrecise formats duration with milliseconds
func FormatDurationPrecise(d time.Duration) string {
hours := int(d.Hours())
minutes := int(d.Minutes()) % 60
seconds := int(d.Seconds()) % 60
millis := d.Milliseconds() % 1000
if hours > 0 {
return fmt.Sprintf("%dh %dm %ds %dms", hours, minutes, seconds, millis)
} else if minutes > 0 {
return fmt.Sprintf("%dm %ds %dms", minutes, seconds, millis)
} else {
return fmt.Sprintf("%ds %dms", seconds, millis)
}
}
// 6. Relative Formatting
// FormatRelativeToNow formats datetime relative to now
func FormatRelativeToNow(t time.Time) string {
now := time.Now()
var diff time.Duration
var suffix string
if t.After(now) {
diff = t.Sub(now)
suffix = "from now"
} else {
diff = now.Sub(t)
suffix = "ago"
}
if diff < time.Minute {
seconds := int(diff.Seconds())
if seconds == 1 {
return fmt.Sprintf("1 second %s", suffix)
}
return fmt.Sprintf("%d seconds %s", seconds, suffix)
} else if diff < time.Hour {
minutes := int(diff.Minutes())
if minutes == 1 {
return fmt.Sprintf("1 minute %s", suffix)
}
return fmt.Sprintf("%d minutes %s", minutes, suffix)
} else if diff < 24*time.Hour {
hours := int(diff.Hours())
if hours == 1 {
return fmt.Sprintf("1 hour %s", suffix)
}
return fmt.Sprintf("%d hours %s", hours, suffix)
} else if diff < 30*24*time.Hour {
days := int(diff.Hours() / 24)
if days == 1 {
return fmt.Sprintf("1 day %s", suffix)
}
return fmt.Sprintf("%d days %s", days, suffix)
} else if diff < 365*24*time.Hour {
months := int(diff.Hours() / (24 * 30))
if months == 1 {
return fmt.Sprintf("1 month %s", suffix)
}
return fmt.Sprintf("%d months %s", months, suffix)
} else {
years := int(diff.Hours() / (24 * 365))
if years == 1 {
return fmt.Sprintf("1 year %s", suffix)
}
return fmt.Sprintf("%d years %s", years, suffix)
}
}
// 7. Business Date Formats
// FormatQuarter formats as quarter
func FormatQuarter(t time.Time) string {
quarter := (t.Month()-1)/3 + 1
return fmt.Sprintf("Q%d %d", quarter, t.Year())
}
// FormatWeekNumber formats with week number
func FormatWeekNumber(t time.Time) string {
year, week := t.ISOWeek()
return fmt.Sprintf("%d-W%02d", year, week)
}
// FormatDayOfYear formats with day of year
func FormatDayOfYear(t time.Time) string {
startOfYear := time.Date(t.Year(), 1, 1, 0, 0, 0, 0, t.Location())
dayOfYear := int(t.Sub(startOfYear).Hours()/24) + 1
return fmt.Sprintf("%d-%03d", t.Year(), dayOfYear)
}
// FormatSemester formats as semester
func FormatSemester(t time.Time) string {
semester := 1
if t.Month() >= 7 {
semester = 2
}
return fmt.Sprintf("S%d %d", semester, t.Year())
}
// 8. Custom Pattern Formatting
// FormatWithPattern formats with custom pattern
func FormatWithPattern(t time.Time, pattern string) string {
// Simple pattern replacement
result := pattern
result = fmt.Sprintf(result, t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
return result
}
// FormatDateTime formats datetime with custom format
func FormatDateTime(t time.Time, format string) string {
// Common format placeholders
layouts := map[string]string{
"YYYY-MM-DD": "2006-01-02",
"DD/MM/YYYY": "02/01/2006",
"MM/DD/YYYY": "01/02/2006",
"YYYY-MM-DD HH:MM:SS": "2006-01-02 15:04:05",
"HH:MM": "15:04",
"HH:MM:SS": "15:04:05",
}
if layout, ok := layouts[format]; ok {
return t.Format(layout)
}
return t.Format(format)
}
// 9. Format Codes Reference
// GetAllFormatCodes gets all format codes with examples
func GetAllFormatCodes() map[string]string {
t := time.Date(2025, 12, 31, 14, 30, 45, 0, time.UTC)
return map[string]string{
"ANSIC": t.Format(time.ANSIC),
"UnixDate": t.Format(time.UnixDate),
"RubyDate": t.Format(time.RubyDate),
"RFC822": t.Format(time.RFC822),
"RFC822Z": t.Format(time.RFC822Z),
"RFC850": t.Format(time.RFC850),
"RFC1123": t.Format(time.RFC1123),
"RFC1123Z": t.Format(time.RFC1123Z),
"RFC3339": t.Format(time.RFC3339),
"RFC3339Nano": t.Format(time.RFC3339Nano),
"Kitchen": t.Format(time.Kitchen),
"Stamp": t.Format(time.Stamp),
"StampMilli": t.Format(time.StampMilli),
"StampMicro": t.Format(time.StampMicro),
"StampNano": t.Format(time.StampNano),
}
}
// 10. Special Formats
// FormatLog formats for logging
func FormatLog(t time.Time) string {
return t.Format("2006-01-02 15:04:05.000")
}
// FormatFileSafe formats for filenames
func FormatFileSafe(t time.Time) string {
return fmt.Sprintf("%04d%02d%02d_%02d%02d%02d",
t.Year(), t.Month(), t.Day(),
t.Hour(), t.Minute(), t.Second())
}
// FormatHTTP formats for HTTP headers
func FormatHTTP(t time.Time) string {
return t.Format(time.RFC1123)
}
// Usage Examples
func main() {
fmt.Println("=== Web Go Time Formatting Examples ===
")
now := time.Now()
// 1. Standard formats
fmt.Println("--- 1. Standard Format Codes ---")
fmt.Printf("Month: %v
", FormatMonth(now))
fmt.Printf("Day: %v
", FormatDay(now))
fmt.Printf("Time: %v
", FormatTime(now))
// 2. Common formats
fmt.Println("
--- 2. Common Date Formats ---")
fmt.Printf("ISO 8601: %s
", FormatISO8601(now))
fmt.Printf("RFC 1123: %s
", FormatRFC1123(now))
fmt.Printf("RFC 3339: %s
", FormatRFC3339(now))
// 3. Regional formats
fmt.Println("
--- 3. Regional Formats ---")
fmt.Printf("US: %s
", FormatUSDate(now))
fmt.Printf("EU: %s
", FormatEUDate(now))
fmt.Printf("ISO: %s
", FormatISODate(now))
fmt.Printf("Chinese: %s
", FormatChineseDate(now))
fmt.Printf("Japanese: %s
", FormatJapaneseDate(now))
// 4. Custom formats
fmt.Println("
--- 4. Custom Formats ---")
fmt.Printf("Readable: %s
", FormatReadable(now))
fmt.Printf("Compact: %s
", FormatCompact(now))
fmt.Printf("Friendly: %s
", FormatFriendly(now))
// 5. Duration formatting
fmt.Println("
--- 5. Duration Formatting ---")
fmt.Printf("1h 30m 45s: %s
", FormatDuration(time.Hour+30*time.Minute+45*time.Second))
fmt.Printf("Duration precise: %s
", FormatDurationPrecise(90*time.Minute+12345*time.Millisecond))
// 6. Relative formatting
fmt.Println("
--- 6. Relative Formatting ---")
future := now.Add(2 * time.Hour)
fmt.Printf("2 hours from now: %s
", FormatRelativeToNow(future))
past := now.Add(-24 * time.Hour)
fmt.Printf("1 day ago: %s
", FormatRelativeToNow(past))
// 7. Business formats
fmt.Println("
--- 7. Business Date Formats ---")
fmt.Printf("Quarter: %s
", FormatQuarter(now))
fmt.Printf("Week: %s
", FormatWeekNumber(now))
fmt.Printf("Day of year: %s
", FormatDayOfYear(now))
fmt.Printf("Semester: %s
", FormatSemester(now))
// 8. Format codes reference
fmt.Println("
--- 8. Format Codes Reference ---")
codes := GetAllFormatCodes()
for name, example := range codes {
fmt.Printf("%s: %s
", name, example)
}
// 9. Special formats
fmt.Println("
--- 9. Special Formats ---")
fmt.Printf("Log: %s
", FormatLog(now))
fmt.Printf("File safe: %s
", FormatFileSafe(now))
fmt.Printf("HTTP: %s
", FormatHTTP(now))
fmt.Println("
=== All Time Formatting Examples Completed ===")
}
💻 时间解析 go
🟡 intermediate
⭐⭐⭐
使用各种格式将字符串解析为time.Time对象并处理解析错误
⏱️ 25 min
🏷️ go, web, datetime, parsing
Prerequisites:
Intermediate Go, time package, parse layouts
// Web Go Time Parsing Examples
// Converting strings to time.Time objects with various formats
package main
import (
"fmt"
"strings"
"time"
)
// 1. Basic Parsing
// ParseISO8601 parses ISO 8601 format
func ParseISO8601(dateString string) (time.Time, error) {
return time.Parse(time.RFC3339, dateString)
}
// ParseRFC1123 parses RFC 1123 format
func ParseRFC1123(dateString string) (time.Time, error) {
return time.Parse(time.RFC1123, dateString)
}
// ParseRFC3339 parses RFC 3339 format
func ParseRFC3339(dateString string) (time.Time, error) {
return time.Parse(time.RFC3339, dateString)
}
// ParseCustomFormat parses using custom format
func ParseCustomFormat(dateString, layout string) (time.Time, error) {
return time.Parse(layout, dateString)
}
// 2. Common Format Parsing
// ParseUSDate parses US date (MM/DD/YYYY)
func ParseUSDate(dateString string) (time.Time, error) {
layouts := []string{
"01/02/2006",
"01/02/2006 15:04:05",
"01-02-2006",
"01-02-2006 15:04:05",
}
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse date: %s", dateString)
}
// ParseEUDate parses European date (DD/MM/YYYY)
func ParseEUDate(dateString string) (time.Time, error) {
layouts := []string{
"02/01/2006",
"02/01/2006 15:04:05",
"02-01-2006",
"02-01-2006 15:04:05",
}
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse date: %s", dateString)
}
// ParseISODate parses ISO date (YYYY-MM-DD)
func ParseISODate(dateString string) (time.Time, error) {
layouts := []string{
"2006-01-02",
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02T15:04:05Z",
"20060102",
}
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse date: %s", dateString)
}
// 3. Flexible Parsing
// ParseAuto auto-detects and parses format
func ParseAuto(dateString string) (time.Time, error) {
// Try common layouts in order
layouts := []string{
time.RFC3339,
time.RFC1123,
time.RFC822,
time.RFC850,
time.ANSIC,
time.UnixDate,
"2006-01-02 15:04:05",
"2006-01-02T15:04:05",
"2006-01-02",
"02/01/2006",
"01/02/2006",
"02.01.2006",
"01.02.2006",
"02 Jan 2006",
"02 January 2006",
"Jan 2, 2006",
"January 2, 2006",
"20060102",
"02/01/06",
"01/02/06",
}
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse date with any known format: %s", dateString)
}
// ParseAutoList parses and returns all possible interpretations
func ParseAutoList(dateString string) []time.Time {
var results []time.Time
layouts := []string{
time.RFC3339,
"2006-01-02 15:04:05",
"2006-01-02",
"02/01/2006",
"01/02/2006",
"02.01.2006",
"01.02.2006",
}
seen := make(map[string]bool)
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
key := t.String()
if !seen[key] {
seen[key] = true
results = append(results, t)
}
}
}
return results
}
// 4. Time Parsing
// ParseTime parses time string
func ParseTime(timeString string) (time.Time, error) {
layouts := []string{
"15:04:05",
"15:04",
"3:04:05 PM",
"3:04 PM",
"15:04:05.000",
"3:04:05.000 PM",
}
for _, layout := range layouts {
t, err := time.Parse(layout, timeString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("cannot parse time: %s", timeString)
}
// ParseTimestamp parses Unix timestamp
func ParseTimestamp(timestamp int64) time.Time {
return time.Unix(timestamp, 0)
}
// ParseTimestampMillis parses millisecond timestamp
func ParseTimestampMillis(timestamp int64) time.Time {
return time.Unix(timestamp/1000, (timestamp%1000)*1000000)
}
// ParseTimestampNanos parses nanosecond timestamp
func ParseTimestampNanos(timestamp int64) time.Time {
sec := timestamp / 1000000000
nsec := timestamp % 1000000000
return time.Unix(sec, nsec)
}
// 5. Relative Time Parsing
// ParseRelative parses relative time strings
func ParseRelative(relativeString string) (time.Time, error) {
now := time.Now()
lower := strings.ToLower(relativeString)
// Match patterns like "in 5 minutes", "2 hours ago", etc.
if strings.Contains(lower, "ago") {
// Past
if strings.Contains(lower, "second") {
return now, fmt.Errorf("use specific number")
} else if strings.Contains(lower, "minute") {
// Parse "X minutes ago"
var minutes int
fmt.Sscanf(relativeString, "%d", &minutes)
return now.Add(-time.Duration(minutes) * time.Minute), nil
} else if strings.Contains(lower, "hour") {
var hours int
fmt.Sscanf(relativeString, "%d", &hours)
return now.Add(-time.Duration(hours) * time.Hour), nil
} else if strings.Contains(lower, "day") {
var days int
fmt.Sscanf(relativeString, "%d", &days)
return now.AddDate(0, 0, -days), nil
}
} else if strings.Contains(lower, "in ") {
// Future
if strings.Contains(lower, "minute") {
var minutes int
fmt.Sscanf(relativeString, "in %d", &minutes)
return now.Add(time.Duration(minutes) * time.Minute), nil
} else if strings.Contains(lower, "hour") {
var hours int
fmt.Sscanf(relativeString, "in %d", &hours)
return now.Add(time.Duration(hours) * time.Hour), nil
} else if strings.Contains(lower, "day") {
var days int
fmt.Sscanf(relativeString, "in %d", &days)
return now.AddDate(0, 0, days), nil
}
}
return time.Time{}, fmt.Errorf("cannot parse relative time: %s", relativeString)
}
// 6. Multi-Format Parsing
// TryMultipleFormats tries multiple formats
func TryMultipleFormats(dateString string, layouts []string) (time.Time, error) {
for _, layout := range layouts {
t, err := time.Parse(layout, dateString)
if err == nil {
return t, nil
}
}
return time.Time{}, fmt.Errorf("none of the formats matched")
}
// 7. Parser with Fallback
// ParseWithFallback parses with fallback on failure
func ParseWithFallback(dateString string, fallback time.Time) time.Time {
t, err := ParseAuto(dateString)
if err != nil {
return fallback
}
return t
}
// 8. Validation
// IsValidDate validates date string against format
func IsValidDate(dateString, layout string) bool {
_, err := time.Parse(layout, dateString)
return err == nil
}
// GetDetectedFormat detects which format matches
func GetDetectedFormat(dateString string) string {
layouts := map[string]string{
"ISO 8601": "2006-01-02",
"US Date": "01/02/2006",
"EU Date": "02/01/2006",
"RFC 3339": time.RFC3339,
"RFC 1123": time.RFC1123,
"Custom Date": "02-Jan-2006",
}
for name, layout := range layouts {
if IsValidDate(dateString, layout) {
return name
}
}
return "Unknown"
}
// 9. Extract Date Parts
// ExtractDateParts extracts date parts using string manipulation
func ExtractDateParts(dateString string) map[string]int {
// Try ISO format first
var year, month, day int
if dateString[4] == '-' && dateString[7] == '-' {
fmt.Sscanf(dateString, "%d-%d-%d", &year, &month, &day)
return map[string]int{
"year": year,
"month": month,
"day": day,
}
}
// Try US format
if dateString[2] == '/' && dateString[5] == '/' {
fmt.Sscanf(dateString, "%d/%d/%d", &month, &day, &year)
return map[string]int{
"year": year,
"month": month,
"day": day,
}
}
// Try EU format
if dateString[2] == '/' && dateString[5] == '/' {
fmt.Sscanf(dateString, "%d/%d/%d", &day, &month, &year)
return map[string]int{
"year": year,
"month": month,
"day": day,
}
}
return nil
}
// 10. Specialized Parsers
// ParseHTTPDate parses HTTP date format
func ParseHTTPDate(dateString string) (time.Time, error) {
return time.Parse(time.RFC1123, dateString)
}
// ParseCookieDate parses cookie date format
func ParseCookieDate(dateString string) (time.Time, error) {
layouts := []string{
time.RFC1123,
"Monday, 02-Jan-2006 15:04:05 MST",
"Mon, 02-Jan-2006 15:04:05 MST",
}
return TryMultipleFormats(dateString, layouts)
}
// ParseEmailDate parses email date format
func ParseEmailDate(dateString string) (time.Time, error) {
return time.Parse(time.RFC1123, dateString)
}
// ParseLogFileDate parses log file timestamp
func ParseLogFileDate(dateString string) (time.Time, error) {
layouts := []string{
"2006/01/02 15:04:05",
"2006-01-02 15:04:05",
"2006.01.02 15:04:05",
"01/02/2006 15:04:05",
"02-Jan-06 15:04:05",
}
return TryMultipleFormats(dateString, layouts)
}
// 11. Locale-Specific Parsing
// ParseGermanDate parses German date format
func ParseGermanDate(dateString string) (time.Time, error) {
layouts := []string{
"02.01.2006",
"02.01.06",
"2.1.2006",
"2.1.06",
}
return TryMultipleFormats(dateString, layouts)
}
// ParseFrenchDate parses French date format
func ParseFrenchDate(dateString string) (time.Time, error) {
layouts := []string{
"02/01/2006",
"02-01-2006",
}
return TryMultipleFormats(dateString, layouts)
}
// ParseJapaneseDate parses Japanese date format
func ParseJapaneseDate(dateString string) (time.Time, error) {
layouts := []string{
"2006年01月02日",
"2006/01/02",
}
return TryMultipleFormats(dateString, layouts)
}
// Usage Examples
func main() {
fmt.Println("=== Web Go Time Parsing Examples ===
")
// 1. Basic parsing
fmt.Println("--- 1. Basic Parsing ---")
isoTime := "2025-12-31T14:30:45Z"
if t, err := ParseISO8601(isoTime); err == nil {
fmt.Printf("ISO 8601: %v
", t)
}
// 2. Common formats
fmt.Println("
--- 2. Common Format Parsing ---")
usDate := "12/31/2025"
if t, err := ParseUSDate(usDate); err == nil {
fmt.Printf("US date: %v
", t)
}
euDate := "31/12/2025"
if t, err := ParseEUDate(euDate); err == nil {
fmt.Printf("EU date: %v
", t)
}
isoDate := "2025-12-31"
if t, err := ParseISODate(isoDate); err == nil {
fmt.Printf("ISO date: %v
", t)
}
// 3. Auto-detect
fmt.Println("
--- 3. Auto-Detection ---")
testDates := []string{
"2025-12-31",
"31/12/2025",
"12/31/2025",
"Dec 31, 2025",
}
for _, date := range testDates {
if t, err := ParseAuto(date); err == nil {
fmt.Printf("'%s' -> %v
", date, t)
}
}
// 4. Time parsing
fmt.Println("
--- 4. Time Parsing ---")
times := []string{"14:30:45", "2:30 PM", "14:30"}
for _, t := range times {
if parsed, err := ParseTime(t); err == nil {
fmt.Printf("'%s' -> %v
", t, parsed)
}
}
// 5. Timestamp parsing
fmt.Println("
--- 5. Timestamp Parsing ---")
ts := int64(1735667445)
fmt.Printf("Timestamp %d: %v
", ts, ParseTimestamp(ts))
// 6. Format detection
fmt.Println("
--- 6. Format Detection ---")
fmt.Printf("Detected format for '2025-12-31': %s
", GetDetectedFormat("2025-12-31"))
fmt.Printf("Detected format for '12/31/2025': %s
", GetDetectedFormat("12/31/2025"))
// 7. Extract parts
fmt.Println("
--- 7. Extract Date Parts ---")
parts := ExtractDateParts("2025-12-31")
fmt.Printf("Parts: %v
", parts)
// 8. Multi-format parsing
fmt.Println("
--- 8. Try Multiple Formats ---")
layouts := []string{"2006-01-02", "02/01/2006", "01/02/2006"}
if t, err := TryMultipleFormats("2025-12-31", layouts); err == nil {
fmt.Printf("Parsed: %v
", t)
}
// 9. Locale-specific
fmt.Println("
--- 9. Locale-Specific Parsing ---")
german := "31.12.2025"
if t, err := ParseGermanDate(german); err == nil {
fmt.Printf("German: %v
", t)
}
japanese := "2025年12月31日"
if t, err := ParseJapaneseDate(japanese); err == nil {
fmt.Printf("Japanese: %v
", t)
}
// 10. Specialized formats
fmt.Println("
--- 10. Specialized Formats ---")
httpDate := "Wed, 31 Dec 2025 14:30:45 GMT"
if t, err := ParseHTTPDate(httpDate); err == nil {
fmt.Printf("HTTP date: %v
", t)
}
logDate := "2025/12/31 14:30:45"
if t, err := ParseLogFileDate(logDate); err == nil {
fmt.Printf("Log date: %v
", t)
}
fmt.Println("
=== All Time Parsing Examples Completed ===")
}