Go 語言程式演示時間運算
我們將使用 Go 程式語言中 time 包的 Now 函式計算當前時間,以演示時間運算。時間運算使用數學函式進行計算。在這兩個示例中,我們將使用數學計算來查詢過去、未來和使用 Sub 函式計算的持續時間。輸出使用 fmt 包的 Println 函式列印。
語法
func Now() Time
Now() 函式在 time 包中定義。此函式生成當前本地時間。要使用此函式,我們必須首先在程式中匯入 time 包。
func sub()
此函式是 time 包的一部分。它用於計算兩個 time.Time 值之間的持續時間。
time.Hour()
此方法是 time 包的一部分。它用於獲取當前小時作為 time.Hour 值。
演算法
在程式中匯入所需的包
建立一個 main 函式
在 main 函式中,使用 time 包的 Now 函式查詢當前時間
使用內建函式和數學邏輯計算未來、過去和持續時間
在控制檯上列印當前時間、未來、過去和持續時間
列印語句使用 fmt 包的 Println 函式執行
示例 1
在此示例中,當前時間將使用 time 包的 Now 函式計算。然後透過將 3 小時的持續時間新增到當前時間來計算未來,透過從未來減去 2 天的持續時間來計算過去,並且使用 Sub 函式計算過去和當前時間之間的差異。所有這些值都使用 Println 函式在控制檯上列印。
//Golang program to demonstrate the time arithmetic
package main
import (
"fmt"
"time"
)
//Main function to execute the program
func main() {
current_time := time.Now() //find the current time using Now function
// Add a duration of 3 hours to now
future := current_time.Add(3 * time.Hour)
// Subtract a duration of 2 days from future
past := future.Add(-2 * 24 * time.Hour)
// Calculate the difference between past and current_time
duration := current_time.Sub(past)
// Print the values calculated above
fmt.Println("Now:", current_time)
fmt.Println("Future:", future)
fmt.Println("Past:", past)
fmt.Println("Duration between past and now:", duration)
}
輸出
Now: 2023-02-28 09:31:56.827693083 +0000 UTC m=+0.000016893 Future: 2023-02-28 12:31:56.827693083 +0000 UTC m=+10800.000016893 Past: 2023-02-26 12:31:56.827693083 +0000 UTC m=-161999.999983107 Duration between past and now: 45h0m0s
示例 2
在此示例中,我們將像在最後一個示例中一樣,使用 Now 函式計算當前時間。未來將透過將 10 分鐘新增到當前時間來計算。然後,從未來時間減去 1 小時以獲得過去,並且將使用 Sub 函式以及過去和當前時間來計算持續時間。所有計算出的值都將列印到控制檯上。讓我們看一下程式碼。
package main
import (
"fmt"
"time"
)
func main() {
current_time := time.Now() //calculate the current time using the Now function
// Add 10 minutes to the current time
future := current_time.Add(10 * time.Minute)
// Subtract 1 hour from the future time
past := future.Add(-1 * time.Hour)
// Calculate the duration between past and now
duration := current_time.Sub(past)
// Print the values calculated above
fmt.Println("Now:", current_time)
fmt.Println("Future:", future)
fmt.Println("Past:", past)
fmt.Println("Duration between past and now:", duration)
}
輸出
Now: 2023-02-28 09:33:53.548874654 +0000 UTC m=+0.000018376 Future: 2023-02-28 09:43:53.548874654 +0000 UTC m=+600.000018376 Past: 2023-02-28 08:43:53.548874654 +0000 UTC m=-2999.999981624 Duration between past and now: 50m0s
結論
我們使用兩個示例執行並編譯了演示時間運算的程式。在這兩個示例中,我們使用不同的數學邏輯和 Sub 函式(有助於查詢持續時間)計算了過去、未來、currentTime 和持續時間。
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP