Home > Software design >  Round millseconds timestamp to nearest 30 seconds
Round millseconds timestamp to nearest 30 seconds

Time:03-31

I have following ruby code to get current time in "milliseconds", for example: 1648059542287 which is equivalent to Wed Mar 23 2022 18:19:02

What I need is timestamp rounded to nearest 30 seconds, for above example, I need it rounded to 1648059540000. Any suggestions?

@ctime = Time.now.to_f
(@ctime * 1000).to_i

CodePudding user response:

Using the time you provided, I think this will do what you want:

  1. Take your time, convert it to an integer
  2. divide by floating point value 30 the number of half minutes
  3. round that value and multiple by 30 to get back to the number of seconds
  4. Create a new time object based on the rounded value.
input = Time.at(1648059542,287000)
Time.at((input.to_i / 30.0).round * 30)
  •  Tags:  
  • ruby
  • Related