Thursday, September 21, 2023
HomeSoftware EngineeringThe way to Subtract from Time in Golang

The way to Subtract from Time in Golang


The problem

Clock reveals h hours, m minutes and s seconds after midnight.

Your process is to jot down a operate that returns the time since midnight in milliseconds.

Instance:

h = 0
m = 1
s = 1

consequence = 61000

Enter constraints:

  • 0 <= h <= 23
  • 0 <= m <= 59
  • 0 <= s <= 59

The answer in Golang

Choice 1:

package deal answer
func Previous(h, m, s int) int {
    return (h*3600000 + m*60000 + s*1000)    
}

Choice 2:

package deal answer
func Previous(h, m, s int) int {
    return (h*60*60+m*60+s)*1000
}

Choice 3:

package deal answer
import "time"
func Previous(h, m, s int) (ms int) {
  now := time.Unix(0, 0)
  now = now.Add(time.Length(h) * time.Hour)
  now = now.Add(time.Length(m) * time.Minute)
  now = now.Add(time.Length(s) * time.Second)
  return int(now.Sub(time.Unix(0, 0)) / 1000000)
}

Take a look at circumstances to validate our answer

package deal solution_test
import (
  . "github.com/onsi/ginkgo"
  . "github.com/onsi/gomega"
)
var _ = Describe("Fundamental exams", func() {
    It("Previous(0, 1, 1)", func() { Anticipate(Previous(0, 1, 1)).To(Equal(61000)) })
    It("Previous(1, 1, 1)", func() { Anticipate(Previous(1, 1, 1)).To(Equal(3661000)) })
    It("Previous(0, 0, 0)", func() { Anticipate(Previous(0, 0, 0)).To(Equal(0)) })
    It("Previous(1, 0, 1)", func() { Anticipate(Previous(1, 0, 1)).To(Equal(3601000)) })
    It("Previous(1, 0, 0)", func() { Anticipate(Previous(1, 0, 0)).To(Equal(3600000)) })
})
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments