• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Scala LocalTime类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Scala中java.time.LocalTime的典型用法代码示例。如果您正苦于以下问题:Scala LocalTime类的具体用法?Scala LocalTime怎么用?Scala LocalTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了LocalTime类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。

示例1: TimeServiceImpl

//设置package包名称以及导入依赖的类
package time.impl

import time.api.TimeService
import com.lightbend.lagom.javadsl.api.ServiceCall
import akka.NotUsed
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
import java.time.LocalTime
import java.time.ZoneId

class TimeServiceImpl extends TimeService{

  
  override def timeAt(tz: String): ServiceCall[NotUsed, String] = {
    new ServiceCall[NotUsed, String] {
      
      override def invoke(obj: NotUsed) : CompletionStage[String] = {
        val c = new CompletableFuture[String]
        c.complete(LocalTime.now(ZoneId.of(tz, ZoneId.SHORT_IDS)).toString)
        c
      }
      
    }
  }
  
} 
开发者ID:oswaldo,项目名称:lagom-scala-scalajs-scalatags,代码行数:27,代码来源:TimeServiceImpl.scala


示例2: Time

//设置package包名称以及导入依赖的类
package uk.vitalcode.dateparser.token

import java.time.LocalTime
import java.time.format.DateTimeFormatter

import scala.util.Try

final case class Time(value: LocalTime, index: Int) extends DateToken

object Time extends TokenCompanion[Time] {

  def apply(hours: Int, minutes: Int, seconds: Int = 0, index: Int = 0): Time = Time(LocalTime.of(hours, minutes, seconds), index)

  private val timeFormatter: DateTimeFormatter = DateTimeFormatter.ofPattern(""
    + "[h.m[.s]a]"
    + "[h[:m][:s]a]"
    + "[H.m[.s]]"
    + "[H:m[:s]]"
  )

  // matches with either : or .  separators,
  // will match a 24 hour time, or a 12 hour time with AM or PM specified,
  // allows 0-59 minutes, and 0-59 seconds. Seconds are not required.
  // http://regexlib.com/REDetails.aspx?regexp_id=144
  private val timeRegEx =
  """((([0]?[1-9]|1[0-2])((:|\.)[0-5]?[0-9])?((:|\.)[0-5]?[0-9])?( )?(AM|am|aM|Am|PM|pm|pM|Pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5]?[0-9]((:|\.)[0-5]?[0-9])?))""".r

  override def of(text: String, index: Int): Try[Time] = Try {
    timeRegEx.findFirstIn(text)
      .map(_.replaceAll("""\s*""", "").toUpperCase)
      .map(timeString => LocalTime.parse(timeString, timeFormatter))
      .map(localTime => Time(localTime, index))
      .get
  }
} 
开发者ID:vitalcode,项目名称:date-time-range-parser,代码行数:36,代码来源:Time.scala


示例3: DateTimeInterval

//设置package包名称以及导入依赖的类
package uk.vitalcode.dateparser

import java.time.format.DateTimeFormatter
import java.time.{LocalDate, LocalDateTime, LocalTime}

import uk.vitalcode.dateparser.token.DateToken

case class DateTimeInterval(from: LocalDateTime, to: Option[LocalDateTime]) {
  def to(date: LocalDate, time: LocalTime): DateTimeInterval = copy(
    to = Some(LocalDateTime.of(date, time))
  )

  def to(year: Int, month: Int, day: Int, hours: Int = 0, minutes: Int = 0): DateTimeInterval = copy(
    to = Some(LocalDateTime.of(year, month, day, hours, minutes))
  )

  private def formatDate(date: LocalDateTime) = date.format(DateTimeFormatter.ISO_DATE_TIME)

  override def toString: String = s"interval[from: ${formatDate(from)}" + to.map(d => s" to: ${formatDate(d)}").getOrElse("") + "]"
}

object DateTimeInterval {

  val defaultTime = LocalTime.of(0, 0)

  def from(date: LocalDate, time: LocalTime): DateTimeInterval = new DateTimeInterval(
    from = LocalDateTime.of(date, time),
    to = None
  )

  def from(year: Int, month: Int, day: Int, hours: Int = 0, minutes: Int = 0): DateTimeInterval = new DateTimeInterval(
    from = LocalDateTime.of(year, month, day, hours, minutes),
    to = None
  )

  def of(dateTokens: List[DateToken], tp: DateTimeProvider): List[DateTimeInterval] = {
    val aggregatedTokens = aggregateTokens(dateTokens, tp)
    Analyser.analyse(aggregatedTokens)
  }

  def of(text: String, tp: DateTimeProvider = new DefaultDateTimeProvider): List[DateTimeInterval] = {
    val tokens = DateToken.parse(text)
    of(tokens, tp)
  }

