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

Scala ISODateTimeFormat类代码示例

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

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



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

示例1: DateJsonFormat

//设置package包名称以及导入依赖的类
package com.durooma.api.route

import java.sql.Date

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import com.durooma.api.model._
import com.durooma.db.Tables
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import spray.json.{DefaultJsonProtocol, DeserializationException, JsString, JsValue, RootJsonFormat}


trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {

  implicit object DateJsonFormat extends RootJsonFormat[DateTime] {

    private val parserISO : DateTimeFormatter = ISODateTimeFormat.dateTimeNoMillis()

    override def write(obj: DateTime) = JsString(parserISO.print(obj))

    override def read(json: JsValue) : DateTime = json match {
      case JsString(s) => parserISO.parseDateTime(s)
      case _ => throw DeserializationException("Invalid date format: " + json)
    }
  }

  implicit object SqlDateJsonFormat extends RootJsonFormat[Date] {

    override def write(obj: Date) = JsString(obj.toString)
    override def read(json: JsValue) = json match {
      case JsString(s) => Date.valueOf(s)
      case _ => throw DeserializationException("Invalid date format: " + json)
    }

  }

  implicit val userFormat = jsonFormat5(User.apply)
  implicit val userRegistrationFormat = jsonFormat5(UserRegistration.apply)
  implicit val accountFormat = jsonFormat4(Account.apply)
  implicit val accounBodyFormat = jsonFormat2(AccountBody.apply)
  implicit val labelFormat = jsonFormat3(Tables.LabelRow.apply)
  implicit val transactionFormat = jsonFormat8(Transaction.apply)
  implicit val transactionBodyFormat = jsonFormat7(TransactionBody.apply)
  implicit val sessionFormat = jsonFormat3(Session.apply)
  implicit val credentialsFormat = jsonFormat2(CustomCredentials.apply)

} 
开发者ID:durooma,项目名称:api,代码行数:48,代码来源:JsonSupport.scala


示例2: Formatters

//设置package包名称以及导入依赖的类
package io.gustavoamigo.quill.pgsql.encoding.jodatime

import org.joda.time.format.{DateTimeFormat, ISODateTimeFormat}

private[jodatime] object Formatters {
  val jodaDateFormatter = ISODateTimeFormat.date()
  val jodaTimeFormatter = DateTimeFormat.forPattern("HH:mm:ss.SSSSSS")
  val jodaTimeFormatter_NoFraction = DateTimeFormat.forPattern("HH:mm:ss")
  val jodaDateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSS")
  val jodaDateTimeFormatter_NoFraction = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
  val jodaTzTimeFormatter = DateTimeFormat.forPattern("HH:mm:ss.SSSSSSZ")
  val jodaTzTimeFormatter_NoFraction = DateTimeFormat.forPattern("HH:mm:ssZ")
  val jodaTzDateTimeFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss.SSSSSSZ")
  val jodaTzDateTimeFormatter_NoFraction = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ssZ")
} 
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:16,代码来源:Formatters.scala


示例3: ChargeSessionsService

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

import models.CurrentTariff
import org.joda.time.{Hours, LocalDateTime}
import org.joda.time.format.ISODateTimeFormat


object ChargeSessionsService {
  def calculateTotalFee(transaction: Map[String,AnyRef], tariff: CurrentTariff) = {
    val volume: Double = transaction.get("volume") match {
      case Some(v) if v.isInstanceOf[Double] => v.asInstanceOf[Double]
      case Some(v) if v.isInstanceOf[String] => v.asInstanceOf[String].toDouble
      case _ => 0d
    }
    val startTime = parseDate(transaction, "startTime")
    val endTime = parseDate(transaction, "endTime")
    val numHours = Hours.hoursBetween(startTime, endTime).getHours
    tariff.startFee + (numHours * tariff.hourlyFee) + (volume * tariff.feePerKwh)
  }

  private def parseDate(transaction: Map[String,AnyRef], field: String) = {
    transaction.get(field).asInstanceOf[Option[String]] match {
      case Some(dateTime) => ISODateTimeFormat.dateTimeParser().parseLocalDateTime(dateTime)
      case _ => new LocalDateTime()
    }

  }

} 
开发者ID:jeroenr,项目名称:reactive-mongo-demo,代码行数:30,代码来源:ChargeSessionsService.scala


示例4: JsonSupport

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

import spray.json._
import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.{DateTime, DateTimeZone}
import se.meldrum.machine.db.models.Task

object JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
  // To make Joda DateTime available
  // cred to suin
  implicit object DateTimeJsonFormat extends RootJsonFormat[DateTime] {
    private lazy val format = ISODateTimeFormat.dateTimeNoMillis()
    def write(datetime: DateTime): JsValue = JsString(format.print(datetime.withZone(DateTimeZone.UTC)))
    def read(json: JsValue): DateTime = json match {
      case JsString(x) => format.parseDateTime(x)
      case x           => deserializationError("Expected DateTime as JsString, but got " + x)
    }
  }
  implicit val taskFormat = jsonFormat5(Task)
  implicit val userCreationFormat = jsonFormat3(UserCreation)
  implicit val userNamesFormat = jsonFormat1(UserNames)
} 
开发者ID:Max-Meldrum,项目名称:machine,代码行数:24,代码来源:JsonSupport.scala


示例5:

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

import salat._
import salat.json._
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.DateTimeZone

package object TypeHintContext {
  implicit val ctx = new Context {
      val name = "json-test-context"
      override val typeHintStrategy = StringTypeHintStrategy(
				when = TypeHintFrequency.Always,
        typeHint = "_t")
      override val jsonConfig = JSONConfig(
				dateStrategy = StringDateStrategy(
					dateFormatter = ISODateTimeFormat.dateTime.withZone(
						DateTimeZone.UTC)))
    }
} 
开发者ID:enpassant,项目名称:rapids,代码行数:20,代码来源:TypeHintContext.scala


示例6: MarketEodEvent

//设置package包名称以及导入依赖的类
package alpha.models.events

import alpha.models.Ticker
import com.github.nscala_time.time.Imports._
import org.joda.time.format.ISODateTimeFormat

import scala.math.BigDecimal
import scala.util.Try

case class MarketEodEvent(
                           ticker: Ticker,
                           date: DateTime,
                           open: BigDecimal,
                           high: BigDecimal,
                           low: BigDecimal,
                           close: BigDecimal,
                           volume: BigDecimal,
                           exDividend: BigDecimal,
                           splitRatio: BigDecimal,
                           adjustedOpen: BigDecimal,
                           adjustedHigh: BigDecimal,
                           adjustedLow: BigDecimal,
                           adjustedClose: BigDecimal,
                           adjustedVolume: BigDecimal
                           ) extends MarketEvent


object MarketEodEvent {
  def fromSequenceOfString(line: Seq[String]): Option[MarketEodEvent] = line match {
    case List(ticker, date, open, high, low, close, volume, exDividend, splitRatio, adjustedOPen, adjustedHigh, adjustedLow, adjustedClose, adjustedVolume) =>
      Try(
        MarketEodEvent(
          Ticker(ticker),
          dateFromString(date),
          BigDecimal(open),
          BigDecimal(high),
          BigDecimal(low),
          BigDecimal(close),
          BigDecimal(volume),
          BigDecimal(exDividend),
          BigDecimal(splitRatio),
          BigDecimal(adjustedOPen),
          BigDecimal(adjustedHigh),
          BigDecimal(adjustedLow),
          BigDecimal(adjustedClose),
          BigDecimal(adjustedVolume)
        )
      ).toOption
    case _ =>
      None
  }
  def dateFromString(string: String): DateTime = {
    val fmt = ISODateTimeFormat.yearMonthDay()
    fmt.parseDateTime(string)
  }

} 
开发者ID:kszlim,项目名称:scala-alpha,代码行数:58,代码来源:MarketEodEvent.scala


示例7: NamedFunction

//设置package包名称以及导入依赖的类
package com.tecsisa.lightql
package parser

import com.github.nscala_time.time.Imports.DateTime
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.DateTimeZone.UTC

private[parser] trait Helpers {
  // Wraps a function with a name
  protected[this] case class NamedFunction[T, V](f: T => V, name: String) extends (T => V) {
    def apply(t: T): V              = f(t)
    override def toString(): String = name
  }

  // A function for valid whitespaces
  protected[this] val Whitespace = NamedFunction(" \r\n".contains(_: Char), "Whitespace")

  // A function for valid digits
  protected[this] val Digits = NamedFunction('0' to '9' contains (_: Char), "Digits")

  // Standard data format
  protected[this] val dateTimeFormatter = ISODateTimeFormat.dateTimeParser().withZone(UTC)

  // A function for parse dates
  protected[this] def parseDate(date: String) = DateTime.parse(date, dateTimeFormatter)
} 
开发者ID:Tecsisa,项目名称:lightQL,代码行数:27,代码来源:Helpers.scala


示例8: parseTimeStamps

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

import java.io.{File, PrintWriter}

import org.apache.spark.SparkContext
import org.apache.spark.rdd.RDD
import org.joda.time.format.ISODateTimeFormat

import scalaz.effect._


trait IOComponent {
  def parseTimeStamps(timestamp: String): Long = ISODateTimeFormat.dateTimeNoMillis.parseDateTime(timestamp).getMillis

  def loader(sc: SparkContext, file: String): RDD[ListenedSongs] = {
    sc.textFile(file)
      .map(_.split("\t"))
      .map(event => ListenedSongs(event(0), parseTimeStamps(event(1)), Song(event(3), event(2))))
  }

  def write[A, B] (map: Map[A, B], file: String) = IO {
    def userHomeDirectory = System.getProperty("user.home")
    val writer = new PrintWriter(new File(userHomeDirectory + "/" + file))
    for {
      tuple <- map
    }
      yield writer.write(tuple.toString() + "\n")
    writer.close()
  }
} 
开发者ID:dsdinter,项目名称:spark-reader-lastfm,代码行数:31,代码来源:IOComponent.scala


示例9: DatabaseInspector

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

import com.mnubo.dbevolv.util.Logging
import org.joda.time.format.ISODateTimeFormat

object DatabaseInspector extends Logging {
  private val fmt = ISODateTimeFormat.dateTime()
  def displayHistory(config: DbMigrationConfig) = {
    import config._

    println(s"History of $name:")
    println()
    println("         Version                       Date                           Checksum")
    config
      .connection
      .getInstalledMigrationVersions
      .toSeq
      .sortBy(_.version)
      .foreach { case InstalledVersion(v, date, checksum) =>
        val fmtDate = fmt.print(date)
        println(f"$v%16s   $fmtDate%s   $checksum")
      }
  }

} 
开发者ID:mnubo,项目名称:dbevolv,代码行数:26,代码来源:DatabaseInspector.scala


示例10: GenericRecordEventJsonConverter

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

import java.io.ByteArrayOutputStream

import com.pragmasoft.eventaggregator.model.KafkaAvroEvent
import com.sksamuel.elastic4s.source.Indexable
import org.apache.avro.generic.{GenericDatumWriter, GenericRecord}
import org.apache.avro.io.EncoderFactory
import org.joda.time.format.ISODateTimeFormat

object GenericRecordEventJsonConverter {

  case class EventHeaderDescriptor(eventIdPath: Option[String], eventTsPath: Option[String]) {
    import com.pragmasoft.eventaggregator.GenericRecordFieldExtractionSupport._

    def extractEventId[T <: GenericRecord](event: T): Option[String] = eventIdPath.flatMap(event.getField[Any]).map(_.toString)

    def extractEventTs[T <: GenericRecord](event: T): Option[Long] = eventTsPath.flatMap(event.getField[Long])
  }

  private def asJsonString(event: GenericRecord): String = {
    val out = new ByteArrayOutputStream()
    val jsonEncoder = EncoderFactory.get().jsonEncoder(event.getSchema, out)
    val writer = new GenericDatumWriter[GenericRecord](event.getSchema)

    writer.write(event, jsonEncoder)
    jsonEncoder.flush()
    out.close()

    out.toString
  }

  implicit def kafkaAvroEventIndexable(implicit headerDescriptor: EventHeaderDescriptor): Indexable[KafkaAvroEvent[GenericRecord]] = new Indexable[KafkaAvroEvent[GenericRecord]] {
    val timestampFormat = ISODateTimeFormat.dateTime().withZoneUTC

    override def json(event: KafkaAvroEvent[GenericRecord]): String = {
      val timestampJsonAttributeMaybe =
        headerDescriptor.extractEventTs(event.data)
          .map(ts => s""" "@timestamp" : "${timestampFormat.print(ts)}",""")

      s"""{
          |  ${timestampJsonAttributeMaybe.getOrElse("")}
          |  "location" : { "topic" : "${event.location.topic}", "partition" : ${event.location.partition}, "offset" : ${event.location.offset} },
          |  "schemaName" : "${event.schemaName}",
          |  "data" : ${asJsonString(event.data)}
          |} """.stripMargin

    }
  }

} 
开发者ID:galarragas,项目名称:event-aggregator,代码行数:52,代码来源:GenericRecordEventJsonConverter.scala


示例11: DateTimeFormat

//设置package包名称以及导入依赖的类
package me.lsbengine.json

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import me.lsbengine.api.admin.security.NewCredentials
import me.lsbengine.api.model.{FetchPostResponse, ListActionResponse, PostCreationResponse, TokenResponse}
import me.lsbengine.database.model.{AboutMe, HtmlMarkdownContent, NavBarConf, Post}
import org.joda.time.DateTime
import org.joda.time.format.{DateTimeFormatter, ISODateTimeFormat}
import spray.json._

import scala.util.Try

trait JSONSupport extends SprayJsonSupport with DefaultJsonProtocol with CollectionFormats {

