dongqu7778 2017-07-11 02:45
浏览 129
已采纳

比较两个日期而不考虑时间

I have two dates like this, I would like to compare only the dates, ignoring the time. Currently I have this:

package main

import (
    "time"
    //"fmt"
)

func main() {
    a, _ := time.Parse(time.RFC3339, "2017-02-01T12:00:00+00:00")
    b, _ := time.Parse(time.RFC3339, "2017-02-11T14:30:00+00:00")

    x := b.Sub(a)

    println(int(x.Hours()))
}

Which prints 242. That is correct, but what I actually want to do is compare the dates like this:

    a, _ := time.Parse(time.RFC3339, "2017-02-01T00:00:00+00:00")
    b, _ := time.Parse(time.RFC3339, "2017-02-11T00:00:00+00:00")

Notice: minutes/hours/seconds have been set to zero - the diff will now be 240 hours.

I couldn't really figure out how to do this, is there a time.SetTime(0, 0, 0) function in Go that I missed or what's the canonical way to reset the time for a date?

  • 写回答

2条回答 默认 最新

  • dongyi9298 2017-07-11 02:52
    关注

    You could Truncate the times to make them round to a multiple of a day.

    In your example:

    oneDay := 24 * time.Hour
    a = a.Truncate(oneDay)
    b = b.Truncate(oneDay)
    

    Find a playground with the adapted code here: https://play.golang.org/p/yWIYt3UkiT

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大