dpbl91234 2018-10-11 04:32
浏览 62

如何减少golang的完美时间?

I'm making a cron job for the booking charge automatic. The admin set the automatic charge after 2 hour of booking completion then I Get all the booking completed before 2 hours from the current time and charge them automatic. But the problem arise in the end of the day is that current_date= 10/10/2018 current_time= 1:00AM and automatic_charge_hours= 2 (hours) means it will get all the bookings which are completed 2 hours before the current_time and current_date. In 24hour format it will get all the bookings of the 23 hours(11:00PM of date 09/10/2018) of the previous date . But in my condition it will turn it into zero below is my condition:-

package main

import (
  "fmt"
  "time"
  "strings"
)

func main() {
timeZone, _ := time.LoadLocation("America/New_York")
currDate := time.Now().In(timeZone).Format("2006-01-02 00:00:00 -0000")
onlyDate := strings.Split(currDate, " ")
hours, _ := 1, 0
if hours-int(2) < 0 {
    hours = 0
} else {
    hours = hours - int(2)
}
fmt.Println(hours, onlyDate[0])
}

playground link https://play.golang.org/p/w7LIoTp9xN0

How will I change it. Any suggestions please.

  • 写回答

2条回答 默认 最新

  • duandong2562 2018-10-11 04:43
    关注
    if hours-int(2) < 0 {
        hours = 0
    } else {
        hours = hours - int(2)
    }
    

    Explicitly sets hours to zero when hours are negative.

    If you change hours = 0 to hours = 24 + (hours-int(2)) it returns 23.

    See https://play.golang.org/p/FyXIn5gjIXk

    Anyhow, Instead of manipulating hours by hand, you should use time functions.

    Update: Use time functions:

    package main
    
    import (
        "fmt"
        "time"
    )
    
    func main() {
        t, err := time.Parse("01.02.2006 03:04:00", "10.10.2018 01:00:00")
        if err != nil {
            panic(err)
        }
        then := t.Add(time.Duration( -2 ) * time.Hour)
        fmt.Printf("%v
    ", then)
    }
    

    https://play.golang.org/p/0r6q7Vvai2h

    评论

报告相同问题?

悬赏问题

  • ¥15 求帮我调试一下freefem代码
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图