好好爱自己!

golang 时间的比较,time.Time的初始值?

参考: https://golangcode.com/checking-if-date-has-been-set/

https://stackoverflow.com/questions/20924303/date-time-comparison-in-golang

 

// utc life
loc, _ := time.LoadLocation("UTC")

// setup a start and end time
createdAt := time.Now().In(loc).Add(1 * time.Hour)
expiresAt := time.Now().In(loc).Add(4 * time.Hour)

// get the diff
diff := expiresAt.Sub(createdAt)
fmt.Printf("Lifespan is %+v", diff)

 

---------------------------------------------------------------

Check If a Date/Time Has Been Set with IsZero

Feb 16, 2019 · 175 words · 1 minute read

In Go, we can store and use dates using the time package and although a date in Go cannot be saved as null (because there’s no such thing) there is an unset state. This unset state can be shown as 0001-01-01 00:00:00 +0000 UTC and there’s a simple way we can check if a date variable has been populated, as demonstrated below. It’s also important to note that these are not unix timestamps, which go back as far as 1970, but can handle a large spectrum of dates.

package main

import (
    "fmt"
    "time"
)

func main() {

    var myDate time.Time

    // IsZero returns a bool of whether a date has been set, but as the printf shows it will
    // still print a zero-based date if it hasn't been set.
    if myDate.IsZero() {
        fmt.Printf("No date has been set, %s\n", myDate)
    }

    // Demonstrating that by setting a date, IsZero now returns false
    myDate = time.Date(2019, time.February, 1, 0, 0, 0, 0, time.UTC)
    if !myDate.IsZero() {
        fmt.Printf("A date has been set, %s\n", myDate)
    }
}

check is date set or not

 

Use the time package to work with time information in Go.

Time instants can be compared using the Before, After, and Equal methods. The Sub method subtracts two instants, producing a Duration. The Add method adds a Time and a Duration, producing a Time.

Play example:

package main

import (
    "fmt"
    "time"
)

func inTimeSpan(start, end, check time.Time) bool {
    return check.After(start) && check.Before(end)
}

func main() {
    start, _ := time.Parse(time.RFC822, "01 Jan 15 10:00 UTC")
    end, _ := time.Parse(time.RFC822, "01 Jan 16 10:00 UTC")

    in, _ := time.Parse(time.RFC822, "01 Jan 15 20:00 UTC")
    out, _ := time.Parse(time.RFC822, "01 Jan 17 10:00 UTC")

    if inTimeSpan(start, end, in) {
        fmt.Println(in, "is between", start, "and", end, ".")
    }

    if !inTimeSpan(start, end, out) {
        fmt.Println(out, "is not between", start, "and", end, ".")
    }
}
posted @   立志做一个好的程序员  阅读(9971)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2015-10-15 iptables原理详解以及功能说明

不断学习创作,与自己快乐相处

点击右上角即可分享
微信分享提示