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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM