Golang 演示时间算术
我们将使用Go编程语言中的time包的Now函数计算当前时间,以演示时间算术。时间算术是使用数学函数计算的。在这两个示例中,我们将使用数学计算来找到过去、未来和持续时间,使用Sub函数进行计算。输出是使用fmt包中的Println函数打印的。
语法
func Now() Time
Now() 函数在time
包中被定义。该函数生成当前的本地时间。要使用该函数,在我们的程序中首先要导入time
包。
func sub()
此函数是时间包的一部分。它用于计算两个time.Time值之间的持续时间。
time.Hour()
此方法是时间包的一部分。它用于将当前小时获取为time.Hour值。
步骤
- 在程序中导入所需的包
-
创建一个主函数
-
在主函数中使用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
结论
我们执行并编译了使用两个示例演示时间算术的程序。在这两个示例中,我们使用不同的数学逻辑和子函数来计算过去、未来、当前时间和持续时间,这些都对于找到持续时间非常有帮助。