栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Go语言

golang日期字符串的互转

Go语言 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

golang日期字符串的互转

  • 绝不BB 上代码 包含时区转换
package main

import (
	"fmt"
	"time"
)

func main() {
	// 日期转字符串
	currentTime := time.Now()
	fmt.Println("Current Time in String: ", currentTime.String())
	fmt.Println("MM-DD-YYYY : ", currentTime.Format("01-02-2006"))
	fmt.Println("YYYY-MM-DD : ", currentTime.Format("2006-01-02"))
	fmt.Println("YYYY.MM.DD : ", currentTime.Format("2006.01.02 15:04:05"))
	// 字符串转日期
	tm2, _ := time.Parse("01/02/2006", "04/29/2021")
	fmt.Println(tm2.Format("2006-01-02"))

    // ----------------有关时区的问题-----------------
    toBeCharge := "2021-04-28T00:00:00+08:00"                             //待转化为时间戳的字符串 注意 这里的小时和分钟还要秒必须写 因为是跟着模板走的 修改模板的话也可以不写
	timeLayout := "2006-01-02T00:00:00+08:00"                             //转化所需模板
	loc, _ := time.LoadLocation("Local")                            //重要:获取时区
	theTime, _ := time.ParseInLocation(timeLayout, toBeCharge, loc) //使用模板在对应时区转化为time.time类型
	sr := theTime.Unix()                                            //转化为时间戳 类型是int64
	fmt.Println(theTime)                                            //打印输出theTime 2015-01-01 15:15:00 +0800 CST
	fmt.Println(sr)                                                 //打印输出时间戳 1420041600

	//时间戳转日期
	dataTimeStr := time.Unix(sr, 0).Format("2006-01-02") //设置时间戳 使用模板格式化为日期字符串
	fmt.Println(dataTimeStr)
}

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/908973.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号