当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Golang time.Since()用法及代码示例

在Go语言中,时间包提供了确定和查看时间的函数。 Go语言中的Since()函数保留时间值,并用于评估与实际时间的差异。此外,此函数在时间包下定义。在这里,您需要导入“time”包才能使用这些函数。

用法:

func Since(t Time) Duration

在此,t是时间值。

注意:此方法是time.Now().Sub(t)的快捷方式。

返回值:它返回一个持续时间值。



范例1:

// Golang program to illustrate in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Calling main 
func main() { 
  
    // Defining time value 
    // of Since method 
    now:= time.Now() 
  
    // Prints time elapse 
    fmt.Println("time elapse:", 
             time.Since(now)) 
}

输出:

time elapse:210ns // Can be different at different run times

在此,打印从现在到当前时间之间经过的时间。因此,它在不同的运行时间可能会有所不同。

范例2:

// Golang program to illustrate in Golang 
  
// Including main package 
package main 
  
// Importing fmt and time 
import ( 
    "fmt"
    "time"
) 
  
// Calling main 
func main() { 
  
    // Defining time value  
    // of Since method 
    timevalue:= time.Now() 
  
    // Calling Since method 
    // with its parameter 
    Duration:= time.Since(timevalue) 
  
    // Prints time elapse in nanoseconds 
    fmt.Println("time elapse in nanoseconds:", 
                   Duration.Nanoseconds()) 
}

输出:

time elapse in nanoseconds:351 // Can be different at different run times



相关用法


注:本文由纯净天空筛选整理自nidhi1352singh大神的英文原创作品 time.Since() Function in Golang With Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。