本文整理汇总了Scala中java.time.format.DateTimeFormatter类的典型用法代码示例。如果您正苦于以下问题:Scala DateTimeFormatter类的具体用法?Scala DateTimeFormatter怎么用?Scala DateTimeFormatter使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTimeFormatter类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Scala代码示例。
示例1: Rfc3339Util
//设置package包名称以及导入依赖的类
package de.zalando.play.controllers
import java.time.format.{ DateTimeFormatter, DateTimeParseException }
import java.time.{ LocalDate, ZoneId, ZonedDateTime }
object Rfc3339Util {
private val fullDate = DateTimeFormatter.ofPattern("yyyy-MM-dd")
private val shortDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
private val shortDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'")
private val fullDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'")
private val dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZ")
def parseDateTime(datestring: String): ZonedDateTime =
if (datestring.endsWith("Z") || datestring.endsWith("z")) parseFull(datestring)
else parseParts(datestring)
def parseDate(datestring: String): LocalDate =
LocalDate.parse(datestring, fullDate)
def writeDate(date: LocalDate): String = fullDate.format(date)
def writeDateTime(date: ZonedDateTime): String = dateTime.format(date)
private def parseParts(datestring: String): ZonedDateTime = {
//step one, split off the timezone.
val sepChar = if (datestring.indexOf('+') > 0) '+' else '-'
val firstpart = datestring.substring(0, datestring.lastIndexOf(sepChar.toInt))
val secondpart = datestring.substring(datestring.lastIndexOf(sepChar.toInt))
//step two, remove the colon from the timezone offset
val thirdpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1)
val dstring = firstpart + thirdpart
try {
ZonedDateTime.parse(dstring, shortDateTime)
} catch {
case pe: DateTimeParseException =>
ZonedDateTime.parse(dstring, dateTime)
}
}
private def parseFull(datestring: String): ZonedDateTime = {
val z = ZoneId.systemDefault()
try {
ZonedDateTime.parse(datestring, shortDTWithTicks.withZone(z))
} catch {
case p: DateTimeParseException => ZonedDateTime.parse(datestring, fullDTWithTicks.withZone(z))
}
}
}
开发者ID:LappleApple,项目名称:api-first-hand,代码行数:52,代码来源:Rfc3339Util.scala
示例2: LocalDateTimeCoercionViolation
//设置package包名称以及导入依赖的类
package io.soheila.cms.api
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Locale
import sangria.ast.StringValue
import sangria.schema.ScalarType
import sangria.validation.ValueCoercionViolation
import scala.util.{ Failure, Success, Try }
package object graphql {
case object LocalDateTimeCoercionViolation extends ValueCoercionViolation("Date value expected")
case object LocaleCoercionViolation extends ValueCoercionViolation("Locale value expected")
private[graphql] def parseLocalDateTime(s: String) = Try(LocalDateTime.parse(s)) match {
case Success(date) => Right(date)
case Failure(_) => Left(LocalDateTimeCoercionViolation)
}
private[graphql] def parseLocale(s: String) = Try(Locale.forLanguageTag(s)) match {
case Success(locale) => Right(locale)
case Failure(_) => Left(LocaleCoercionViolation)
}
val LocalDateTimeType = ScalarType[LocalDateTime](
"LocalDateTime",
coerceOutput = (value, caps) => value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME),
coerceUserInput = {
case s: String => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocalDateTime(s)
case _ => Left(LocalDateTimeCoercionViolation)
}
)
val LocaleType = ScalarType[Locale](
"Locale",
coerceOutput = (value, caps) => value.toLanguageTag,
coerceUserInput = {
case s: String => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
},
coerceInput = {
case StringValue(s, _, _) => parseLocale(s)
case _ => Left(LocaleCoercionViolation)
}
)
}
开发者ID:esfand-r,项目名称:soheila-cm,代码行数:53,代码来源:package.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: 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
示例5: putStatus
//设置package包名称以及导入依赖的类
package org.wex.cmsfs.common.monitor
import java.time.format.DateTimeFormatter
import java.time.{ZoneOffset, ZonedDateTime}
import com.redis.RedisClient
import play.api.libs.json._
trait MonitorStatus {
val r = new RedisClient("redis.cmsfs.org", 6379)
def putStatus(id: Int, stage: String)(state: Boolean, result: String) = {
val stageStatus = CoreMonitorStageStatus(state, result)
val key = s"${id}_${stage}"
r.set(key, Json.toJson(stageStatus).toString())
}
}
case class CoreMonitorStatus(id: Int, category: String, name: String, metric: String,
collect: CoreMonitorCollectStatus,
analyze: Option[CoreMonitorAnalyzeStatus],
Alarm: Option[CoreMonitorAlarmStatus])
object CoreMonitorStatus {
implicit val format: Format[CoreMonitorStatus] = Json.format
}
case class CoreMonitorStageStatus(state: Boolean, result: String,
timestamp: String = ZonedDateTime.now(ZoneOffset.ofHours(8)).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:m:s")))
object CoreMonitorStageStatus {
implicit val format: Format[CoreMonitorStageStatus] = Json.format
}
case class CoreMonitorCollectStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorCollectStatus {
implicit val format: Format[CoreMonitorCollectStatus] = Json.format
}
case class CoreMonitorAnalyzeStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorAnalyzeStatus {
implicit val format: Format[CoreMonitorAnalyzeStatus] = Json.format
}
case class CoreMonitorAlarmStatus(state: Boolean, timestamp: String, result: String)
object CoreMonitorAlarmStatus {
implicit val format: Format[CoreMonitorAlarmStatus] = Json.format
}
开发者ID:shinhwagk,项目名称:cmsfs,代码行数:53,代码来源:MonitorStatus.scala
示例6: StdOutLogger
//设置package包名称以及导入依赖的类
package knot.core.logging
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import scala.util.control.NoStackTrace
object StdOutLogger {
final val errorLevel = 1
final val warningLevel = 2
final val infoLevel = 3
final val debugLevel = 4
}
case class StdOutLogger(name: String, logLevel: Int = 1) extends Logger {
override def isErrorEnabled: Boolean = logLevel >= StdOutLogger.errorLevel
override def isWarningEnabled: Boolean = logLevel >= StdOutLogger.warningLevel
override def isInfoEnabled: Boolean = logLevel >= StdOutLogger.infoLevel
override def isDebugEnabled: Boolean = logLevel >= StdOutLogger.debugLevel
override protected def logError(cause: Throwable, message: String): Unit = {
println(s"$time [ERROR] - $thread - $name - $message ${stackTrace(cause)}")
}
override protected def logWarning(message: String): Unit = {
println(s"$time [WARN ] - $thread - $name - $message")
}
override protected def logInfo(message: String): Unit = {
println(s"$time [INFO ] - $thread - $name - $message")
}
override protected def logDebug(message: String): Unit = {
println(s"$time [DEBUG] - $thread - $name - $message")
}
private def time = LocalDateTime.now().format(DateTimeFormatter.ISO_DATE_TIME)
private def thread = Thread.currentThread.getName
private def stackTrace(e: Throwable): String = e match {
case null => ""
case _: NoStackTrace => " (" + e.getClass.getName + ")"
case other =>
val sw = new java.io.StringWriter
val pw = new java.io.PrintWriter(sw)
pw.append('\n')
other.printStackTrace(pw)
sw.toString
}
}
开发者ID:defvar,项目名称:knot,代码行数:56,代码来源:StdOutLogger.scala
示例7: Formatters
//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.datetime
import java.time.format.{DateTimeFormatter, DateTimeFormatterBuilder}
import java.time.temporal.ChronoField
private[datetime] object Formatters {
val bpDateFormatter = DateTimeFormatter.ISO_LOCAL_DATE
val bpTimeFormatter = DateTimeFormatter.ISO_LOCAL_TIME
val bpTzTimeFormatter =
new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("HH:mm:ss"))
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND,0,6,true)
.optionalEnd()
.appendOffset("+HH:mm","+00")
.toFormatter()
val bpTzDateTimeFormatter =
new DateTimeFormatterBuilder()
.append(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"))
.optionalStart()
.appendFraction(ChronoField.NANO_OF_SECOND,0,6,true)
.optionalEnd()
.appendOffset("+HH:mm","+00")
.toFormatter()
}
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:26,代码来源:Formatters.scala
示例8: TimeParser
//设置package包名称以及导入依赖的类
package wvlet.core.scales
import java.time.format.DateTimeFormatter
import java.time._
import java.time.temporal.{TemporalAccessor, TemporalQueries, TemporalQuery}
import wvlet.log.LogSupport
import scala.util.{Failure, Success, Try}
object TimeParser extends LogSupport{
val localDatePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd")
val localDateTimePattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss[.SSS]")
val zonedDateTimePatterns: List[DateTimeFormatter] = List(
"yyyy-MM-dd HH:mm:ss[.SSS][ z][XXXXX][XXXX]['['VV']']",
"yyyy-MM-dd'T'HH:mm:ss[.SSS][ z][XXXXX][XXXX]['['VV']']"
).map(DateTimeFormatter.ofPattern(_))
def parseLocalDateTime(s: String, zone: ZoneOffset): Option[ZonedDateTime] = {
Try(LocalDateTime.parse(s, localDateTimePattern))
.map{ d => ZonedDateTime.of(d, zone) }
.orElse {
Try(LocalDate.parse(s, localDatePattern))
.map{ d => d.atStartOfDay(zone) }
}
.toOption
}
def parseZonedDateTime(s:String): Option[ZonedDateTime] = {
def loop(lst:List[DateTimeFormatter]): Option[ZonedDateTime] = {
if(lst.isEmpty)
None
else {
val formatter = lst.head
Try(ZonedDateTime.parse(s, formatter)) match {
case Success(dt) =>
Some(dt)
case Failure(e) =>
loop(lst.tail)
}
}
}
loop(zonedDateTimePatterns.toList)
}
def parseAtLocalTimeZone(s:String) = parse(s, TimeWindow.systemZone)
def parse(s: String, zone: ZoneOffset): Option[ZonedDateTime] = {
parseLocalDateTime(s, zone)
.orElse {
parseZonedDateTime(s)
}
}
}
开发者ID:wvlet,项目名称:wvlet,代码行数:59,代码来源:TimeParser.scala
示例9: 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
示例10: 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
示例11: Describe
//设置package包名称以及导入依赖的类
package delorean.commands
import java.time.format.DateTimeFormatter
import delorean.FileOps._
import delorean._
/**
* Class for 'describe' command.
*/
case class Describe(pitstops: List[String]) {
pitstops.foreach(pitstop ? {
docExplain(pitstop)
if (pitstops.length > 1) println
})
// Let the doc explain the pitstop
def docExplain(simplifiedPitstop: String): Unit = {
val correctPitstop = resolveTheCorrectPitstop(simplifiedPitstop)
if (correctPitstop.isEmpty) return
val metadata: Metadata = Metadata(correctPitstop)
// fileName -> fileHash
val changedFilesMap = getFileAsMap(PITSTOPS_FOLDER + correctPitstop)
println(
s"""Pitstop $correctPitstop
|Rider: ${metadata.rider}
|Time: ${metadata.time.format(DateTimeFormatter.ofPattern("MMM dd yyyy hh:mm a zz"))}
|Parent(s): ${metadata.parents.mkString(", ")}
|Rider Log: ${metadata.riderLog}
|Changes: ${changedFilesMap.keys.mkString("\n\t", "\n\t", "")}
""".stripMargin)
}
}
开发者ID:durgaswaroop,项目名称:delorean,代码行数:35,代码来源:Describe.scala
示例12: GpxFileReader
//设置package包名称以及导入依赖的类
package eu.kraml.io
import java.io.File
import java.nio.file.Path
import java.time.Instant
import java.time.format.DateTimeFormatter
import eu.kraml.model.{GpsCoordinate, Record}
import scala.collection.mutable.ListBuffer
import scala.xml.XML
object GpxFileReader {
val formatter = DateTimeFormatter.ISO_INSTANT
def read(gpxFile: Path): Option[List[Record]] = {
read(gpxFile.toFile)
}
def read(gpxFile: File): Option[List[Record]] = {
try {
Some(readInternal(gpxFile))
} catch {
case e:Exception =>
None
}
}
private def readInternal(gpxFile: File): List[Record] = {
val gpx = XML.loadFile(gpxFile)
val segment = gpx \ "trk" \ "trkseg"
val points = segment \ "trkpt"
val records = ListBuffer[Record]()
points.foreach(n => {
val lat = n.attribute("lat").get.head.text
val lon = n.attribute("lon").get.head.text
val timestampText = (n \ "time").text
val timestamp = Instant.parse(timestampText)
records += Record(new GpsCoordinate(lat.toDouble, lon.toDouble), timestamp)
})
records.toList
}
}
开发者ID:jkraml,项目名称:gpsplot,代码行数:45,代码来源:GpxFileReader.scala
示例13: Request
//设置package包名称以及导入依赖的类
package services.moysklad
import java.time.format.DateTimeFormatter
import java.time.temporal.TemporalAccessor
abstract class Request[A <: Response] {
def endpoint: String
def queryString: Seq[(String, String)]
private val dateFormatter = DateTimeFormatter.ofPattern("YYYY-MM-dd 00:00:00")
protected def formatDateTime(date: TemporalAccessor): String = dateFormatter.format(date)
}
abstract class PagedRequest[E](__limit: Int = 100, __offset: Int = 0) extends Request[PagedResponse[E]] with Cloneable {
private var _limit: Int = __limit
private var _offset: Int = __offset
def limit(): Int = _limit
def offset(): Int = _offset
override def queryString: Seq[(String, String)] = {
Seq(
("limit", _limit.toString),
("offset", _offset.toString)
)
}
def next : this.type = {
val cl: this.type = this.clone().asInstanceOf[this.type]
cl._offset = this.offset + this.limit
cl
}
}
开发者ID:SeriousDron,项目名称:moysklad-reports,代码行数:36,代码来源:Request.scala
示例14: QuoteParser
//设置package包名称以及导入依赖的类
package openquant.yahoofinance.impl
import java.time.format.DateTimeFormatter
import java.time.{LocalDate, ZoneId, ZonedDateTime}
import com.github.tototoshi.csv._
import openquant.yahoofinance.Quote
import scala.io.Source
class QuoteParser {
private[this] val df = DateTimeFormatter.ofPattern("yyyy-MM-dd")
private[this] val zoneId = ZoneId.of("America/New_York")
def parse(content: String): Vector[Quote] = {
val csvReader = CSVReader.open(Source.fromString(content))
val quotes: Vector[Quote] = csvReader.toStream.drop(1).map { fields ?
parseCSVLine(fields.toVector)
}.toVector
quotes
}
private def parseCSVLine(field: Vector[String]): Quote = {
require(field.length >= 7)
Quote(
parseDate(field(0)),
BigDecimal(field(1)),
BigDecimal(field(4)),
BigDecimal(field(2)),
BigDecimal(field(3)),
BigDecimal(field(5)),
BigDecimal(field(6))
)
}
private def parseDate(date: String): ZonedDateTime = {
LocalDate.parse(date, df).atStartOfDay().atZone(zoneId)
}
}
object QuoteParser {
def apply() = new QuoteParser
}
开发者ID:openquant,项目名称:YahooFinanceScala,代码行数:45,代码来源:QuoteParser.scala
示例15: Candlestick
//设置package包名称以及导入依赖的类
package br.com.caelum.argentum.model
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
final case class Candlestick(val opening: BigDecimal, val closing: BigDecimal, val minimum: BigDecimal,
val maximum: BigDecimal, val volume: BigDecimal, val date: LocalDateTime) {
require(opening >= BigDecimal(0.0))
require(closing >= BigDecimal(0.0))
require(minimum >= BigDecimal(0.0))
require(maximum >= BigDecimal(0.0))
require(volume >= BigDecimal(0.0))
require(maximum >= minimum)
final var defaultDateFormat = DateTimeFormatter.ofPattern("dd/MM/yyyy hh:mm:ss")
def isAlta(): Boolean = opening <= closing
def isBaixa(): Boolean = opening > closing
override def toString: String = {
s"{ (Abertura: ${opening}) (Fechamento: ${closing}) (Minimo: ${minimum}) (Maximo: ${maximum}) (volume: ${volume}) (Data: ${date.format(defaultDateFormat)}) }"
}
}
开发者ID:cristianospsp,项目名称:argentum-scala-play,代码行数:26,代码来源:Candlestick.scala
示例16: LocalDateUtil
//设置package包名称以及导入依赖的类
package com.squarecode.axia.util
import java.text.SimpleDateFormat
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.Date
object LocalDateUtil {
implicit class LocalDateFormat(val o: String) {
def toLocalDate: LocalDate = LocalDate.parse(o)
}
implicit class LocalDateString(val o: LocalDate) {
def toLocalDateString: String = o.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
}
implicit class StringToJavaDate(val s: String) {
def toStringJavaDate: Date = new SimpleDateFormat("yyyy-MM-dd").parse(s)
}
implicit class JavaDateToString(val d: Date) {
def toJavaDateString: String = new SimpleDateFormat("yyyy-MM-dd").format(d)
}
}
开发者ID:dynastymasra,项目名称:ScalaGolangThirft,代码行数:26,代码来源:LocalDateUtil.scala
示例17: LocalDateTimeUtil
//设置package包名称以及导入依赖的类
package com.squarecode.axia.util
import java.time.LocalDateTime
import org.joda.time.format.{DateTimeFormat => joda}
import java.time.format.DateTimeFormatter
import org.joda.time.DateTime
object LocalDateTimeUtil {
implicit class LocalDateTimeFormat(val o: String) {
def toLocalDateTime: LocalDateTime = LocalDateTime.parse(o, DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
}
implicit class JodaDateTimeFormat(val d: String) {
def toJodaDateTime: DateTime = DateTime.parse(d, joda.forPattern("yyyy-MM-dd'T'HH:mm:ss"))
}
implicit class StringJodaTimeFormat(val d: DateTime) {
def toStringJodaTime: String = d.toString("yyyy-MM-dd'T'HH:mm:ss")
}
implicit class LocalDateTimeString(val o: LocalDateTime) {
def toLocalDateTimeString: String = o.format(DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"))
}
}
开发者ID:dynastymasra,项目名称:ScalaGolangThirft,代码行数:26,代码来源:LocalDateTimeUtil.scala
示例18: Serializers
//设置package包名称以及导入依赖的类
package com.wunder.pets.web
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import java.util.UUID
import com.wunder.pets.pets._
import com.wunder.pets.validations.Validations.ErrorMessages
import play.api.libs.functional.syntax._
import play.api.libs.json._
object Serializers {
// Order is important here (compiler needs to know about any implicit Reads/Writes before it uses them):
implicit val uuidWrites = new Writes[UUID] {
override def writes(o: UUID): JsValue = JsString(o.toString)
}
implicit val offsetDateTimeWrites = new Writes[OffsetDateTime] {
override def writes(o: OffsetDateTime): JsValue = JsString(o.format(DateTimeFormatter.ISO_INSTANT))
}
implicit val errorMessagesWrites = new Writes[ErrorMessages] {
override def writes(o: ErrorMessages): JsValue = Json.obj(
"errors" -> o.map(JsString(_))
)
}
def newAttributeWriter[T <: PetAttribute]: Writes[T] = {
new Writes[T] {
override def writes(o: T): JsValue = JsNumber(o.value)
}
}
implicit val petStrengthWrites = newAttributeWriter[Strength]
implicit val petSpeedWrites = newAttributeWriter[Speed]
implicit val petIntelligenceWrites = newAttributeWriter[Intelligence]
implicit val petIntegrityWrites = newAttributeWriter[Integrity]
implicit val petNameWrites = new Writes[Name] {
override def writes(o: Name): JsValue = JsString(o.value)
}
implicit val petWrites = new Writes[Pet] {
override def writes(o: Pet): JsValue = Json.obj(
"id" -> Json.toJson(o.id),
"name" -> Json.toJson(o.name),
"strength" -> Json.toJson(o.strength),
"speed" -> Json.toJson(o.speed),
"intelligence" -> Json.toJson(o.intelligence),
"integrity" -> Json.toJson(o.integrity)
)
}
implicit val createPetFormReads: Reads[CreatePetForm] = (
(JsPath \ "name").read[String] and
(JsPath \ "strength").read[Int] and
(JsPath \ "speed").read[Int] and
(JsPath \ "intelligence").read[Int] and
(JsPath \ "integrity").read[Int]
) (CreatePetForm.apply _)
}
开发者ID:wunderteam,项目名称:battle-pets-api,代码行数:62,代码来源:Serializers.scala
示例19: TestEventEncoder
//设置package包名称以及导入依赖的类
package akka.persistence.pg
import java.time.OffsetDateTime
import java.time.format.DateTimeFormatter
import akka.persistence.pg.TestActor.{Incremented, Altered}
import akka.persistence.pg.event.JsonEncoder
import scala.util.parsing.json._
class TestEventEncoder extends JsonEncoder {
val A = classOf[Altered]
val I = classOf[Incremented]
override def toJson = {
case a: Altered => JsonString(s"""{
| "type": "altered",
| "id": "${a.id}",
| "created": "${DateTimeFormatter.ISO_DATE_TIME.format(a.created)}"
|}""".stripMargin)
case i: Incremented => JsonString(s"""{
| "count": ${i.count},
| "created": "${DateTimeFormatter.ISO_DATE_TIME.format(i.created)}"
|}""".stripMargin)
}
private def parseDateTime(jsonMap: Map[String, Any]): OffsetDateTime = {
OffsetDateTime.from(DateTimeFormatter.ISO_DATE_TIME.parse(jsonMap("created").asInstanceOf[String]))
}
private def altered(jsValue: Map[String, Any]): Altered = {
Altered(jsValue("id").asInstanceOf[String], parseDateTime(jsValue))
}
private def incremented(jsValue: Map[String, Any]): Incremented = {
Incremented(jsValue("count").asInstanceOf[Double].toInt, parseDateTime(jsValue))
}
private def parseJsonString(jsonString: JsonString) = {
JSON.parseFull(jsonString.value).get.asInstanceOf[Map[String, Any]]
}
override def fromJson = {
case (json, A) => altered(parseJsonString(json))
case (json, I) => incremented(parseJsonString(json))
}
}
开发者ID:WegenenVerkeer,项目名称:akka-persistence-postgresql,代码行数:49,代码来源:TestEventEncoder.scala
示例20: Conf
//设置package包名称以及导入依赖的类
package utils
import java.time.LocalDate
import scala.concurrent.duration.FiniteDuration
import scala.collection.JavaConversions._
import java.time.format.DateTimeFormatter
import play.api.Configuration
class Conf(
conf: Configuration
) {
def requiredString(key: String) = requiredValue(optionalString, key)
def requiredStringList(key: String) = requiredValue(optionalStringList, key)
def requiredStringMap(key: String) = requiredValue(optionalStringMap, key)
def requiredBoolean(key: String) = requiredValue(optionalBoolean, key)
def requiredMs(key: String) = requiredValue(optionalMs, key)
def requiredInt(key: String) = requiredValue(optionalInt, key)
def requiredDate(key: String) = validateDate(requiredValue(optionalString, key))
def requiredDuration(key: String) = requiredValue(optionalDuration, key)
def requiredLong(key: String) = requiredValue(optionalLong, key)
def optionalString(key: String) = conf.getString(key)
def optionalStringList(key: String) = conf.getStringList(key)
def optionalStringMap(key: String) = conf.getObject(key).map(obj => obj.map {
case (key, value) => (key, value.unwrapped.toString)
}.toMap)
def optionalBoolean(key: String) = conf.getBoolean(key)
def optionalMs(key: String) = conf.getMilliseconds(key)
def optionalInt(key: String) = conf.getInt(key)
def optionalDuration(key: String) = optionalMs(key).map(ms => FiniteDuration(ms, "millis"))
def optionalLong(key: String) = conf.getLong(key)
private def requiredValue[A](getter: String => Option[A], key: String): A =
getter(key).getOrElse(sys.error(s"Missing config key: $key"))
private def validateDate(mayBeDate : String ): String = {
try {
val format = DateTimeFormatter.ofPattern("d/MM/uuuu")
LocalDate.parse(mayBeDate, format)
mayBeDate
} catch {
case _: Throwable => {
sys.error(s"Format date error : ${mayBeDate}")
}
}
}
}
开发者ID:denis-mludek,项目名称:zencroissants,代码行数:50,代码来源:Conf.scala
注:本文中的java.time.format.DateTimeFormatter类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论