好好爱自己!

Return local beginning of day time object in Go

Both the title and the text of the question asked for "a local [Chicago] beginning of today time." The Bod function in the question did that correctly. The accepted Truncate function claims to be a better solution, but it returns a different result; it doesn't return a local [Chicago] beginning of today time. For example,

package main

import (
    "fmt"
    "time"
)

func Bod(t time.Time) time.Time {
    year, month, day := t.Date()
    return time.Date(year, month, day, 0, 0, 0, 0, t.Location())
}

func Truncate(t time.Time) time.Time {
    return t.Truncate(24 * time.Hour)
}

func main() {
    chicago, err := time.LoadLocation("America/Chicago")
    if err != nil {
        fmt.Println(err)
        return
    }
    now := time.Now().In(chicago)
    fmt.Println(Bod(now))
    fmt.Println(Truncate(now))
}

Output:

2014-08-11 00:00:00 -0400 EDT
2014-08-11 20:00:00 -0400 EDT

The time.Truncate method truncates UTC time.

The accepted Truncate function also assumes that there are 24 hours in a day. Chicago has 23, 24, or 25 hours in a day.

posted @   立志做一个好的程序员  阅读(788)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
历史上的今天:
2018-08-23 [转]php中实现事件驱动
2018-08-23 给ubuntu设置静态ip —— How to set static IP Address in Ubuntu Server 16.04
2018-08-23 成为一个有目标的学习者
2018-08-23 PHP Variable Scope
2018-08-23 linux中backticks反引号的作用
2017-08-23 【转】Unix下C程序内存泄漏检测工具Valgrind安装与使用
2016-08-23 三种Dataase Mapping的系统架构

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

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