本文整理汇总了Scala中java.time.LocalDateTime类的典型用法代码示例。如果您正苦于以下问题:Scala LocalDateTime类的具体用法?Scala LocalDateTime怎么用?Scala LocalDateTime使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了LocalDateTime类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: MessageEntity
//设置package包名称以及导入依赖的类
package sample.helloworldconsumer.impl
import java.time.LocalDateTime
import akka.Done
import com.lightbend.lagom.scaladsl.persistence.PersistentEntity
class MessageEntity extends PersistentEntity {
override type Command = MessageCommand[_]
override type Event = MessageEvent
override type State = MessageState
override def initialState = MessageState("", LocalDateTime.now().toString)
override def behavior: Behavior = {
case MessageState(msg, _) => Actions().onCommand[SaveNewMessage, Done]{
case (SaveNewMessage(msg), ctx, state) =>
println(s"observe new message from kafka and save ${msg}")
ctx.thenPersist( MessageSaved(msg)) { msgSaved: MessageSaved =>
ctx.reply(Done)
}
}.onEvent {
case (MessageSaved(message), state) =>
println(s"MessgaeSaved event fire ...")
MessageState(message, LocalDateTime.now().toString)
}
}
}
示例2: genericEncoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.sql.{PreparedStatement, Types}
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
trait Encoders {
this: JdbcSource[_, _] =>
import Formatters._
private def genericEncoder[T](valueToString: (T => String)): Encoder[T] = {
new Encoder[T] {
override def apply(index: Int, value: T, row: PreparedStatement) = {
val sqlLiteral = valueToString(value)
row.setObject(index + 1, sqlLiteral, Types.OTHER)
row
}
}
}
private def tuple[T](t: (T, T))(valToStr: T => String) = s"[${valToStr(t._1)}, ${valToStr(t._2)}]"
implicit val dateTupleEncoder: Encoder[(Date, Date)] = genericEncoder(tuple(_)(formatDate))
implicit val localDateTimeTupleEncoder: Encoder[(LocalDateTime, LocalDateTime)] =
genericEncoder(tuple(_)(formatLocalDateTime))
implicit val zonedDateTimeTupleEncoder: Encoder[(ZonedDateTime, ZonedDateTime)] =
genericEncoder(tuple(_)(formatZonedDateTime))
implicit val dateTimeTupleEncoder: Encoder[(LocalDate, LocalDate)] =
genericEncoder(t => s"[${formatLocalDate(t._1)}, ${formatLocalDate(t._2)})")
}
示例3: Player
//设置package包名称以及导入依赖的类
package proton.game
import java.time.format.DateTimeFormatter
import java.time.temporal.ChronoUnit
import java.time.{Clock, LocalDateTime}
import java.util.{Base64, UUID}
import javax.crypto.spec.SecretKeySpec
import javax.crypto.{KeyGenerator, Mac}
@SerialVersionUID(1L)
class Player(val id: UUID, val name: String, val secret: String) extends Serializable {
override def hashCode = id.hashCode()
override def equals(other: Any) = other match {
case that: Player => this.id == that.id
case _ => false
}
override def toString = s"$name ($id)"
def identity = PlayerIdentity(id, name)
def isAuthorized(time: LocalDateTime, signature: String): Boolean = {
val seconds = ChronoUnit.SECONDS.between(time, LocalDateTime.now(Clock.systemUTC()))
if (seconds < -300 || seconds > 300) {
false
} else {
val secretKeySpec = new SecretKeySpec(secret.getBytes, "HmacSHA256")
val mac = Mac.getInstance("HmacSHA256")
mac.init(secretKeySpec)
val message = id.toString.toLowerCase + "|" + time.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
val hmac = mac.doFinal(message.getBytes("UTF-8"))
val encoded = Base64.getEncoder.encodeToString(hmac)
encoded.equalsIgnoreCase(signature)
}
}
}
object Player {
def apply(name: String) = new Player(UUID.randomUUID(), name, generateKey)
def apply(id: UUID, name: String) = new Player(id, name, generateKey)
private def generateKey: String = {
val keyGenerator: KeyGenerator = KeyGenerator.getInstance("HmacSHA256")
Base64.getEncoder.encodeToString(keyGenerator.generateKey().getEncoded)
}
def apply(id: UUID, name: String, secret: String) = new Player(id, name, secret)
def apply(identity: PlayerIdentity) = new Player(identity.id, identity.name, generateKey)
def apply(identity: PlayerIdentity, secret: String) = new Player(identity.id, identity.name, secret)
}
case class PlayerIdentity(id: UUID, name: String)
示例4: HermesGameFileEntry
//设置package包名称以及导入依赖的类
package proton.game.hermes
import java.time.LocalDateTime
import java.util.UUID
import proton.game.hermes.HermesGameRegion.HermesGameRegion
case class HermesGameFileEntry(time: LocalDateTime, values: Map[HermesGameRegion, Int])
trait HermesGameFile {
def id: UUID
def settings: Option[HermesGameFileSettings]
def getEntry(tick: Int): Option[HermesGameFileEntry]
def totalTicks: Int
def complete: Boolean
}
trait HermesGameFileRepository {
def getById(id: UUID): Option[HermesGameFile]
}
示例5: HermesGameTickerConfig
//设置package包名称以及导入依赖的类
package proton.game.hermes
import java.time.LocalDateTime
import java.util.UUID
import proton.game._
import scala.concurrent.duration.{FiniteDuration, _}
class HermesGameTickerConfig(val gameFile: UUID, override val players: Seq[Player],
override val startTime: Option[LocalDateTime],
override val tickDuration: FiniteDuration,
override val timeoutDuration: Option[FiniteDuration]) extends GameTickerConfig {
override val minPlayers: Option[Int] = Some(1)
override val maxPlayers: Option[Int] = None
}
case class HermesGameTickerConfigFactory(gameFile: UUID, players: Seq[PlayerIdentity], startTime: Option[LocalDateTime],
tickDuration: Option[FiniteDuration], timeoutDuration: Option[FiniteDuration])
extends GameTickerConfigFactory[HermesGameTickerConfig] {
override def build(): HermesGameTickerConfig = {
new HermesGameTickerConfig(gameFile, players.map(p => Player(p)), startTime,
tickDuration.getOrElse(200.milliseconds), timeoutDuration)
}
}
示例6: getStackTrace
//设置package包名称以及导入依赖的类
package proton.users
import java.io.{PrintWriter, StringWriter}
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import spray.json.{JsValue, JsonFormat, _}
trait UsersProtocol {
private def getStackTrace(t: Throwable) = {
val sw: StringWriter = new StringWriter()
val pw: PrintWriter = new PrintWriter(sw)
t.printStackTrace(pw)
sw.toString
}
implicit object ThrowableWriter extends RootJsonWriter[Throwable] {
def write(t: Throwable) = JsObject(
"message" -> JsString(t.getMessage),
"cause" -> t.getCause.toJson,
"stackTrace" -> JsString(getStackTrace(t))
)
}
implicit object MessageFormat extends RootJsonWriter[Message] {
def write(m: Message) = JsObject(
"summary" -> JsString(m.summary),
"errorCode" -> JsNumber(m.errorCode)
)
}
implicit object ValidationFormat extends RootJsonWriter[Validation] {
def write(v: Validation) = {
val fields = Seq[Option[JsField]](
Some("message" -> JsString(v.message)),
Some("errorCode" -> JsNumber(v.errorCode)),
v.exception.map(exception => "exception" -> exception.toJson)
)
JsObject(fields.flatten: _*)
}
}
implicit object UUIDFormat extends JsonFormat[UUID] {
def write(uuid: UUID) = JsString(uuid.toString)
def read(value: JsValue) = value match {
case JsString(uuid) => UUID.fromString(uuid)
case _ => deserializationError("UUID expected.")
}
}
implicit object LocalDateTimeFormat extends JsonFormat[LocalDateTime] {
def write(dateTime: LocalDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
def read(value: JsValue) = value match {
case JsString(dateTime) => LocalDateTime.parse(dateTime, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
case _ => deserializationError("LocalDateTime expected.")
}
}
}
示例7: SolarInfoStorage
//设置package包名称以及导入依赖的类
package storages
import java.time.LocalDateTime
import java.util.UUID
import javax.inject.Inject
import models.SolarInfo
import play.api.db.slick.DatabaseConfigProvider
import slick.driver.JdbcProfile
import support.database.PvPostgresDriver.api._
import scala.concurrent.{ExecutionContext, Future}
class SolarInfoStorage(tag: Tag) extends Table[SolarInfo](tag, "solar_info") {
def id = column[UUID]("id", O.PrimaryKey)
def monitoring_time = column[LocalDateTime]("monitoring_time")
def irradiance = column[Double]("irradiance")
def panel_temp = column[Double]("panel_temp")
def ambient_temp = column[Double]("ambient_temp")
def wind_speed = column[Double]("wind_speed")
def wind_dir = column[Double]("wind_dir")
def sum_energy = column[Double]("sum_energy")
override def * = (id, monitoring_time, irradiance, panel_temp, ambient_temp, wind_speed, wind_dir, sum_energy) <> (SolarInfo.tupled, SolarInfo.unapply)
}
object SolarInfoStorage {
val tableQuery = TableQuery[SolarInfoStorage]
}
class SolarInfoRepository @Inject()(protected val dbConfigProvider: DatabaseConfigProvider)(implicit ec: ExecutionContext) {
val dbconfig = dbConfigProvider.get[JdbcProfile]
val db = dbconfig.db
private val SolarInfos = SolarInfoStorage.tableQuery
def findById(id: UUID): Future[SolarInfo] = db.run(SolarInfos.filter(_.id === id).result.head)
def all(): Future[List[SolarInfo]] = db.run(SolarInfos.to[List].result)
def create(solarInfo: SolarInfo): Future[UUID] = db.run(SolarInfos returning SolarInfos.map(_.id) += solarInfo)
def delete(id: UUID): Future[Boolean] = db.run(SolarInfos.filter(_.id === id).delete).map(_ > 0)
}
示例8: LocalDateTimeColumnType
//设置package包名称以及导入依赖的类
package com.dbrsn.datatrain.slick
import java.time.LocalDateTime
import cats.~>
import com.dbrsn.datatrain.dsl.meta.ResourceDSL
import com.dbrsn.datatrain.dsl.meta.ResourceDSL.Create
import com.dbrsn.datatrain.model.Resource
import com.dbrsn.datatrain.model.ResourceId
import shapeless.Generic
import shapeless.HNil
import slick.jdbc.JdbcProfile
import slick.lifted.ProvenShape
import slickless._
case class LocalDateTimeColumnType[P <: JdbcProfile](implicit columnType: P#BaseColumnType[LocalDateTime])
trait ResourceJdbcComponent[P <: JdbcProfile] {
val localDateTimeColumnType: LocalDateTimeColumnType[P]
val profile: P
import profile.api._
import localDateTimeColumnType._
type ResourceJdbcDSL[A] = ResourceDSL[A]
def resourceTableName: String = "dt_resource"
class ResourceTable(tag: Tag) extends Table[Resource](tag, resourceTableName) {
def id: Rep[ResourceId] = column[ResourceId]("id", O.PrimaryKey)
def createdAt: Rep[LocalDateTime] = column[LocalDateTime]("created_at")
override def * : ProvenShape[Resource] = (id :: createdAt :: HNil).mappedWith(Generic[Resource])
}
lazy val resourceTableQuery: TableQuery[ResourceTable] = TableQuery[ResourceTable]
object ResourceInterpreter extends (ResourceJdbcDSL ~> DBIO) {
override def apply[A](fa: ResourceJdbcDSL[A]): DBIO[A] = fa match {
case Create(resource) => (resourceTableQuery returning resourceTableQuery.map(_.id) into ((v, _) => v)) += resource
}
}
}
示例9: decoder
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.range.datetime
import java.time.{LocalDate, ZonedDateTime, LocalDateTime}
import java.util.Date
import io.getquill.source.jdbc.JdbcSource
import io.gustavoamigo.quill.pgsql.encoding.GenericDecoder
trait Decoders extends GenericDecoder {
this: JdbcSource[_, _] =>
import Formatters._
private val rangePattern = """([0-9\-\+\. :]+)""".r
private def decoder[T](map: String => T) = decode(s => {
val dates = rangePattern.findAllIn(s).toList
(map(dates.head), map(dates.last))
})
implicit val dateTupleDecoder: Decoder[(Date, Date)] = decoder(parseDate)
implicit val localDateTimeTupleDecoder: Decoder[(LocalDateTime, LocalDateTime)] = decoder(parseLocalDateTime)
implicit val zonedDateTimeTupleDecoder: Decoder[(ZonedDateTime, ZonedDateTime)] = decoder(parseZonedDateTime)
implicit val localDateTupleDecoder: Decoder[(LocalDate, LocalDate)] = decoder(parseLocalDate)
}
示例10: Repository
//设置package包名称以及导入依赖的类
package unus.db
import java.sql.Timestamp
import java.time.LocalDateTime
class Repository(private val db: DbContext) {
import db._
private implicit val timestampEncoder = MappedEncoding[LocalDateTime, Timestamp](Timestamp.valueOf)
private implicit val timestampDecoder = MappedEncoding[Timestamp, LocalDateTime](_.toLocalDateTime)
def patientsExist(): Boolean = {
run(
quote {
query[Patient].size
}
) > 0
}
def getModel(model: String): Model = {
run(
quote {
query[Model].filter(_.model == lift(model)).take(1)
}
).head
}
def createBlocker(blocker: Blocker): Long = {
run(
quote {
query[Blocker].insert(lift(blocker))
}
)
}
}
示例11: Rfc3339UtilTest
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.time.{ LocalDateTime, ZoneId, ZoneOffset, ZonedDateTime }
import org.scalatest.{ FunSpec, MustMatchers }
class Rfc3339UtilTest extends FunSpec with MustMatchers {
val dtz = ZoneId.of("UTC")
val offset = ZoneOffset.UTC
//noinspection ScalaStyle
val date = ZonedDateTime.of(LocalDateTime.ofEpochSecond(1451911387L, 0, offset), dtz)
describe("Rfc3339UtilTest") {
it("should parse RFC3339 DateTime") {
Rfc3339Util.parseDateTime("2007-05-01T15:43:26-00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452-01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T16:43:26.345200Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+01:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T14:43:26.345200Z[UTC]"
Rfc3339Util.parseDateTime("2007-05-01T15:43:26.3452+00:00").withZoneSameInstant(dtz).toString mustBe "2007-05-01T15:43:26.345200Z[UTC]"
}
it("should parse RFC3339 Date") {
Rfc3339Util.parseDate("2007-05-01").toString mustBe "2007-05-01"
Rfc3339Util.parseDate("2008-05-01").toString mustBe "2008-05-01"
Rfc3339Util.parseDate("2007-08-01").toString mustBe "2007-08-01"
Rfc3339Util.parseDate("2007-05-08").toString mustBe "2007-05-08"
}
it("should write DateTime") {
Rfc3339Util.writeDateTime(date) mustBe "2016-01-04T12:43:07.0000+0000"
}
it("should write Date") {
Rfc3339Util.writeDate(date.toLocalDate) mustBe "2016-01-04"
}
}
}
示例12: now
//设置package包名称以及导入依赖的类
package uk.vitalcode.dateparser
import java.time.LocalDateTime
import org.scalatest._
import org.scalatest.matchers.{MatchResult, Matcher}
trait ExamplesSupport extends fixture.FreeSpec with fixture.TestDataFixture with Matchers {
protected val currentDate: LocalDateTime
private val dateTimeProvider = new DateTimeProvider {
override def now: LocalDateTime = currentDate
}
private def parseAs(right: List[DateTimeInterval]): Matcher[String] = new Matcher[String] {
def apply(left: String): MatchResult = {
val actual = DateTimeInterval.of(left, dateTimeProvider)
MatchResult(
actual == right,
s"String [$left] results in [$actual] which is not the same as expected [$right]",
s"String [$left] results in $right but it must not"
)
}
}
protected def expected(expectation: DateTimeInterval*) =
(text: FixtureParam) => text.name should parseAs(expectation.toList)
}
示例13: DateTimeModel
//设置package包名称以及导入依赖的类
package com.github.shinharad.scalajsonlab.circe
import java.time.{LocalDate, LocalDateTime}
case class DateTimeModel(
date: LocalDate,
dateTime: LocalDateTime
)
object DateTimeExample extends App {
import io.circe._
import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._
import io.circe.java8.time._
val original = DateTimeModel(
LocalDate.now(),
LocalDateTime.now()
)
// Encode
val encodeData: String = original.asJson.spaces2
println(encodeData)
// Decode
val decodedData: Either[Error, DateTimeModel] = decode[DateTimeModel](encodeData)
println(decodedData)
}
示例14: MessagesPerSecCounterActor
//设置package包名称以及导入依赖的类
package org.remote.app.sender
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit._
import akka.actor.{Actor, ActorRef}
import org.remote.app.messaging.Statistics
class MessagesPerSecCounterActor extends Actor {
def updateStatistics(stat: Statistics, map: Map[ActorRef, Statistics]) = {
val now = LocalDateTime.now
val updated = (map + (sender() -> stat)).filter { case (_, value) => Math.abs(MILLIS.between(value.date, now)) < 1000 }
val messagesPerSecond = updated.values.map(_.number).sum
println(messagesPerSecond)
context become counting(updated)
}
override def receive: Receive = counting(Map[ActorRef, Statistics]())
def counting(map: Map[ActorRef, Statistics]): Receive = {
case stat: Statistics =>
updateStatistics(stat, map)
}
}
示例15: CanarySMSAsserter
//设置package包名称以及导入依赖的类
package com.ovoenergy.comms.monitor.canary.sms.asserter
import java.time.LocalDateTime
import com.ovoenergy.comms.monitor.canary.sms.client.Twilio.Message
import com.ovoenergy.comms.monitor.logging.LoggingWithMDC
import scala.util.control.NonFatal
object CanarySMSAsserter extends LoggingWithMDC {
def apply(canaryMobileNumber: String, smsClient: (String, LocalDateTime) => Option[Either[String, Message]])(
generatedTime: LocalDateTime,
traceToken: String): Either[Seq[String], Boolean] = {
try {
smsClient(traceToken, generatedTime) match {
case None => Right(false)
case Some(result) =>
result match {
case Left(error) => Left(Seq(error))
case Right(message) =>
val errors = Seq(
checkBodyForErrors(traceToken, message),
checkSenderForErrors(message)
).flatten
if (errors.isEmpty) Right(true)
else Left(errors)
}
}
} catch {
case NonFatal(ex) =>
logError(traceToken, "Error retrieving canary sms from client", ex)
Right(false)
}
}
private def checkBodyForErrors(traceToken: String, sms: Message): Option[String] = {
val expContent = s"This is a canary comm with trace token $traceToken"
if (sms.body == expContent) None
else Some(s"SMS content not as expected, expected '$expContent' but was '${sms.body}'")
}
private def checkSenderForErrors(sms: Message): Option[String] = {
val expSender = "OVO Energy"
if (sms.from == expSender) None
else Some(s"SMS sender not as expected, expected '$expSender' but was '${sms.from}'")
}
override def loggerName: String = "CanarySMSAsserter"
}