  implicit object DateTimeFormat extends RootJsonFormat[DateTime] {

    val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime

    override def read(json: JsValue): DateTime = json match {
      case JsString(s) => Try(formatter.parseDateTime(s)).fold(_ => error(s), identity)
      case _ =>
        error(json.toString())
    }

    override def write(obj: DateTime): JsValue = {
      JsString(formatter.print(obj))
    }

    def error(v: Any): DateTime = {
      val example = formatter.print(0)
      deserializationError(s"$v is not a valid date. Dates must be in ISO formatForForm : $example")
    }
  }

  //USED ONLY FOR BUILDINFO OTHERWISE STRANGE BEHAVIOUR
  implicit object AnyFormat extends JsonFormat[Any] {
    override def write(obj: Any): JsValue = JsString(s"$obj")

    override def read(json: JsValue): Any = json match {
      case JsString(s) => s
      case _ =>
        deserializationError(s"Expected a string, got $json")
    }
  }

  implicit val htmlMarkdownContentFormat: RootJsonFormat[HtmlMarkdownContent] = jsonFormat2(HtmlMarkdownContent)

  implicit val postFormat: RootJsonFormat[Post] = jsonFormat5(Post)
  implicit val aboutMeFormat: RootJsonFormat[AboutMe] = jsonFormat2(AboutMe)
  implicit val navbarFormat: RootJsonFormat[NavBarConf] = jsonFormat2(NavBarConf)
  implicit val tokenResponseFormat: RootJsonFormat[TokenResponse] = jsonFormat1(TokenResponse)
  implicit val listActionResponseFormat: RootJsonFormat[ListActionResponse] = jsonFormat1(ListActionResponse)
  implicit val fetchPostResponseFormat: RootJsonFormat[FetchPostResponse] = jsonFormat1(FetchPostResponse)
  implicit val postCreationResponseFormat: RootJsonFormat[PostCreationResponse] = jsonFormat1(PostCreationResponse)

  implicit val newCredentialsFormat: RootJsonFormat[NewCredentials] = jsonFormat3(NewCredentials)
} 
开发者ID:jrabasco,项目名称:LSBEngine,代码行数:58,代码来源:JSONSupport.scala


示例12: write

//设置package包名称以及导入依赖的类
package com.app.service.model

import org.joda.time.DateTime
import org.joda.time.format.{ DateTimeFormatter, ISODateTimeFormat }
import spray.json._

trait ServiceJsonFormatters extends DefaultJsonProtocol {

  val formatter: DateTimeFormatter = ISODateTimeFormat.dateTime()

  // Joda - DateTime
  implicit val jodaDateTimeJFConverter = new JsonFormat[DateTime] {
    override def write(obj: DateTime): JsValue = {
      formatter.print(obj).toJson
    }
    override def read(js: JsValue): DateTime = {
      formatter.parseDateTime(js.convertTo[String])
    }
  }

} 
开发者ID:witZack,项目名称:scala-akka-skeleton,代码行数:22,代码来源:ServiceJsonFormatters.scala


示例13: DateTimeFormat

//设置package包名称以及导入依赖的类
package main.scala.textboard

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport
import akka.http.scaladsl.marshalling.GenericMarshallers._
import akka.http.scaladsl.marshalling.GenericMarshallers.futureMarshaller
import akka.http.scaladsl.unmarshalling.PredefinedFromEntityUnmarshallers
import java.sql.Timestamp
import org.joda.time.DateTime
import org.joda.time.DateTimeZone.UTC
import slick.driver.PostgresDriver.api._
import slick.ast.TypedType
import spray.json._
import spray.json.DefaultJsonProtocol
import textboard.domain._
import textboard.utils._
import org.joda.time.format.ISODateTimeFormat
import org.joda.time.format.DateTimeFormatter

/**
 * Root json protocol class for others to extend from.
 */
trait TextboardJsonProtocol extends DefaultJsonProtocol with SprayJsonSupport with DateTimeHelper {
  implicit object DateTimeFormat extends RootJsonFormat[DateTime] {

    private val parser: DateTimeFormatter = {
      ISODateTimeFormat.dateTimeNoMillis()
    }

    override def read(value: JsValue): DateTime = value match {
      case s: JsValue => parser.parseDateTime(s.toString())
      case _           => throw new Exception("DateTime expected")
    }
    override def write(dt: DateTime) = JsString(parser.print(dt))
  }

  implicit val threadFormat = jsonFormat2(Thread.apply)
  implicit val postFormat = jsonFormat7(Post.apply)
  implicit val newThread = jsonFormat6(NewThread.apply)
  implicit val newContent = jsonFormat1(NewContent.apply)
} 
开发者ID:michaltrzesimiech,项目名称:scala-textboard,代码行数:41,代码来源:Protocol.scala



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


鲜花

握手

雷人

路过

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

请发表评论

全部评论

专题导读
上一篇:
Scala StreamingLinearRegressionWithSGD类代码示例发布时间:2022-05-23
下一篇:
Scala File类代码示例发布时间: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