  private def aggregateTokens(dateTokens: List[DateToken], timeProvider: DateTimeProvider): List[DateToken] = {
    val aggregatedTokens = DateTokenAggregator.aggregate(dateTokens, timeProvider)
    if (aggregatedTokens == dateTokens) aggregatedTokens
    else aggregateTokens(aggregatedTokens, timeProvider)
  }
} 
开发者ID:vitalcode,项目名称:date-time-range-parser,代码行数:52,代码来源:DateTimeInterval.scala


示例4: Converters

//设置package包名称以及导入依赖的类
package com.github.akhil.slick

import java.time.{ LocalDate, LocalDateTime, LocalTime }

import com.github.akhil.slick.converter._

object Converters {

  implicit class WrappedLocalDateTime(d: LocalDateTime) extends LocalDateTimeSqlTimestampConverter {
    def toSqlTimestamp(): java.sql.Timestamp = toSqlType(d)
  }

  implicit class WrappedLocalDateTimeOption(d: Option[LocalDateTime]) extends LocalDateTimeSqlTimestampConverter {
    def toSqlTimestampOption(): Option[java.sql.Timestamp] = d.map(toSqlType)
  }

  implicit class WrappedLocalDate(d: LocalDate) extends LocalDateSqlDateConverter {
    def toSqlDate(): java.sql.Date = toSqlType(d)
  }

  implicit class WrappedLocalDateOption(d: Option[LocalDate]) extends LocalDateSqlDateConverter {
    def toSqlDateOption(): Option[java.sql.Date] = d.map(toSqlType)
  }

  implicit class WrappedLocalTime(t: LocalTime) extends LocalTimeSqlTimeConverter {
    def toSqlTime(): java.sql.Time = toSqlType(t)
  }

  implicit class WrappedLocalTimeOption(t: Option[LocalTime]) extends LocalTimeSqlTimeConverter {
    def toSqlTimeOption(): Option[java.sql.Time] = t.map(toSqlType)
  }

  implicit class WrappedSqlTimestampForLocalDateTime(t: java.sql.Timestamp) extends LocalDateTimeSqlTimestampConverter {
    def toLocalDateTime(): LocalDateTime = fromSqlType(t)
  }

  implicit class WrappedSqlTimestampOptionForLocalDateTime(t: Option[java.sql.Timestamp]) extends LocalDateTimeSqlTimestampConverter {
    def toLocalDateTimeOption(): Option[LocalDateTime] = t.map(fromSqlType)
  }

  implicit class WrappedSqlTime(t: java.sql.Time) extends LocalTimeSqlTimeConverter {
    def toLocalTime(): LocalTime = fromSqlType(t)
  }

  implicit class WrappedSqlTimeOption(t: Option[java.sql.Time]) extends LocalTimeSqlTimeConverter {
    def toLocalTimeOption(): Option[LocalTime] = t.map(fromSqlType)
  }

  implicit class WrappedSqlDate(d: java.sql.Date) extends LocalDateSqlDateConverter {
    def toLocalDate(): LocalDate = fromSqlType(d)
  }

  implicit class WrappedSqlDateOption(d: Option[java.sql.Date]) extends LocalDateSqlDateConverter {
    def toLocalDateOption(): Option[LocalDate] = d.map(fromSqlType)
  }

} 
开发者ID:akhil,项目名称:slick-javatime-mapper,代码行数:58,代码来源:Converters.scala


示例5: Identifiers

//设置package包名称以及导入依赖的类
package com.kimstebel.alexa

import java.time.LocalTime
import org.http4s._
import org.http4s.dsl._
import org.http4s.client.blaze._
import org.json4s._
import org.json4s.native.JsonMethods._




case class Identifiers(global: Option[String])

case class AuthResponse(
  token: String,
  persistentToken: String,
  userId: String,
  username: String,
  identifiers: Identifiers,
  roles: Seq[String],
  userCreationTime: LocalTime
)

object AuthClient {
  
  private val client = PooledHttp1Client()
  
  def apply = {
    val Seq(user, password, account) = Seq("user", "password", "account").map(key => Config.conf.getString(s"""secrets."alexa.uat.test-$key""""))
    
    val loginUri = Uri.uri("https://myovo-uat.ovoenergy.com/api/auth/login")
    val req = Request(POST, loginUri).withBody(s"""
{
    "username": "$user",
    "password": "$password",
    "rememberMe": true
}
""").replaceAllHeaders(Header("Accept", "application/json")).withType(MediaType.`application/json`)

//replaceAllHeaders(Header("Content-Type", "application/json;charset=UTF-8"))
    val res = client.expect[String](req).run
    implicit val formats = DefaultFormats
    
    
    
    (user, password, account)
  }
} 
开发者ID:KimStebel,项目名称:magic8ball,代码行数:50,代码来源:AuthClient.scala


示例6: Now

//设置package包名称以及导入依赖的类
package akka.http

import java.time.LocalTime

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.model.StatusCodes
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import com.typesafe.config.ConfigFactory
import org.scalatest._
import spray.json.DefaultJsonProtocol

case class Now(time: String = LocalTime.now.toString)

trait NowService extends DefaultJsonProtocol with SprayJsonSupport {
  import akka.http.scaladsl.server.Directives._
  import akka.http.scaladsl.marshalling._
  import akka.http.scaladsl.model.HttpResponse
  implicit val nowFormat = jsonFormat1(Now)

  val routes = path("now") {
    get {
      complete(ToResponseMarshallable[Now](Now()))
    } ~
    post {
      entity(as[Now]) { now =>
        if (now.time.isEmpty) complete(HttpResponse(NotFound)) else complete(HttpResponse(OK))
      }
    }
  }
}

class HttpJsonTest extends WordSpec with Matchers with ScalatestRouteTest with BeforeAndAfterAll with NowService {
  val actorRefFactory = ActorSystem.create("now", ConfigFactory.load("test.conf"))
  val server = Http().bindAndHandle(routes, "localhost", 0)

  override protected def afterAll(): Unit = {
    server.flatMap(_.unbind()).onComplete(_ ? system.terminate())
  }

  "NowService" should {
    "handle get and post." in {
      Get("/now") ~> routes ~> check {
        responseAs[Now].time.nonEmpty shouldBe true
      }
      Post("/now", Now()) ~> routes ~> check {
        status shouldBe StatusCodes.OK
      }
    }
  }
} 
开发者ID:objektwerks,项目名称:akka.http,代码行数:54,代码来源:HttpJsonTest.scala


示例7: TimeParser

//设置package包名称以及导入依赖的类
package performanceanalysis

import java.time.LocalTime

import scala.util.Try
import scala.util.matching.Regex.Match

class TimeParser(shift: Int) {

  private val iHour = shift + 1

  private val iMin = shift + 2

  private val iSec = shift + 3

  private val iNano = iSec + 1

  private def nanoOption(s: String): Option[String] = {
    val nanoTry = Try(Option(s))
    nanoTry.toOption.flatten
  }

  def parse(m: Match): LocalTime = {
    val hour = m.group(iHour).toInt
    val min = m.group(iMin).toInt
    val sec = m.group(iSec).toInt
    val nano = nanoOption(m.group(iNano)) match {
      case None => 0
      case Some(".") => 0
      case Some(s) => (s.toDouble * 1000000000).toInt
    }
    LocalTime.of(hour, min, sec, nano)
  }

} 
开发者ID:scala-academy,项目名称:performance-analysis,代码行数:36,代码来源:TimeParser.scala


示例8: Scheduler

//设置package包名称以及导入依赖的类
package net.seabears.hockey

import java.time.{LocalDate, LocalTime, ZonedDateTime}
import java.time.format.DateTimeFormatter

import net.ruippeixotog.scalascraper.browser.JsoupBrowser
import net.ruippeixotog.scalascraper.dsl.DSL._
import net.ruippeixotog.scalascraper.dsl.DSL.Extract._
import net.ruippeixotog.scalascraper.dsl.DSL.Parse._
import net.ruippeixotog.scalascraper.model.Element

import net.seabears.hockey.core._
import net.seabears.hockey.util.DateUtils

object Scheduler {
  def apply(adapterFactory: Game => GameAdapter, dateStart: String, dateEnd: String, host: String)(implicit userAgentFactory: () => String, pauseFactory: () => Unit) =
    new Scheduler(adapterFactory, host, DateUtils.dates(dateStart, dateEnd), userAgentFactory, pauseFactory)
}

class Scheduler(adapterFactory: Game => GameAdapter, host: String, dates: Seq[LocalDate], userAgentFactory: () => String, pauseFactory: () => Unit) {
  private[this] val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
  private[this] val browser = new JsoupBrowser(userAgentFactory())

  def run() {
    dates.flatMap(getGames)
         .map(adapterFactory)
         .filter(_.isNew)
         .foreach(_.save)
  }

  private[this] def getGames(date: LocalDate): List[FutureGame] = {
    val dayId = date.format(formatter)
    val url = host + dayId
    println("Searching for games at " + url)
    val doc = browser.get(url)
    val tables: List[Element] = doc >> elementList("div.game-header")
    tables.map(toGame(date))
  }

  private def toGame(date: LocalDate)(element: Element): FutureGame = {
    pauseFactory()
    val away = element.select("table.game-header-table tr:nth-child(1) td.team-name").head.text
    val home = element.select("table.game-header-table tr:nth-child(3) td.team-name").head.text
    val time = element.select("ul.game-info li:nth-child(2) span:first-child").head.text
    FutureGame(Team("", home), Team("", away), parseTime(date, time))
  }

  private def parseTime(date: LocalDate, timeToParse: String) = {
    val gameTime = """^\s*(\d+:\d+\s+\w+)\s+(\w+)\s*$""".r
    val gameTime(rawTime, rawZone) = timeToParse
    val time = LocalTime.parse(rawTime, DateTimeFormatter.ofPattern("h:mm a"))
    ZonedDateTime.of(date, time, DateUtils.parseZone(rawZone))
  }
} 
开发者ID:cberes,项目名称:hockey-stats-loader,代码行数:55,代码来源:scheduler.scala


示例9: Settings

//设置package包名称以及导入依赖的类
package WorkDayLength

import java.time.LocalTime
import java.time.format.DateTimeFormatter

import com.typesafe.config.Config

class Settings(config: Config) {

  val app = new AppSettings(config.getConfig("app"))
  val httpClient = new HttpSettings(config.getConfig("app.http"))

  override def toString: String = s"App: $app; HttpClient: $httpClient"
}

class AppSettings(config: Config) {
  val startDate = config.getString("startDate")
  val endDate = config.getString("endDate")
  val minimalTime = config.getInt("grouping.max_timeout")
  val dayStartsAt = LocalTime.parse(config.getString("dayStartsAt"), DateTimeFormatter.ISO_LOCAL_TIME)
  val dayEndsAt = LocalTime.parse(config.getString("dayEndsAt"), DateTimeFormatter.ISO_LOCAL_TIME)

  override def toString: String = s"startDate: $startDate, endDate: $endDate, minimalTime: $minimalTime"
}

class HttpSettings(config: Config) {
  val key = config.getString("key")
  val protocol = config.getString("protocol")
  val hostname = config.getString("hostname")
  val port = config.getInt("port")

  override def toString: String = s"protocol: $protocol, hostname: $hostname, port: $port, key: $key"
} 
开发者ID:denyago,项目名称:work_day_length,代码行数:34,代码来源:Settings.scala


示例10: DayLength

//设置package包名称以及导入依赖的类
package WorkDayLength.Reports

import java.time.format.DateTimeFormatter
import java.time.{Duration, LocalTime}

import WorkDayLength.{TimeEntry, TimeEntryHelper}


object DayLength {
  def result(entries: List[TimeEntry], dayStartsAt: LocalTime, dayEndsAt: LocalTime): String = {

    def closestIndex(entries: List[TimeEntry], time: LocalTime): Int = {
      entries.
      zipWithIndex.
      map(pair => {
        val distance = Duration.between(time, pair._1.startsAt.toLocalTime).getSeconds
        val index = pair._2
        (Math.abs(distance), index)
      }).
      minBy(_._1).
      _2
    }

    val closestIndexToStart = closestIndex(entries, dayStartsAt)
    val closestIndexToEnd = closestIndex(entries, dayEndsAt)

    val workEntries = entries.slice(closestIndexToStart, closestIndexToEnd + 1)

    // TODO: Summerize properly
    val startAt = TimeEntryHelper.startsEarliest(workEntries).startsAt
    val endAt = TimeEntryHelper.endsLatest(workEntries).endsAt
    val overallDuration = TimeEntryHelper.addDurations(workEntries)

    startAt.toLocalDate + ": Worked from " +
      startAt.toLocalTime + " till " + endAt.toLocalTime + " for " +
      TimeEntryHelper.DurationParts(overallDuration).toString
  }
} 
开发者ID:denyago,项目名称:work_day_length,代码行数:39,代码来源:DayLength.scala


示例11: DayLengthSpec

//设置package包名称以及导入依赖的类
package unit

import java.time.LocalTime

import WorkDayLength.Reports.DayLength
import WorkDayLength.TimeEntry

class DayLengthSpec extends UnitSpec{
  it("returns all activities within 'workday relative time'") {
    val dayStartsAt = LocalTime.parse("09:45")
    val dayEndsAt = LocalTime.parse("18:40")
    // Delta is 5 minutes
    val entries = List(
      TimeEntry("2016-04-13T09:30:00", 60, 1, "early activity", "", 0), // out
      TimeEntry("2016-04-13T09:41:00", 60, 1, "first activity", "", 0), // in for 1 minutes
      TimeEntry("2016-04-13T12:00:00", 60, 1, "second activity", "", 0), // in for 1 minute
      TimeEntry("2016-04-13T12:01:00", 60, 1, "after second activity", "", 0), // in for 1 minute
      TimeEntry("2016-04-13T18:43:00", 60, 1, "third activity", "", 0), // in for 1 minute
      TimeEntry("2016-04-13T18:50:00", 60, 1, "late activity", "", 0) // out for 1 minute
    )

    DayLength.result(entries, dayStartsAt, dayEndsAt) shouldBe "2016-04-13: Worked from 09:41 till 18:44 for 4 minutes"
  }
} 
开发者ID:denyago,项目名称:work_day_length,代码行数:25,代码来源:DayLengthSpec.scala


示例12: FutureDemo

//设置package包名称以及导入依赖的类
package scalaDemo

import java.time.LocalTime

import scala.concurrent.Future
import java.time._
import java.time._
import scala.concurrent._
import scala.concurrent.duration._
import scala.concurrent._
import ExecutionContext.Implicits.global

object FutureDemo extends App {
  Future {
    Thread.sleep(10000)
    println(s"This is the future at ${LocalTime.now}")
  }
  println(s"This is the present at ${LocalTime.now}")

  Thread.sleep(11000)

  Future { for (i <- 1 to 100) { print("A"); Thread.sleep(10) } }
  Future { for (i <- 1 to 100) { print("B"); Thread.sleep(10) } }

  Thread.sleep(2000)

  val f = Future {
    Thread.sleep(10000)
    42
  }
  println(f)

  Thread.sleep(11000)

  println(f)

  val f23 = Future {
    if (LocalTime.now.getHour > 12)
      throw new Exception("too late")
    42
  }
  Thread.sleep(1000)
  println(f23)


  val f4 = Future { Thread.sleep(10000); 42 }
  val result = Await.result(f4, 11.seconds)
  println(result)

  val f2 = Future { Thread.sleep(10000); 42 }
  Await.ready(f2, 11.seconds)
  val Some(t) = f2.value
  println(t)
} 
开发者ID:tophua,项目名称:spark1.52,代码行数:55,代码来源:FutureDemo.scala


示例13: TemperatureChecker

//设置package包名称以及导入依赖的类
package io.tardieu.netwemo.checkers

import java.time.{DayOfWeek, LocalDateTime, LocalTime}

import akka.actor.Props
import com.typesafe.config.ConfigFactory
import io.tardieu.netwemo.Utils
import io.tardieu.netwemo.connectors.{NetatmoConnector, WemoConnector}

import scala.concurrent.Future

object TemperatureChecker {

  def props(wemoConnector: WemoConnector, netatmoConnector: NetatmoConnector): Props =
    Props(new TemperatureChecker(wemoConnector, netatmoConnector))

}

class TemperatureChecker private (val wemoConnector: WemoConnector, val netatmoConnector: NetatmoConnector)
  extends Checker {

  val conf = ConfigFactory.load.getConfig("temperature")

  // Those values should be read from the database
  val lowThreshold = conf.getDouble("lowThreshold").toFloat
  val highThreshold = conf.getDouble("highThreshold").toFloat
  val coldLowThreshold = conf.getDouble("coldLowThreshold").toFloat
  val coldHighThreshold = conf.getDouble("coldHighThreshold").toFloat
  val coldStartTime: LocalTime = LocalTime.of(conf.getInt("coldHourStart"), conf.getInt("coldMinuteStart"))
  val coldStopTime: LocalTime = LocalTime.of(conf.getInt("coldHourStop"), conf.getInt("coldMinuteStop"))

  override val deviceName = conf.getString("deviceName")

  private def isWorkingDay: Boolean =
    LocalDateTime.now.getDayOfWeek match {
      case DayOfWeek.SATURDAY | DayOfWeek.SUNDAY => false
      case _ => true
    }

  private def inColdHours(startTime: LocalTime, stopTime: LocalTime): Boolean = {
    val now = LocalTime.now()
    val b = Utils.inBetween(now, startTime, stopTime) && isWorkingDay
    log.debug("In cold hours: {}", b)
    b
  }

  override def checkValue: Future[Float] = netatmoConnector.getTemperature

  override def computeDesiredState(value: Float): Option[Boolean] = {
    inColdHours(coldStartTime, coldStopTime) match {
      case true => computeState(value, coldLowThreshold, coldHighThreshold)
      case false => computeState(value, lowThreshold, highThreshold)
    }
  }

} 
开发者ID:jacobtardieu,项目名称:Netwemo,代码行数:57,代码来源:TemperatureChecker.scala


示例14: HumidityChecker

//设置package包名称以及导入依赖的类
package io.tardieu.netwemo.checkers
import java.time.LocalTime

import akka.actor.Props
import com.typesafe.config.ConfigFactory
import io.tardieu.netwemo.Utils
import io.tardieu.netwemo.connectors.{NetatmoConnector, WemoConnector}

import scala.concurrent.Future

object HumidityChecker {

  def props(wemoConnector: WemoConnector, netatmoConnector: NetatmoConnector): Props =
    Props(new HumidityChecker(wemoConnector, netatmoConnector))

}

class HumidityChecker private (val wemoConnector: WemoConnector, val netatmoConnector: NetatmoConnector)
  extends Checker {

  val conf = ConfigFactory.load.getConfig("humidity")

  // Those values should be read from the database
  private val startTime: LocalTime = LocalTime.of(conf.getInt("startHour"), conf.getInt("stopMinute"))
  private val stopTime: LocalTime = LocalTime.of(conf.getInt("stopHour"), conf.getInt("stopMinute"))
  private val lowThreshold = conf.getInt("lowThreshold")
  private val highThreshold = conf.getInt("highThreshold")

  override def deviceName: String = conf.getString("deviceName")

  override def checkValue: Future[Float] = netatmoConnector.getHumidity

  private def inService(startTime: LocalTime, stopTime: LocalTime): Boolean = {
    val now = LocalTime.now()
    val b = Utils.inBetween(now, startTime, stopTime)
    log.debug(s"Humidity in service: {}", b)
    b
  }

  override def computeDesiredState(value: Float): Option[Boolean] = {
    inService(startTime, stopTime) match {
      case true => computeState(value, lowThreshold, highThreshold).map(!_) // We want to switch on the
        // deshumidifier if the value is too high
      case false => Some(false)
    }
  }
} 
开发者ID:jacobtardieu,项目名称:Netwemo,代码行数:48,代码来源:HumidityChecker.scala


示例15: UtilsSpec

//设置package包名称以及导入依赖的类
package io.tardieu.netwemo

import java.time.LocalTime

import org.scalatest.{FlatSpec, Matchers}

class UtilsSpec extends FlatSpec with Matchers {

  "The inBetween method" should
  "work with startTime before stopTime" in {
    val startTime = LocalTime.parse("08:00")
    val stopTime = LocalTime.parse("18:00")
    val before = LocalTime.parse("06:54")
    val during = LocalTime.parse("14:43")
    val after = LocalTime.parse("20:22")
    Utils.inBetween(before, startTime, stopTime) shouldBe false
    Utils.inBetween(during, startTime, stopTime) shouldBe true
    Utils.inBetween(after, startTime, stopTime) shouldBe false
  }
  it should "work with startTime after stopTime" in {
    val startTime = LocalTime.parse("22:00")
    val stopTime = LocalTime.parse("02:00")
    val before = LocalTime.parse("21:54")
    val during1 = LocalTime.parse("22:43")
    val during2 = LocalTime.parse("00:32")
    val after = LocalTime.parse("08:11")
    Utils.inBetween(before, startTime, stopTime) shouldBe false
    Utils.inBetween(during1, startTime, stopTime) shouldBe true
    Utils.inBetween(during2, startTime, stopTime) shouldBe true
    Utils.inBetween(after, startTime, stopTime) shouldBe false
  }

} 
开发者ID:jacobtardieu,项目名称:Netwemo,代码行数:34,代码来源:UtilsSpec.scala


示例16: EsTraitTest

//设置package包名称以及导入依赖的类
package orm.elasticsearch
import java.time.{LocalDate, LocalDateTime, LocalTime, ZoneId}

import org.scalatest.prop.TableDrivenPropertyChecks
import org.scalatest.{FunSuite, Matchers}
import webby.commons.time.StdDates

class EsTraitTest extends FunSuite with Matchers with TableDrivenPropertyChecks {
  test("LocalDateTimeTimestampConv packTime") {
    Table[LocalTime, Long](("LocalTime", "packed")
      , (LocalTime.of(19, 55, 1, 135), 195501000L)
      , (LocalTime.of(3, 25, 52, 123456789), 32552123L)
      , (LocalTime.of(0, 0, 0, 0), 0L)
    ).forEvery {case (localTime, packed) =>
      LocalDateTimeTimestampConv.packTime(localTime) shouldEqual packed
    }
  }

  test("LocalDateTimeTimestampConv unpackTime") {
    Table[Long, LocalTime](("packed", "LocalTime")
      , (195501000L, LocalTime.of(19, 55, 1, 0))
      , (32552123L, LocalTime.of(3, 25, 52, 123000000))
      , (0L, LocalTime.of(0, 0, 0, 0))
    ).forEvery {case (packed, localTime) =>
      LocalDateTimeTimestampConv.unpackTime(packed) shouldEqual localTime
    }
  }

  test("LocalDateTimeTimestampConv from") {
    Table[Long, LocalDateTime](("packed", "LocalDateTime")
      , (1447859405000L, StdDates.toLocalDateTime(1447859405000L, ZoneId.systemDefault())) // old format
      , (20151125032552123L, LocalDateTime.of(2015, 11, 25, 3, 25, 52, 123000000)) // new format
    ).forEvery {case (packed, localDateTime) =>
      LocalDateTimeTimestampConv.from(packed.asInstanceOf[AnyRef]) shouldEqual localDateTime
    }
  }

  test("LocalDateTimestampConv packDate/unpackDate") {
    Table[LocalDate, Long](("LocalDate", "packed")
      , (LocalDate.of(2005, 6, 5), 20050605000000000L)
      , (LocalDate.of(2015, 11, 25), 20151125000000000L)
      , (LocalDate.of(0, 1, 1), 101000000000L)
    ).forEvery {case (localDate, packed) =>
      LocalDateTimestampConv.packDate(localDate) shouldEqual packed
      LocalDateTimestampConv.unpackDate(packed) shouldEqual localDate
    }
  }

  test("LocalDateTimestampConv from") {
    Table[Long, LocalDate](("packed", "LocalDate")
      , (1447859405000L, StdDates.toLocalDate(1447859405000L, ZoneId.systemDefault())) // old format
      , (20151125032552123L, LocalDate.of(2015, 11, 25)) // new format
    ).forEvery {case (packed, localDate: LocalDate) =>
      LocalDateTimestampConv.from(packed.asInstanceOf[AnyRef]) shouldEqual localDate
    }
  }
} 
开发者ID:citrum,项目名称:webby,代码行数:58,代码来源:EsTraitTest.scala


示例17: TZDBSpec

//设置package包名称以及导入依赖的类
package kuyfi

import java.time.{DayOfWeek, LocalTime, Month, LocalDateTime}

import kuyfi.TZDB._
import org.scalatest.{FlatSpec, Matchers}

import scalaz._
import Scalaz._

class TZDBSpec extends FlatSpec with Matchers {
  "Year ordering" should
    "orders given years" in {
      (GivenYear(2001): RuleYear) <= (GivenYear(2002): RuleYear) shouldBe true
      (GivenYear(2004): RuleYear) >= (GivenYear(2002): RuleYear) shouldBe true
      (GivenYear(2004): RuleYear) == (GivenYear(2004): RuleYear) shouldBe true
    }
    it should "make everything less than Maximum" in {
      (GivenYear(2001): RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Minimum: RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Only: RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Maximum: RuleYear) >= (Maximum: RuleYear) && (Maximum: RuleYear) <= (Maximum: RuleYear) shouldBe true
    }
    it should "make everything more than Maximum" in {
      (GivenYear(2001): RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Minimum: RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Only: RuleYear) <= (Maximum: RuleYear) shouldBe true
      (Minimum: RuleYear) >= (Minimum: RuleYear) && (Minimum: RuleYear) <= (Minimum: RuleYear) shouldBe true
    }
    it should "make everything equal to Only" in {
      (GivenYear(2001): RuleYear) >= (Only: RuleYear) shouldBe true
      (Minimum: RuleYear) >=(Only: RuleYear) shouldBe true
      (Maximum: RuleYear) >= (Only: RuleYear) shouldBe true
      (Only: RuleYear) <= (Only: RuleYear) && (Only: RuleYear) >= (Only: RuleYear) shouldBe true
    }

  "Until" should
    "calculate date time" in {
      val until = Until(1998,Some(Month.APRIL),Some(AfterWeekday(DayOfWeek.SUNDAY,1)),Some(AtWallTime(LocalTime.of(3, 0), endOfDay = false)))
      until.toDateTime shouldBe LocalDateTime.of(1998, Month.APRIL, 5, 3, 0)
      until.toDateTime shouldBe LocalDateTime.of(1998, Month.APRIL, 5, 3, 0)
    }

  "On" should
    "calculate day on a year" in {
      val on = AfterWeekday(DayOfWeek.SUNDAY, 1)
      on.dayOnYear(1998, Month.APRIL) shouldBe 5
      val on2 = DayOfTheMonth(5)
      on2.dayOnYear(1998, Month.APRIL) shouldBe 5
    }
} 
开发者ID:cquiroz,项目名称:kuyfi,代码行数:52,代码来源:TZDBSpec.scala


示例18: zoned

//设置package包名称以及导入依赖的类
package dtc.cats.instances

import java.time.{DayOfWeek, Duration, LocalDate, LocalTime}

import cats.functor.Invariant
import dtc.{Offset, TimeZoneId, Zoned}

object zoned extends CatsZonedInstances

trait CatsZonedInstances {
  implicit val zonedInvariant: Invariant[Zoned] = new Invariant[Zoned] {
    def imap[A, B](ev: Zoned[A])(f: A => B)(g: B => A): Zoned[B] = new Zoned[B] {
      def compare(x: B, y: B): Int = ev.compare(g(x), g(y))
      def zone(t: B): TimeZoneId = ev.zone(g(t))
      def millisecond(x: B): Int = ev.millisecond(g(x))
      def second(t: B): Int = ev.second(g(t))
      def minute(t: B): Int = ev.minute(g(t))
      def hour(t: B): Int = ev.hour(g(t))
      def dayOfMonth(t: B): Int = ev.dayOfMonth(g(t))
      def dayOfWeek(x: B): DayOfWeek = ev.dayOfWeek(g(x))
      def month(t: B): Int = ev.month(g(t))
      def year(t: B): Int = ev.year(g(t))
      def of(date: LocalDate, time: LocalTime, zone: TimeZoneId): B = f(ev.of(date, time, zone))
      def withZoneSameInstant(x: B, zone: TimeZoneId): B = f(ev.withZoneSameInstant(g(x), zone))
      def withZoneSameLocal(x: B, zone: TimeZoneId): B = f(ev.withZoneSameLocal(g(x), zone))
      def offset(x: B): Offset = ev.offset(g(x))
      def date(x: B): LocalDate = ev.date(g(x))
      def time(x: B): LocalTime = ev.time(g(x))
      def plus(x: B, d: Duration): B = f(ev.plus(g(x), d))
      def minus(x: B, d: Duration): B = f(ev.minus(g(x), d))
      def plusDays(x: B, days: Int): B = f(ev.plusDays(g(x), days))
      def plusMonths(x: B, months: Int): B = f(ev.plusMonths(g(x), months))
      def plusYears(x: B, years: Int): B = f(ev.plusYears(g(x), years))
      def withYear(x: B, year: Int): B = f(ev.withYear(g(x), year))
      def withMonth(x: B, month: Int): B = f(ev.withMonth(g(x), month))
      def withDayOfMonth(x: B, dayOfMonth: Int): B = f(ev.withDayOfMonth(g(x), dayOfMonth))
      def withHour(x: B, hour: Int): B = f(ev.withHour(g(x), hour))
      def withMinute(x: B, minute: Int): B = f(ev.withMinute(g(x), minute))
      def withSecond(x: B, second: Int): B = f(ev.withSecond(g(x), second))
      def withMillisecond(x: B, millisecond: Int): B = f(ev.withMillisecond(g(x), millisecond))
      def yearsUntil(x: B, until: B): Long = ev.yearsUntil(g(x), g(until))
      def monthsUntil(x: B, until: B): Long = ev.monthsUntil(g(x), g(until))
      def daysUntil(x: B, until: B): Long = ev.daysUntil(g(x), g(until))
      def hoursUntil(x: B, until: B): Long = ev.hoursUntil(g(x), g(until))
      def minutesUntil(x: B, until: B): Long = ev.minutesUntil(g(x), g(until))
      def secondsUntil(x: B, until: B): Long = ev.secondsUntil(g(x), g(until))
      def millisecondsUntil(x: B, until: B): Long = ev.millisecondsUntil(g(x), g(until))
    }
  }
} 
开发者ID:vpavkin,项目名称:dtc,代码行数:51,代码来源:zoned.scala


示例19: Main

//设置package包名称以及导入依赖的类
package dtc.examples

import java.time.{Duration, LocalDate, LocalTime}

import dtc.instances.jsDate._
import dtc.js.JSDate

import scala.scalajs.js.JSApp

// scalastyle:off
object Main extends JSApp {

  def main() = {
    val calendar = Calendar(List(
      CalendarEvent(
        JSDate.of(LocalDate.now(), LocalTime.of(10, 0)),
        JSDate.of(LocalDate.now(), LocalTime.of(11, 0)),
        "Breakfast"
      ),
      CalendarEvent(
        JSDate.of(LocalDate.now().plusDays(2), LocalTime.of(12, 0)),
        JSDate.of(LocalDate.now().plusDays(2), LocalTime.of(14, 0)),
        "Meeting"
      ),
      CalendarEvent(
        JSDate.of(2016, 10, 9, 11, 0),
        JSDate.of(2016, 10, 9, 11, 0),
        "Birthday party"
      )
    ))

    println(calendar.eventsAfter(JSDate.now).mkString(", "))
    println(calendar.onlyWorkDays.mkString(", "))

    val period = Period(JSDate.now, JSDate.now.plus(Duration.ofDays(1L)))
    println(period.durationInMinutes)
    println(period.durationInSeconds)
    println(period.hours.mkString("\n"))
  }
} 
开发者ID:vpavkin,项目名称:dtc,代码行数:41,代码来源:Main.scala


示例20: Main

//设置package包名称以及导入依赖的类
package dtc.examples

import java.time.{LocalDate, LocalDateTime, LocalTime, Month}

import dtc.instances.localDateTime._

// scalastyle:off
object Main extends App {

  val calendar = Calendar(List(
    CalendarEvent(
      LocalDateTime.of(LocalDate.now(), LocalTime.of(10, 0)),
      LocalDateTime.of(LocalDate.now(), LocalTime.of(11, 0)),
      "Breakfast"
    ),
    CalendarEvent(
      LocalDateTime.of(LocalDate.now().minusDays(2), LocalTime.of(12, 0)),
      LocalDateTime.of(LocalDate.now().minusDays(2), LocalTime.of(14, 0)),
      "Meeting"
    ),
    CalendarEvent(
      LocalDateTime.of(2016, Month.OCTOBER, 9, 11, 0),
      LocalDateTime.of(2016, Month.OCTOBER, 9, 11, 0),
      "Birthday party"
    )
  ))

  println(calendar.eventsAfter(LocalDateTime.now().minusDays(1L)).mkString(", "))
  println(calendar.onlyWorkDays.mkString(", "))

  val period = Period(LocalDateTime.now(), LocalDateTime.now().plusDays(1L))
  println(period.durationInMinutes)
  println(period.durationInSeconds)
  println(period.hours.mkString("\n"))
} 
开发者ID:vpavkin,项目名称:dtc,代码行数:36,代码来源:Main.scala



注:本文中的java.time.LocalTime类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Scala VectorUDT类代码示例发布时间:2022-05-23
下一篇:
Scala ConsumerSettings类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap