英文:
golang how to parse time without year, but default to current year
问题
如果我有一个字符串,格式为"Today is Wed Jun 30",我可以使用以下代码解析它:
time.Parse("Today is Mon, Jan 2")
由于年份未包含在内,默认为0000年。
如何使其解析日期并默认为当前年份?我可以想到一些不太好的解决方法,比如获取当前年份并将其附加到字符串中,然后再次解析,但我猜应该有更好的方法。
英文:
If I have a string such as today's date, in the format "Today is Wed Jun 30", I can parse it with:
time.Parse("Today is Mon, Jan 2")
The year is not included, and so it is defaulted to 0000.
How do I get it to parse the date and default to the current year? I can think of some ugly workarounds, like getting the year and appending it to the string and then parsing it again, but I'm guessing there's a better way.
答案1
得分: 1
将当前年份添加到解析字符串的结果中:
t, err := time.Parse("Today is Mon, Jan 2", "Today is Wed, Jun 30")
if err != nil {
log.Fatal(err)
}
t = t.AddDate(time.Now().Year(), 0, 0)
在 playground 上运行示例:点击这里。
英文:
Add the current year to the result of parsing the string:
t, err := time.Parse("Today is Mon, Jan 2", "Today is Wed, Jun 30")
if err != nil {
log.Fatal(err)
}
t = t.AddDate(time.Now().Year(), 0, 0)
答案2
得分: 1
你可以使用strings.Replace()
方法将默认年份替换为当前年份,但需要进行一些字符串转换。我已经创建了一个示例代码来演示相同的逻辑:
package main
import (
"fmt"
"log"
"strconv"
"strings"
"time"
)
func main() {
t, err := time.Parse("Today is Mon, Jan 2", "Today is Thu, Jul 1")
if err != nil {
log.Fatal(err)
}
fmt.Println("t ", t)
fmt.Println(time.Now())
year := time.Now().Year()
fmt.Println(strings.Replace(t.String(), "0000", strconv.Itoa(year), 1))
}
输出结果:
t 0000-07-01 00:00:00 +0000 UTC
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-07-01 00:00:00 +0000 UTC
英文:
You can default to current year instead of 0000 by using strings.Replace()
method but it require you doing some string conversion ,I have created a code depicting the same logic :
package main
import (
"fmt"
"log"
"strconv"
"strings"
"time"
)
func main() {
t, err := time.Parse("Today is Mon, Jan 2", "Today is Thu, Jul 1")
if err != nil {
log.Fatal(err)
}
fmt.Println("t ", t)
fmt.Println(time.Now())
year := time.Now().Year()
fmt.Println(strings.Replace(t.String(), "0000", strconv.Itoa(year), 1))
}
Output:
t 0000-07-01 00:00:00 +0000 UTC
2009-11-10 23:00:00 +0000 UTC m=+0.000000001
2009-07-01 00:00:00 +0000 UTC
答案3
得分: 0
只需在解析后立即设置它。
t, err := time.Parse("Today is Mon, Jan 2", "Today is Mon, Jan 2")
if err != nil {
panic(err)
}
t = time.Date(time.Now().Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
英文:
Just set it right after you parse it.
t, err := time.Parse("Today is Mon, Jan 2", "Today is Mon, Jan 2")
if err != nil {
panic(err)
}
t = time.Date(time.Now().Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), t.Nanosecond(), t.Location())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论