función time.Time.Sub() en Golang con ejemplos

En el lenguaje Go, los paquetes de tiempo brindan funcionalidad para determinar y ver el tiempo. La función Time.Sub() en lenguaje Go se utiliza para arrojar la duración obtenida al realizar la operación tu. Y si la salida aquí supera el valor máximo o mínimo que se puede almacenar en una Duración «d», entonces se devolverá la duración máxima o mínima. Además, esta función se define en el paquete de tiempo. Aquí, debe importar el paquete «tiempo» para poder usar estas funciones.

Sintaxis:

func (t Time) Sub(u Time) Duration

Aquí, «t» y «u» son el tiempo establecido.

Nota: para calcular «td» para una duración determinada «d», debe usar t.Add (-d).

Valor devuelto: Devuelve la duración obtenida al realizar la operación tu.

Ejemplo 1:

// Golang program to illustrate the usage of
// Time.Sub() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Calling main
func main() {
  
    // Defining t and u for Sub method
    t := time.Date(2020, 11, 14, 16,
               45, 16, 36, time.UTC)
    u := time.Date(2019, 9, 5, 18, 0,
                      0, 0, time.UTC)
  
    // Calling Sub method
    subtract := t.Sub(u)
  
    // Prints output
    fmt.Printf("t-d = %v\n", subtract)
}

Producción:

t-d = 10462h45m16.000000036s

Ejemplo 2:

// Golang program to illustrate the usage of
// Time.Sub() function
  
// Including main package
package main
  
// Importing fmt and time
import (
    "fmt"
    "time"
)
  
// Calling main
func main() {
  
    // Defining t and u for Sub method
    t := time.Date(2020, 11, 14, 34, 
               67, 98, 63, time.UTC)
    u := time.Date(2019, 9, 5, 28, 
            66, 89, 100, time.UTC)
  
    // Calling Sub method
    subtract := t.Sub(u)
  
    // Prints output
    fmt.Printf("t-d = %v\n", subtract)
}

Producción:

t-d = 10470h1m8.999999963s

Aquí, los tiempos «t» y «u» indicados en el código anterior tienen valores que están fuera del rango habitual pero se normalizan durante la conversión.

Publicación traducida automáticamente

Artículo escrito por nidhi1352singh y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *