本文整理汇总了Scala中java.time.LocalTime类的典型用法代码示例。如果您正苦于以下问题:Scala LocalTime类的具体用法?Scala LocalTime怎么用?Scala LocalTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LocalTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
}
}
}
}
示例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
}
}
示例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)
}
}
示例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)
}
}
示例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)
}
}
示例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
}
}
}
}
示例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)
}
}
示例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))
}
}
示例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"
}
示例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
}
}
示例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"
}
}
示例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)
}
示例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)
}
}
}
示例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)
}
}
}
示例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
}
}