当前位置: 首页>>代码示例>>Scala>>正文


Scala LocalDateTime类代码示例

本文整理汇总了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)
    }
  }
} 
开发者ID:knoldus,项目名称:lagom-scala-wordcount.g8,代码行数:32,代码来源:MessageEntity.scala

示例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)})")
} 
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:34,代码来源:Encoders.scala

示例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) 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:61,代码来源:Player.scala

示例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]
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:20,代码来源:HermesGameFile.scala

示例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)
  }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:27,代码来源:HermesGameConfig.scala

示例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.")
    }
  }
} 
开发者ID:Morgan-Stanley,项目名称:proton,代码行数:60,代码来源:UsersProtocol.scala

示例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)

} 
开发者ID:astahiam,项目名称:pv_,代码行数:45,代码来源:SolarInfoStorage.scala

示例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
    }
  }

} 
开发者ID:dborisenko,项目名称:data-train,代码行数:46,代码来源:ResourceJdbcComponent.scala

示例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)
} 
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:26,代码来源:Decoders.scala

示例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))
      }
    )
  }

} 
开发者ID:mindfulmachines,项目名称:unus,代码行数:36,代码来源:Repository.scala

示例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"
    }
  }
} 
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:38,代码来源:Rfc3339UtilTest.scala

示例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)
} 
开发者ID:vitalcode,项目名称:date-time-range-parser,代码行数:31,代码来源:ExamplesSupport.scala

示例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)

} 
开发者ID:shinharad,项目名称:scala-json-lab,代码行数:32,代码来源:DateTimeExample.scala

示例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)
  }
} 
开发者ID:ayuzhanin,项目名称:test-akka,代码行数:27,代码来源:MessagesPerSecCounterActor.scala

示例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"
} 
开发者ID:ovotech,项目名称:comms-monitor-service,代码行数:52,代码来源:CanarySMSAsserter.scala


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