Files

41 lines
1.1 KiB
Go

package timeconv
import (
"fmt"
"time"
)
// ToUTC converts a naive local datetime string to UTC using the user's timezone.
// The input format is "2006-01-02 15:04".
func ToUTC(localDatetime string, timezone string) (time.Time, error) {
loc, err := time.LoadLocation(timezone)
if err != nil {
return time.Time{}, fmt.Errorf("invalid timezone %q: %w", timezone, err)
}
t, err := time.ParseInLocation("2006-01-02 15:04", localDatetime, loc)
if err != nil {
return time.Time{}, fmt.Errorf("invalid local datetime %q: %w", localDatetime, err)
}
return t.UTC(), nil
}
// ToLocal converts a UTC timestamp to a naive local datetime string in the user's timezone.
// The output format is "2006-01-02 15:04".
func ToLocal(utc time.Time, timezone string) string {
loc, err := time.LoadLocation(timezone)
if err != nil {
return utc.UTC().Format("2006-01-02 15:04")
}
return utc.In(loc).Format("2006-01-02 15:04")
}
func CurrentLocalTime(timezone string) string {
loc, err := time.LoadLocation(timezone)
if err != nil {
loc = time.UTC
}
return time.Now().In(loc).Format("2006-01-02 15:04")
}