Go语言时间与字符串以及时间戳的相互转换

1、时间与字符串以及时间戳的相互转换

  • Time类型---------->string类型

  • string类型---------->Time类型

  • Time类型---------->时间戳int64类型(秒)

  • 时间戳int64类型(秒)---------->Time类型

package main

import (
   "fmt"
   "time"
)

func main() {

   //获取当前时间Time类型
   now := time.Now()
   fmt.Println(fmt.Sprintf("当前时间(Time类型):%s", now)) //返回当前时间Time类型

   //Time类型---------->string类型
   strTime := now.Format("2006-01-02 15:04:05")
   fmt.Println(fmt.Sprintf("当前时间(string类型)(Time类型---------->string类型):%s", strTime)) //格式化时间为字符串

   //string类型---------->Time类型
   loc, _ := time.LoadLocation("Local") //获取当地时区
   location, err := time.ParseInLocation("2006-01-02 15:04:05", "2021-11-30 19:21:35", loc)
   if err != nil {
      return
   }
   fmt.Printf("string类型(2021-11-30 19:21:35)---------->Time类型:%+v\n", location)

   //Time类型---------->时间戳(秒)
   unix := now.Unix()
   fmt.Printf("当前时间戳(int64类型)(Time类型---------->时间戳(秒)int64类型):%d\n", unix) //获取时间戳,基于1970年1月1日,单位秒

   //时间戳(秒)---------->Time类型
   unixStr := time.Unix(1638271295, 0)
   fmt.Printf("时间戳(秒)2021-11-30 19:21:35|1638271295---------->Time类型:%s", unixStr)
}

image-20211130195835521

2、今天是几月几号周几

package main

import (
   "fmt"
   "time"
)

func main() {

   //获取当前时间Time类型
   now := time.Now()
   fmt.Println(fmt.Sprintf("当前时间(Time类型):%s", now)) //返回当前时间Time类型

   day := now.Day()
   fmt.Printf("今天是几号-->%d\n", day)

   fmt.Printf("本月是几月-->%s\n", now.Month())

   fmt.Printf("今天是周几-->%s\n", now.Weekday())
}

image-20211130195754702

3、时间的加法(获取下周几是几月几号)

思路举例:

  • 假设今天是周二,求下周三是几月几号?

    • 求下周三是几月几号,则下周一到下周三就是3天(记录为number)

    • 今天是周二,则周二到这周末还剩余7-2=5天(记录为7 - weekday)

    • 所以距离下周三就还剩余7 - weekday + number天

    • 所以用今天加上天数即可知道下周三是几月几号

package main

import (
   "fmt"
   "time"
)

func main() {
   GetNextWeekNumber(time.Monday)    //求下周一是几月几号
   GetNextWeekNumber(time.Tuesday)   //求下周二是几月几号
   GetNextWeekNumber(time.Wednesday) //求下周三是几月几号
   GetNextWeekNumber(time.Thursday)  //求下周四是几月几号
   GetNextWeekNumber(time.Friday)    //求下周五是几月几号
   GetNextWeekNumber(time.Saturday)  //求下周六是几月几号
   GetNextWeekNumber(time.Sunday)    //求下周天是几月几号

   GetNextWeekNumber(8)  //求下周一是几月几号 (根据对7取余数来计算)
   GetNextWeekNumber(9)  //求下周二是几月几号 (根据对7取余数来计算)
   GetNextWeekNumber(10) //求下周三是几月几号(根据对7取余数来计算)

   //GetNextWeekNumber(-1) //求这周六是几月几号
   //GetNextWeekNumber(-2) //求这周五是几月几号
   //GetNextWeekNumber(-3) //求这周四是几月几号
}

func GetNextWeekNumber(next time.Weekday) {
   number := next % 7 //保证是求下周一到下周天的某一个
   now := time.Now()
   weekday := now.Weekday()
   if weekday == time.Sunday {
      weekday = 7 //周一为第一天,周二为第二天,以此类推,周天表示为第7天
   }
   if number == time.Sunday {
      number = 7
   }
   expiryDays := 7 - weekday + number
   nextWeek := now.AddDate(0, 0, int(expiryDays))
   fmt.Printf("下一个%s 是 %s\n", next.String(), nextWeek)
}

image-20211201103208040

posted @ 2021-12-01 10:43  南风丶轻语  阅读(1855)  评论(0编辑  收藏  举报