本文介绍了如何获取Ruby on Rails中两个DateTimes之间的秒数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有代码可以为员工进行时间跟踪。它创建一个计数器来显示员工已经记录了多长时间。



这是当前的代码:



$ _ code> start_time = Time.parse(self.settings.first_clock_in)
total_seconds = Time.now - start_time
hours =(total_seconds / 3600).to_i
minutes =((total_seconds%3600)/ 60).to_i
seconds =((total_seconds%3600)%60).to_i

这工作正常。但是由于时间限制在1970 - 2038年的范围之内,我们正试图用DateTimes替代所有Time的用途。我不知道如何获得两个DateTimes之间的秒数。减去它们产生一个我不知道如何解释的Rational,而减去Times产生差异。

解决方案

减法两个DateTimes返回以天为单位的经过时间,因此您可以执行以下操作:

  elapsed_seconds =((end_time  -  start_time)* 24 * 60 * 60).to_i 


I've got code that does time tracking for employees. It creates a counter to show the employee how long they have been clocked in for.

This is the current code:

  start_time = Time.parse(self.settings.first_clock_in)
  total_seconds = Time.now - start_time
  hours = (total_seconds/ 3600).to_i
  minutes = ((total_seconds % 3600) / 60).to_i
  seconds = ((total_seconds % 3600) % 60).to_i

This works fine. But because Time is limited to the range of 1970 - 2038 we are trying to replace all Time uses with DateTimes. I can't figure out how to get the number of seconds between two DateTimes. Subtracting them yields a Rational which I don't know how to interpret, whereas subtracting Times yields the difference in seconds.

解决方案

Subtracting two DateTimes returns the elapsed time in days, so you could just do:

elapsed_seconds = ((end_time - start_time) * 24 * 60 * 60).to_i

这篇关于如何获取Ruby on Rails中两个DateTimes之间的秒数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 18:08