Files
crawlab/core/utils/time.go
Marvin Zhang 3276083994 refactor: replace apex/log with structured logger across multiple services
- Replaced all instances of apex/log with a structured logger interface in various services, including Api, Server, Config, and others, to enhance logging consistency and context.
- Updated logging calls to utilize the new logger methods, improving error tracking and service monitoring.
- Added logger initialization in services and controllers to ensure proper logging setup.
- Improved error handling and logging messages for better clarity during service operations.
- Removed unused apex/log imports and cleaned up related code for better maintainability.
2024-12-24 19:11:19 +08:00

73 lines
1.7 KiB
Go

package utils
import (
"errors"
"github.com/crawlab-team/crawlab/trace"
"regexp"
"strconv"
"time"
)
func GetLocalTime(t time.Time) time.Time {
return t.In(time.Local)
}
func GetTimeString(t time.Time) string {
return t.Format("2006-01-02 15:04:05")
}
func GetLocalTimeString(t time.Time) string {
t = GetLocalTime(t)
return GetTimeString(t)
}
func GetTimeUnitParts(timeUnit string) (num int, unit string, err error) {
re := regexp.MustCompile(`^(\d+)([a-zA-Z])$`)
groups := re.FindStringSubmatch(timeUnit)
if len(groups) < 3 {
err = errors.New("failed to parse duration text")
logger.Errorf("failed to parse duration text: %v", err)
trace.PrintError(err)
return 0, "", err
}
num, err = strconv.Atoi(groups[1])
if err != nil {
logger.Errorf("failed to convert string to int: %v", err)
trace.PrintError(err)
return 0, "", err
}
unit = groups[2]
return num, unit, nil
}
func GetTimeDuration(num string, unit string) (d time.Duration, err error) {
numInt, err := strconv.Atoi(num)
if err != nil {
logger.Errorf("failed to convert string to int: %v", err)
trace.PrintError(err)
return d, err
}
switch unit {
case "s":
d = time.Duration(numInt) * time.Second
case "m":
d = time.Duration(numInt) * time.Minute
case "h":
d = time.Duration(numInt) * time.Hour
case "d":
d = time.Duration(numInt) * 24 * time.Hour
case "w":
d = time.Duration(numInt) * 7 * 24 * time.Hour
case "M":
d = time.Duration(numInt) * 30 * 24 * time.Hour
case "y":
d = time.Duration(numInt) * 365 * 24 * time.Hour
default:
err = errors.New("invalid time unit")
logger.Errorf("invalid time unit: %v", unit)
trace.PrintError(err)
return d, err
}
return d, nil
}