本文整理汇总了Scala中org.joda.time.format.DateTimeFormat类的典型用法代码示例。如果您正苦于以下问题:Scala DateTimeFormat类的具体用法?Scala DateTimeFormat怎么用?Scala DateTimeFormat使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了DateTimeFormat类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
}
}
}
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:GeoTagSpec.scala
示例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)
}
}
开发者ID:Driox,项目名称:play-app-seed,代码行数:59,代码来源:CustomTag.scala
示例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)
}
}
开发者ID:pelagios,项目名称:recogito2,代码行数:53,代码来源:TemporalBounds.scala
示例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)
}
}
开发者ID:AppMinistry,项目名称:scathon,代码行数:34,代码来源:VersionUtils.scala
示例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
}
开发者ID:rickbau5,项目名称:SiteTracker,代码行数:47,代码来源:AnomalyDetails.scala
示例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))
}
}
开发者ID:cetic,项目名称:tsimulus-cli,代码行数:29,代码来源:Main.scala
示例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")
}
开发者ID:gustavoamigo,项目名称:quill-pgsql,代码行数:16,代码来源:Formatters.scala
示例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
}
}
开发者ID:gitter-badger,项目名称:artemisia,代码行数:26,代码来源:Util.scala
示例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)
}
开发者ID:ezinelony,项目名称:http-log-monitor,代码行数:45,代码来源:LogEntryParser.scala
示例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]
}
开发者ID:UKGovernmentBEIS,项目名称:das-alpha-hmrc-api-mock,代码行数:43,代码来源:LevyDeclarationResponse.scala
示例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)
}
}
}
开发者ID:eiennohito,项目名称:nlp-tools-demo,代码行数:46,代码来源:JumanppAdmin.scala
示例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)
}
开发者ID:greven77,项目名称:PlaySlickTest,代码行数:50,代码来源:Question.scala
示例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")))
}
开发者ID:FrancoAra,项目名称:freet-presentation,代码行数:46,代码来源:LocalDateHelpers.scala
示例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
}
}
开发者ID:FrancoAra,项目名称:freet-presentation,代码行数:38,代码来源:BookingStore.scala
示例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
}
}
开发者ID:ayush03agarwal,项目名称:connekt,代码行数:26,代码来源:BigFootServiceTest.scala
示例16: TeratailGetter
//设置package包名称以及导入依赖的类
package services.articleGetter
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.ws._
class TeratailGetter(keyword: String)(implicit ws: WSClient) extends Getter(keyword) {
case class JsonArticle(id: Int, title: String, modified: String)
def execute(): Option[Seq[Article]] = {
val response = getResponse(getParams())
analyzeResponse(response.json)
}
protected[this] def getSite(): String = "Teratail"
protected[this] def getUrl(): String = {
s"https://teratail.com/api/v1/tags/${keyword}/questions"
}
protected[this] def getParams(): Seq[(String, String)] = {
Seq[(String, String)]()
}
protected[this] def analyzeResponse(response: JsValue): Option[Seq[Article]] = {
implicit val articleReader = Json.reads[JsonArticle]
val target = (response \ "questions")
target match {
case _: JsDefined => {
val results = target.as[Seq[JsonArticle]]
if(results.nonEmpty) { Some(convertJsonArticleToArticle(results)) }
else { None }
}
case _: JsUndefined => None
case _ => None
}
}
protected[this] def convertJsonArticleToArticle(articles: Seq[JsonArticle]): Seq[Article] = {
articles.map{ article =>
makeArticle(
title = article.title,
url = makeUrl(article.id),
contents = None,
postedAt = convertStringToDateTime(article.modified)
)
}
}
protected[this] def makeUrl(id: Int): String = {
s"https://teratail.com/questions/${id.toString}"
}
protected[this] def convertStringToDateTime(time: String): Option[DateTime] = {
val pattern = """^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*$""".r
time match {
case pattern(n) => Some(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(n))
case _ => None
}
}
}
开发者ID:eidera,项目名称:multi-search,代码行数:61,代码来源:TeratailGetter.scala
示例17: Article
//设置package包名称以及导入依赖的类
package services.articleGetter
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
class Article(site: String, title: String, url: String, contents: Option[String], postedAt: Option[DateTime]) {
def getSite(): String = { site }
def getTitle(): String = { title }
def getUrl(): String = { url }
def getContents(): Option[String] = { contents }
def getPostedAt(): Option[DateTime] = { postedAt }
def getPostedString(pattern: String = "yyyy-MM-dd HH:mm:ss"): String = {
postedAt match {
case Some(n) => DateTimeFormat.forPattern(pattern).print(n)
case None => ""
}
}
}
开发者ID:eidera,项目名称:multi-search,代码行数:19,代码来源:Article.scala
示例18: QiitaGetter
//设置package包名称以及导入依赖的类
package services.articleGetter
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import play.api.libs.json._
import play.api.libs.ws._
class QiitaGetter(keyword: String)(implicit ws: WSClient) extends Getter(keyword) {
case class JsonArticle(title: String, body: String, url: String, updated_at: String)
def execute(): Option[Seq[Article]] = {
val response = getResponse(getParams())
analyzeResponse(response.json)
}
protected[this] def getSite(): String = "Qiita"
protected[this] def getUrl(): String = "https://qiita.com/api/v1/search"
protected[this] def getParams(): Seq[(String, String)] = {
Seq(
"q" -> keyword
)
}
protected[this] def analyzeResponse(response: JsValue): Option[Seq[Article]] = {
implicit val articleReader = Json.reads[JsonArticle]
val results = (response).as[Seq[JsonArticle]]
if(results.nonEmpty) { Some(convertJsonArticleToArticle(results)) }
else { None }
}
protected[this] def convertJsonArticleToArticle(articles: Seq[JsonArticle]): Seq[Article] = {
articles.map{ article =>
makeArticle(
title = article.title,
url = article.url,
contents = Some(article.body),
postedAt = convertStringToDateTime(article.updated_at)
)
}
}
protected[this] def convertStringToDateTime(time: String): Option[DateTime] = {
val pattern = """^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}).*$""".r
time match {
case pattern(n) => Some(DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss").parseDateTime(n))
case _ => None
}
}
}
开发者ID:eidera,项目名称:multi-search,代码行数:50,代码来源:QiitaGetter.scala
示例19: ApiLog
//设置package包名称以及导入依赖的类
package models
import api.ApiRequestHeader
import play.api.mvc.RequestHeader
import play.api.libs.json._
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
case class ApiLog(
id: Long,
date: DateTime,
ip: String,
apiKey: Option[String],
token: Option[String],
method: String,
uri: String,
requestBody: Option[String],
responseStatus: Int,
responseBody: Option[String]) {
def dateStr: String = ApiLog.dtf.print(date)
}
object ApiLog {
import FakeDB.logs
private val dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:ss:mm")
def findById(id: Long): Future[Option[ApiLog]] = Future.successful {
logs.get(id)
}
def insert[R <: RequestHeader](request: ApiRequestHeader[R], status: Int, json: JsValue): Future[(Long, ApiLog)] = Future.successful {
logs.insert(ApiLog(
_,
date = request.dateOrNow,
ip = request.remoteAddress,
apiKey = request.apiKeyOpt,
token = request.tokenOpt,
method = request.method,
uri = request.uri,
requestBody = request.maybeBody,
responseStatus = status,
responseBody = if (json == JsNull) None else Some(Json.prettyPrint(json))
))
}
def delete(id: Long): Future[Unit] = Future.successful {
logs.delete(id)
}
}
开发者ID:cyrillzadra,项目名称:tippspiel_backend,代码行数:54,代码来源:ApiLog.scala
示例20: Utils
//设置package包名称以及导入依赖的类
package org.zouzias.spark.lucenerdd.aws.utils
// CAUTION: Do not remove this (sbt-build-info)
import org.apache.spark.rdd.RDD
import org.apache.spark.sql.SparkSession
import org.joda.time.DateTime
import org.joda.time.format.DateTimeFormat
import org.zouzias.spark.lucenerdd.aws.BuildInfo
object Utils {
val FuzzyEditDistance = 1
val topK = 10
def loadWikipediaTitles(implicit sparkSession: SparkSession): RDD[String] = {
import sparkSession.sqlContext.implicits._
sparkSession.read.parquet("s3://spark-lucenerdd/wikipedia/enwiki-latest-all-titles.parquet")
.map(row => row.getString(0)).map(_.replaceAll("_", " ")).map(_.replaceAll("[^a-zA-Z0-9\\s]", ""))
.rdd
}
def sampleTopKWikipediaTitles(k: Int)(implicit sparkSession: SparkSession): List[String] = {
loadWikipediaTitles.sample(false, 0.01).take(k).toList
}
def dayString(): String = {
val date = new DateTime()
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd")
formatter.print(date)
}
val Version = BuildInfo.version
}
开发者ID:zouzias,项目名称:spark-lucenerdd-aws,代码行数:34,代码来源:Utils.scala
注:本文中的org.joda.time.format.DateTimeFormat类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论