DateTime:小时和整数之间的差异 [英] DateTime: Difference between Hour and Integer

查看:71
本文介绍了DateTime:小时和整数之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中的第2行中有一些错误,上面有一条注释:

I have some mistakes, in my code in the 2 lines where a comment above them:

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

How can I change my code to find the best result ?

推荐答案

代码应类似于我对您的回答此处,但您需要了解我的所作所为。您肯定需要检查我使用的api调用,但是我添加了一些其他注释:

Code should be similar to my answer to you here, but you need to understand what I did. You definitely need to check api calls I used, but I added some additional comments:

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 后缀

Spend some time and check java.time api (specifically LocalTime.until). Check FiniteDuration api to understand .millis suffix I used

这篇关于DateTime:小时和整数之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