Code generation
I have a time in format 1days2hours3minutes4seconds which means 1 day 2 hours 3 minutes 4 seconds start from now, I want to convert it to a time.Time
Result
import (
"errors"
"fmt"
"regexp"
"strconv"
"time"
)
func parseDuration(s string) (time.Time, error) {
// Use regular expressions to extract the duration components
r := regexp.MustCompile(`(\d+)days(\d+)hours(\d+)minutes(\d+)seconds`)
matches := r.FindStringSubmatch(s)
if len(matches) != 5 {
return time.Time{}, errors.New("invalid duration format")
}
// Parse the duration components into integers
days, _ := strconv.Atoi(matches[1])
hours, _ := strconv.Atoi(matches[2])
minutes, _ := strconv.Atoi(matches[3])
seconds, _ := strconv.Atoi(matches[4])
// Calculate the total duration in seconds
totalSeconds := (days * 24 * 60 * 60) + (hours * 60 * 60) + (minutes * 60) + seconds
// Get the current time and add the duration to it
now := time.Now()
duration := time.Duration(totalSeconds) * time.Second
future := now.Add(duration)
// Return the future time
return future, nil
}
Case 1 解析字符串,转为time.Time
Prompt
Result