【问题标题】:DateTime: Difference between Hour and Integer日期时间:小时和整数之间的差异
【发布时间】:2018-03-29 12:05:14
【问题描述】:

我有一些错误,在我的代码中的 2 行中,它们上方的注释:

如何更改我的代码以找到最佳结果?

【问题讨论】:

  • The test of the function ToStart, is false in these tow cases: 您发布了 4 个案例。什么是错误的情况?请添加预期输出
  • 在上面有评论的两行

标签: scala datetime


【解决方案1】:

代码应该和我给你的here的回答类似,但是你需要明白我做了什么。你肯定需要检查我使用的 api 调用,但我添加了一些额外的 cmets:

import java.time.temporal.ChronoUnit
import java.time.LocalTime

import scala.concurrent.duration._

val t = LocalTime.now()


// start of the day
val start = LocalTime.of(9, 0)
// end of first half
val midEnd = LocalTime.of(13, 0)
// start of second half
val midStart = LocalTime.of(14, 0)
// end of the day
val end = LocalTime.of(18, 0)
// here we define duration of first half a day: diff between start of a day and midEnd (end of first half)
val firstHalf = start.until(midEnd, ChronoUnit.MILLIS).millis
// here we define duration of second half a day: diff between start of second half a day and end of a day
val secondHalf = midStart.until(end, ChronoUnit.MILLIS).millis

def toStart(t: LocalTime) = {
  // when checked time is before start of a day
  if (t.isBefore(start)) 0.hours
  // otherwise when checked time is before end of first half (will be diff between start time and checked time)
  else if (t.isBefore(midEnd)) start.until(t, ChronoUnit.MILLIS).millis
  // otherwise when checked time is before start of second half (will be duration of first half)
  else if (t.isBefore(midStart)) firstHalf
  // otherwise when checked time is before end of a day (will be duration of first half + duration of diff between checked time and start of second half)
  else if (t.isBefore(end)) firstHalf + midStart.until(t, ChronoUnit.MILLIS).millis
  // otherwise sum of durations 
  else firstHalf + secondHalf
}

// here you can add any specific format for evaluated duration
implicit class formatter(d: FiniteDuration) {
  def withMinutes = {
    // convert to minutes
    val l = d.toMinutes
    // format
    s"${l / 60}:${l % 60}"
  }
}

toStart(t).withMinutes
toStart(LocalTime.of(9, 30)).withMinutes
toStart(LocalTime.of(12, 30)).withMinutes
toStart(LocalTime.of(13, 30)).withMinutes
toStart(LocalTime.of(14, 30)).withMinutes

花一些时间检查java.time api(特别是LocalTime.until)。查看FiniteDuration api 了解我使用的.millis 后缀

【讨论】:

  • 真的非常感谢您,尤其是您的进步。我从现在开始检查 java.time API,它对我的​​项目特别有用。非常感谢@Evgeny
  • 我问了一个问题stackoverflow.com/questions/49574503/…我正在使用你的功能并拖曳另一个功能。我正在研究如何解析该函数​​等于调用其他三个函数(toEnd、ToStart 和 jourouvree),因为我应该在我的数据帧之后,特别是在我的数据帧中的 2 个参数(start_date,finish_date)上应用它你能帮我吗?
猜你喜欢
  • 1970-01-01
  • 2012-02-04
  • 1970-01-01
  • 1970-01-01
  • 2012-06-26
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多