本文整理汇总了Scala中org.joda.time.format.DateTimeFormat类的典型用法代码示例。如果您正苦于以下问题:Scala DateTimeFormat类的具体用法?Scala DateTimeFormat怎么用?Scala DateTimeFormat使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTimeFormat类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。
示例1: GeoTagSpec
//设置package包名称以及导入依赖的类
package models.geotag
import java.util.UUID
import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import org.specs2.mutable._
import org.specs2.runner._
import org.junit.runner._
import play.api.libs.json.Json
import play.api.test._
import play.api.test.Helpers._
import scala.io.Source
@RunWith(classOf[JUnitRunner])
class GeoTagSpec extends Specification {
private val DATE_TIME_PATTERN = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ")
"The sample geotag" should {
"be properly created from JSON" in {
val json = Source.fromFile("test/resources/models/geotag/geotag.json").getLines().mkString("\n")
val result = Json.fromJson[GeoTag](Json.parse(json))
// Parsed without errors?
result.isSuccess must equalTo(true)
val geotag = result.get
geotag.annotationId must equalTo(UUID.fromString("5c25d207-11a5-49f0-b2a7-61a6ae63d96c"))
geotag.documentId must equalTo("qhljvnxnuuc9i0")
geotag.filepartId must equalTo(UUID.fromString("f903b736-cae8-4fe3-9bda-01583783548b"))
geotag.gazetteerUri must equalTo("http://pleiades.stoa.org/places/118543")
geotag.lastModifiedAt must equalTo(DateTime.parse("2016-09-19T13:09:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
}
}
"JSON serialization/parsing roundtrip" should {
"yield an equal geotag" in {
val geotag = GeoTag(
UUID.randomUUID(),
"qhljvnxnuuc9i0",
UUID.fromString("841f9462-beb0-4967-ad48-64af323fc4c1"),
"http://pleiades.stoa.org/places/118543",
Seq.empty[String], // toponym
Seq.empty[String], // contributors
None, // lastModifiedBy
DateTime.parse("2016-02-23T18:24:00Z", DATE_TIME_PATTERN).withZone(DateTimeZone.UTC))
// Convert to JSON
val serialized = Json.prettyPrint(Json.toJson(geotag))
val parseResult = Json.fromJson[GeoTag](Json.parse(serialized))
parseResult.isSuccess must equalTo(true)
parseResult.get must equalTo(geotag)
}
}
}
示例2: IfTag
//设置package包名称以及导入依赖的类
package helpers
import models._
import org.joda.time.format.DateTimeFormat
import org.joda.time.{DateTime, Days}
import org.joda.time.Minutes
import org.joda.time.Hours
import play.api.Play
import play.api.Play.current
import play.api.i18n.Lang
import play.twirl.api.Html
import utils.DateUtils
import utils.m
import play.api.mvc.WrappedRequest
class IfTag(condition: Boolean, content: => Html) extends scala.xml.NodeSeq {
def theSeq = Nil // just ignore, required by NodeSeq
override def toString = if (condition) content.toString else ""
def orElse(failed: => Html) = if (condition) content else failed
}
object CustomTag {
def date2delay(d: DateTime)(implicit request: WrappedRequest[_]): String = {
val d_minus_seven_days = DateUtils.now.minusDays(7)
val d_minus_one_days = DateUtils.now.minusDays(1)
val d_minus_one_hours = DateUtils.now.minusHours(1)
val now = DateUtils.now
if (d.isAfterNow) { "" }
else if (d.isAfter(d_minus_one_hours)) {
val minutes_delta = Minutes.minutesBetween(d, now)
m("general.date.delay.minutes", Math.abs(minutes_delta.getMinutes))
} else if (d.isAfter(d_minus_one_days)) {
val hours_delta = Hours.hoursBetween(d, now)
m("general.date.delay.hours", Math.abs(hours_delta.getHours))
} else if (d.isAfter(d_minus_seven_days.toInstant)) {
val day_delta = Days.daysBetween(d, now)
m("general.date.delay.days", Math.abs(day_delta.getDays))
} else {
m("general.date.delay.on", date_format(d, Some("MMM")), d.getDayOfMonth)
}
}
def date_format(date: DateTime, format: Option[String] = None)(implicit lang: Lang): String = {
val pattern = format
.orElse(Play.configuration.getString(s"date.i18n.date.format.${lang.language}"))
.getOrElse("dd/MM/yyyy")
val locale = lang.toLocale
val formatter = DateTimeFormat.forPattern(pattern).withLocale(locale)
formatter.print(date)
}
}
示例3: TemporalBounds
//设置package包名称以及导入依赖的类
package models.place
import org.joda.time.{ DateTime, DateTimeZone }
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class TemporalBounds(from: DateTime, to: DateTime)
object TemporalBounds {
private val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd").withZone(DateTimeZone.UTC)
implicit val dateFormat =
Format(
JsPath.read[JsString].map { json =>
dateFormatter.parseDateTime(json.value)
},
Writes[DateTime] { dt =>
Json.toJson(dateFormatter.print(dt))
}
)
private def flexDateWrite(dt: DateTime): JsValue =
if (dt.monthOfYear == 1 && dt.dayOfMonth == 1 && dt.minuteOfDay == 0)
Json.toJson(dt.year.get)
else
Json.toJson(dt)
implicit val temporalBoundsFormat: Format[TemporalBounds] = (
(JsPath \ "from").format[JsValue].inmap[DateTime](flexDateRead, flexDateWrite) and
(JsPath \ "to").format[JsValue].inmap[DateTime](flexDateRead, flexDateWrite)
)(TemporalBounds.apply, unlift(TemporalBounds.unapply))
def computeUnion(bounds: Seq[TemporalBounds]): TemporalBounds = {
val from = bounds.map(_.from.getMillis).min
val to = bounds.map(_.to.getMillis).max
TemporalBounds(
new DateTime(from, DateTimeZone.UTC),
new DateTime(to, DateTimeZone.UTC))
}
def fromYears(from: Int, to: Int): TemporalBounds = {
val f = new DateTime(DateTimeZone.UTC).withDate(from, 1, 1).withTime(0, 0, 0, 0)
val t = new DateTime(DateTimeZone.UTC).withDate(to, 1, 1).withTime(0, 0, 0, 0)
TemporalBounds(f, t)
}
}
示例4: VersionUtils
//设置package包名称以及导入依赖的类
package uk.co.appministry.scathon.models.v2.util
import uk.co.appministry.scathon.models.v2.Version
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
object VersionUtils {
val format = DateTimeFormat.forPattern("YYYY-MM-DD'T'HH:mm:ss.SSS'Z'").withZoneUTC()
def dateTimeReads[E <: DateTime]: Reads[DateTime] = new Reads[DateTime] {
def reads(json: JsValue): JsResult[DateTime] = json match {
case JsString(s) => {
try {
JsSuccess(Version(s))
} catch {
case _: IllegalArgumentException => JsError(s"Expected a String representation of a date. Value '$s' does not look like one.")
}
}
case _ => JsError("String value expected")
}
}
implicit def dateTimeWrites[ E <: DateTime ]: Writes[DateTime] = new Writes[DateTime] {
def writes(v: DateTime): JsValue = JsString(Version(v))
}
implicit def dateTimeformat: Format[DateTime] = {
Format(VersionUtils.dateTimeReads, VersionUtils.dateTimeWrites)
}
}
示例5: AnomalyDetails
//设置package包名称以及导入依赖的类
package com.bau5.sitetracker.common
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
object AnomalyDetails {
val formatter = DateTimeFormat.forPattern("HH:mm:ss MM/dd/yyyy")
sealed trait AnomalyDetail
case class SSystem(value: String) extends AnomalyDetail
case class User(value: String) extends AnomalyDetail
case class Time(value: DateTime) extends AnomalyDetail {
override def toString: String = value.toString(formatter)
}
case class AnomalyEntry(user: User, anomaly: Anomaly, timeRecorded: Time) extends AnomalyDetail {
def update(detail: AnomalyDetail): AnomalyEntry = detail match {
case id: Identifier => AnomalyEntry(user, Anomaly(id, anomaly.name, anomaly.typ), timeRecorded)
case name: Name => AnomalyEntry(user, Anomaly(anomaly.ident, name, anomaly.typ), timeRecorded)
case typ: Type => AnomalyEntry(user, Anomaly(anomaly.ident, anomaly.name, typ), timeRecorded)
case _ => // Unsupported
this
}
override def toString: String = {
s"Entry[User:${user.value}, $anomaly, Time:$timeRecorded]"
}
def stringify: String = {
s"${anomaly.stringify},${user.value},${timeRecorded.toString}"
}
}
case class Anomaly(ident: Identifier, name: Name, typ: Type) extends AnomalyDetail {
override def toString: String = {
s"Anomaly[ID:${ident.value}, Name:'${name.value}', Type:${typ.value}]"
}
def stringify: String = {
s"${ident.value},${name.value},${typ.value}"
}
}
case class Identifier(value: String) extends AnomalyDetail
case class Name(value: String) extends AnomalyDetail
case class Type(value: String) extends AnomalyDetail
}
示例6: Main
//设置package包名称以及导入依赖的类
package be.cetic.tsimulus.cli
import java.io.File
import be.cetic.tsimulus.Utils.{generate, config2Results}
import be.cetic.tsimulus.config.Configuration
import org.joda.time.format.DateTimeFormat
import spray.json._
import scala.io.Source
object Main
{
def main(args: Array[String]): Unit =
{
val content = Source .fromFile(new File(args(0)))
.getLines()
.mkString("\n")
val dtf = DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss.SSS")
val config = Configuration(content.parseJson)
println("date;series;value")
generate(config2Results(config)) foreach (e => println(dtf.print(e._1) + ";" + e._2 + ";" + e._3))
}
}
示例7: 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")
}
示例8: currentTime
//设置package包名称以及导入依赖的类
package tech.artemisia.util
import java.io._
import java.nio.file.{Files, Paths}
import com.typesafe.config.{Config, ConfigFactory}
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import tech.artemisia.core.{AppLogger, Keywords, env}
def currentTime : String = {
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss")
formatter.print(new DateTime())
}
def prettyPrintAsciiTable(content: String, heading: String, width: Int = 80): String = {
s"""
|${"=" * (width / 2) } $heading ${"=" * (width / 2)}
|$content
|${"=" * (width / 2) } $heading ${"=" * (width / 2)}
""".stripMargin
}
}
示例9: parse
//设置package包名称以及导入依赖的类
package com.nelly.monitor
import com.nelly.core.domain.LogEntry
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import scala.util.{Failure, Success, Try}
trait LogEntryParser[T <: Product] {
def parse(entry: String) :Option[T]
}
class CommonLogFormatRegexParser extends LogEntryParser[LogEntry] {
val datePattern = DateTimeFormat.forPattern("dd/MMM/yyyy:HH:mm:ss Z")
val reg = "^(\\S+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(\\S+ \\S+\\s*\\S*\\s*)\" (\\d{3}) (\\S+)".r
override def parse(entry: String): Option[LogEntry] = entry match {
case reg(ip, identity, userId, requestReceivedTimeString, requestUrl, status, size) => {
Try(
LogEntry(
ip = ip,
receivedTime = DateTime.parse(requestReceivedTimeString, datePattern),
requestUrl = requestUrl,
status = status.toInt,
identity = identity match { case "-" | "" => None; case _ => Option(identity)},
userId = userId match { case "-" | "" => None; case _ => Option(userId)},
responseSize = size match { case "-" | "" => None; case _ => Option(size.toLong)}
)
) match {
case Success(logEntry) => Option(logEntry)
case Failure(e) => { println(s"Failed to parse:: `$e`"); None }
}
}
case _ => { println(s"Failed to parse `$entry`"); None }
}
}
object LogRecord {
def apply( logEntry: String)(implicit parser: LogEntryParser[LogEntry] =
new CommonLogFormatRegexParser) : Option[LogEntry] = parser.parse(logEntry)
}
示例10: PayrollPeriod
//设置package包名称以及导入依赖的类
package uk.gov.bis.levyApiMock.data.levy
import org.joda.time.format.DateTimeFormat
import org.joda.time.{LocalDate, LocalDateTime}
import play.api.libs.json._
case class PayrollPeriod(year: String, month: Int)
object PayrollPeriod {
implicit val formats = Json.format[PayrollPeriod]
}
case class LevyDeclaration(id: Long,
submissionTime: LocalDateTime,
dateCeased: Option[LocalDate] = None,
inactiveFrom: Option[LocalDate] = None,
inactiveTo: Option[LocalDate] = None,
payrollPeriod: Option[PayrollPeriod] = None,
levyDueYTD: Option[BigDecimal] = None,
levyAllowanceForFullYear: Option[BigDecimal] = None,
noPaymentForPeriod: Option[Boolean] = None)
object LevyDeclaration {
implicit val ldtFormats = new Format[LocalDateTime] {
val fmt = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS")
override def reads(json: JsValue): JsResult[LocalDateTime] = implicitly[Reads[JsString]].reads(json).map { js =>
fmt.parseDateTime(js.value).toLocalDateTime
}
override def writes(o: LocalDateTime): JsValue = JsString(fmt.print(o))
}
implicit val formats = Json.format[LevyDeclaration]
}
case class LevyDeclarationResponse(empref: String, declarations: Seq[LevyDeclaration])
object LevyDeclarationResponse {
implicit val formats = Json.format[LevyDeclarationResponse]
}
示例11: JumanppAdmin
//设置package包名称以及导入依赖的类
package controllers
import javax.inject.Inject
import code.{AnalysisResult, MongoWorker}
import org.joda.time.format.DateTimeFormat
import play.api.mvc.{Action, Controller}
import reactivemongo.bson.BSONDocument
import ws.kotonoha.akane.utils.XInt
import scala.concurrent.ExecutionContext
class JumanppAdmin @Inject() (
mw: MongoWorker
)(implicit ec: ExecutionContext) extends Controller {
def stats() = Action { Ok(views.html.jppadmin()) }
def queries() = Action.async { req =>
val from = req.getQueryString("from").flatMap(XInt.unapply).getOrElse(0)
val fixed = req.getQueryString("fixed").contains("true")
val sorting = req.getQueryString("sorting").collect({
case "date" => BSONDocument("timestamp" -> 1)
case "date-" => BSONDocument("timestamp" -> -1)
}).getOrElse(BSONDocument("timestamp" -> 1))
mw.get(from, 100, fixed, sorting).map { items =>
val dateFormatter = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm")
val data = items.map { a =>
AnalysisResult(
a._id.stringify,
dateFormatter.print(a.timestamp),
a.input,
JumanppConversion.convertLatttice(a._id, a.analysis),
a.version,
a.dicVersion,
a.reported.map(_.nodes)
)
}
val string = upickle.default.write(data)
Ok(string)
}
}
}
示例12: Question
//设置package包名称以及导入依赖的类
package models
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.json.Reads
import play.api.libs.functional.syntax._
import slick.driver.MySQLDriver.api.{Tag => SlickTag}
import slick.driver.MySQLDriver.api._
import com.github.tototoshi.slick.MySQLJodaSupport._
case class Question(id: Option[Long], title: String, content: String,
created_by: Option[Long], correct_answer: Option[Long],
created_at: Option[DateTime] = None, updated_at: Option[DateTime] = None)
object Question {
// implicit val format = Json.format[Question]
implicit val questionReads: Reads[Question] = (
(JsPath \ "id").readNullable[Long] and
(JsPath \ "title").read[String] and
(JsPath \ "content").read[String] and
(JsPath \ "created_by").readNullable[Long] and
(JsPath \ "correct_answer").readNullable[Long] and
(JsPath \ "created_at").readNullable[DateTime] and
(JsPath \ "updated_at").readNullable[DateTime]
)(Question.apply _)
implicit val questionWrites = Json.writes[Question]
}
class QuestionTable(tag: SlickTag) extends Table[Question](tag, "questions") {
// import utils.CustomColumnTypes._
// val dtf = DateTimeFormat.forPattern("yyyy-MM-dd hh:mm:ss")
def id = column[Long]("id", O.PrimaryKey, O.AutoInc)
def title = column[String]("title")
def content = column[String]("content")
def created_by = column[Option[Long]]("created_by")
def correct_answer = column[Option[Long]]("correct_answer")
def created_at = column[Option[DateTime]]("created_at", O.Default(Some(new DateTime)))
def updated_at = column[Option[DateTime]]("updated_at")
def * = (id.?, title, content, created_by, correct_answer,
created_at, updated_at) <> ((Question.apply _).tupled, Question.unapply)
def creator = foreignKey("creator_fk", created_by, TableQuery[UserTable])(_.id.get)
def answer = foreignKey("answer_fk", correct_answer, TableQuery[AnswerTable])(_.id)
}
示例13: LocalDateHelpers
//设置package包名称以及导入依赖的类
package utils
import algebra.Cats.TryAsJsResult
import org.joda.time.LocalDate
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import scala.util.Try
object LocalDateHelpers {
def parse(str: String): Try[LocalDate] =
dateFormat1(str) orElse dateFormat2(str) orElse dateFormat3(str) orElse dateFormat4(str) orElse dateFormat5(str) orElse dateFormat6(
str)
implicit val jsonReads: Reads[LocalDate] = Reads(_.validate[String].flatMap(x => TryAsJsResult(parse(x))))
implicit val jsonWrites: Writes[LocalDate] =
Writes { date =>
val format = DateTimeFormat.forPattern("dd-MM-yyyy")
val string = date.toString(format)
JsString(string)
}
implicit val orderingLocalDate: Ordering[LocalDate] =
Ordering.by[LocalDate, (Int, Int, Int)](x => (x.getYear, x.getMonthOfYear, x.getDayOfMonth))
private def dateFormat1(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("dd-mm-yyyy")))
private def dateFormat2(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("dd/mm/yyyy")))
private def dateFormat3(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("dd.mm.yyyy")))
private def dateFormat4(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("yyyy-mm-dd")))
private def dateFormat5(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("yyyy/mm/dd")))
private def dateFormat6(str: String): Try[LocalDate] =
Try(LocalDate.parse(str, DateTimeFormat.forPattern("yyyy.mm.dd")))
}
示例14: BookingWithKey
//设置package包名称以及导入依赖的类
package services.booking
import cats.{Id, ~>}
import models.store.InMemoryStore
import models.Booking
import org.joda.time.format.DateTimeFormat
import play.api.libs.json.Json
import scala.language.higherKinds
case class BookingWithKey(key: String, booking: Booking)
object BookingWithKey {
implicit val format = Json.format[BookingWithKey]
}
object BookingStore extends InMemoryStore[Booking] {
def book(ref: Booking): Task[BookingWithKey] = {
val key = mkKey(ref)
for {
opt <- search(key)
_ <- opt match {
case Some(_) => fail(Booked(ref))
case None => put(key, ref)
}
} yield BookingWithKey(key, ref)
}
def mkKey(booking: Booking): String = {
val format = DateTimeFormat.forPattern("ddMMyyyy")
val rawDay = booking.day.toString(format)
val rawTime = booking.time.string.replace(":", "")
rawDay + rawTime
}
}
示例15: BigFootServiceTest
//设置package包名称以及导入依赖的类
package com.flipkart.connekt.commons.tests.services
import java.util.UUID
import com.flipkart.connekt.commons.services.BigfootService
import com.flipkart.connekt.commons.tests.CommonsBaseTest
import fkint.mp.connekt.DeviceDetails
import org.joda.time.format.DateTimeFormat
import org.scalatest.Ignore
@Ignore
class BigFootServiceTest extends CommonsBaseTest {
val deviceId = "UT-" + UUID.randomUUID().toString
val userId = "ACC-" + UUID.randomUUID().toString
val token = "TOKEN-" + UUID.randomUUID().toString
"BigFoot Service " should " return success " in {
val deviceDetails = DeviceDetails(deviceId, userId, token, "osName", "osVersion",
"appName", "appVersion", "brand", "model", "state",
DateTimeFormat.forPattern("YYYY-MM-dd HH:mm:ss").print(System.currentTimeMillis()))
BigfootService.ingestEntity(deviceId, deviceDetails, "fkint/mp/connekt/DeviceDetails").get shouldEqual true
}
}