Разница между прошлой датой и текущим временем в минутах в Голанге - PullRequest
0 голосов
/ 10 октября 2018

У меня есть текущее время и прошедшее время, я пытаюсь найти разницу в минутах.

Вот мой код, который я пытаюсь, хотя я новичок.

package main

import (
    "fmt"
    "time"
)

func main() {
    //fetching current time
    currentTime := time.Now().Format("2006-01-02 15:04:05")
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04:05"
    //converting string to date
    pasttime, err := time.Parse(layout, pasttimestr)
        if err != nil {
        fmt.Println(err)
    }
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Println("difference time in min : ", diff)
}

Ошибка:

# command-line-arguments
.\dates.go:21:21: currentTime.Sub undefined (type string has no field or method Sub)

Заранее спасибо:)

Ответы [ 2 ]

0 голосов
/ 10 октября 2018

Вам, вероятно, следует удалить вызов функции форматирования из текущего времени, чтобы получить фактическую структуру времени, а не строковое представление, и исправить макет за прошедшее время

package main

import (
    "fmt"
    "time"
)

func main() {
    //fetching current time
    currentTime := time.Now()
    loc := currentTime.Location()
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04"
    //converting string to date
    pasttime, err := time.ParseInLocation(layout, pasttimestr, loc)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println("Past Time: ", pasttime)
    fmt.Println("Current Time: ", currentTime)
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Printf("time difference is %v or %v in minutes\n", diff, diff.Minutes())
}

Дает мне

Past Time:  2018-10-10 23:00:00 -0400 EDT
Current Time:  2018-10-10 14:31:34.865259 -0400 EDT m=+0.000351797
time difference is -8h28m25.134741s or -508.41891235 in minutes
0 голосов
/ 10 октября 2018

Отключить вызов функции .Format() на time.Now(), как показано ниже.Также я обновил layout string, чтобы он соответствовал формату pasttimestr.

func main() {
    //fetching current time
    currentTime := time.Now()
    //past time comes in as string
    pasttimestr := "2018-10-10 23:00"
    layout := "2006-01-02 15:04"
    //converting string to date
    pasttime, err := time.Parse(layout, pasttimestr)
        if err != nil {
        fmt.Println(err)
    }
    //differnce between pastdate and current date
    diff := currentTime.Sub(pasttime)
    fmt.Println("difference time is : ", diff)
}

Вывод

difference time is :  -4h36m32.001213s
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...