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


Scala DateTime类代码示例

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


在下文中一共展示了DateTime类的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)
    }
    
  }
  
} 
开发者ID:pelagios,项目名称:recogito2,代码行数:62,代码来源:GeoTagSpec.scala

示例2: UserTokenDaoSpec

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

import scala.concurrent.Await

import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.test._
import play.api.test.Helpers._

import org.joda.time.DateTime
import org.specs2.mutable.Specification

import java.util.UUID

import scala.concurrent.Await
import scala.concurrent.duration.DurationInt

import models.UserToken

class UserTokenDaoSpec extends Specification {

  val timeout = DurationInt(10).seconds
  def fakeApp = FakeApplication(additionalConfiguration = Map("mongodb.uri" -> "mongodb://localhost:27017/test"))

  def withUserTokenDao[T](t:UserTokenDao => T):T = running(fakeApp) {
    val userTokenDao = new MongoUserTokenDao
    Await.ready(userTokenDao.tokens.drop(), timeout)
    t(userTokenDao)
  }

  val token = UserToken(id=UUID.randomUUID(), userId=UUID.randomUUID(), "[email protected]", new DateTime(), true)

  "UserTokenDao" should {
    "Persist and find a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        maybeToken <- userTokenDao.find(token.id)
      } yield maybeToken.map(_ == token)
      Await.result(future, timeout) must beSome(true)
    }

    "Remove a token" in withUserTokenDao { userTokenDao =>
      val future = for {
        _ <- userTokenDao.save(token)
        _ <- userTokenDao.remove(token.id)
        maybeToken <- userTokenDao.find(token.id)
      } yield maybeToken
      Await.result(future, timeout) must beNone       
    }
  }
} 
开发者ID:Viva-con-Agua,项目名称:drops,代码行数:51,代码来源:UserTokenDaoSpec.scala

示例3: info

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

import java.beans.Transient
import net.logstash.log4j.JSONEventLayoutV1
import org.apache.log4j.Logger
import org.joda.time.DateTime
import scala.collection.mutable



trait CrawlerLogger {
  def info(string: Any)
  def debug(string: Any)
  def trace(string: Any)
  def error(string: Any)
  def warning(string: Any)
}

object CrawlerLoggerFactory {
  private val loggers = mutable.HashMap[String, CrawlerLogger]()

  def logger(appname: String, folder: String = "apps") = synchronized {
    if (loggers.contains(appname)) loggers(appname)
    else {
      val newLogger = new CrawlerLoggerLog4j(appname, s"$folder/$appname")
      loggers(appname) = newLogger
      newLogger
    }
  }
}

class CrawlerLoggerLog4j(loggerName: String, filename: String) extends CrawlerLogger {
  @Transient val logger = Logger.getLogger(loggerName)
  logger.addAppender(new org.apache.log4j.RollingFileAppender(new JSONEventLayoutV1(), s"logs/$filename-${new DateTime().toString("yyyy-MM-dd-HH-mm")}"))

  override def info(message: Any) = logger.info(message)
  override def debug(message: Any) = logger.debug(message)
  override def trace(message: Any) = logger.trace(message)
  override def error(message: Any) = logger.error(message)
  override def warning(message: Any) = logger.warn(message)
} 
开发者ID:mxmptv,项目名称:osn.crawler,代码行数:42,代码来源:CrawlerLogger.scala

示例4: Hello

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

import java.util.Locale

import com.cronutils.descriptor.CronDescriptor
import com.cronutils.model.CronType
import com.cronutils.model.definition.CronDefinitionBuilder
import com.cronutils.parser.CronParser
import org.joda.time.DateTime

object Hello {
  def main(args: Array[String]): Unit = {
    val cronDefinition = CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
    val parser = new CronParser(cronDefinition)
    val now = DateTime.now()
    val descriptor = CronDescriptor.instance(Locale.UK)
    // val executionTime = ExecutionTime.forCron(parser.parse("* 49 * * * ? 2016"))
    println(descriptor.describe(parser.parse("* * * * *")))
  }
} 
开发者ID:shigemk2,项目名称:my-cron-utils-scala,代码行数:21,代码来源:Hello.scala

示例5: Account

//设置package包名称以及导入依赖的类
package ca.schwitzer.scaladon.models

import org.joda.time.DateTime
import play.api.libs.functional.syntax._
import play.api.libs.json._

case class Account(id: Int,
                   username: String,
                   acct: String,
                   displayName: String,
                   note: String,
                   url: String,
                   avatar: String,
                   header: String,
                   locked: Boolean,
                   createdAt: DateTime,
                   followersCount: Int,
                   followingCount: Int,
                   statusesCount: Int)

object Account {
  import ca.schwitzer.scaladon.dateReads

  implicit val reads: Reads[Account] = (
    (JsPath \ "id").read[Int] and
    (JsPath \ "username").read[String] and
    (JsPath \ "acct").read[String] and
    (JsPath \ "display_name").read[String] and
    (JsPath \ "note").read[String] and
    (JsPath \ "url").read[String] and
    (JsPath \ "avatar").read[String] and
    (JsPath \ "header").read[String] and
    (JsPath \ "locked").read[Boolean] and
    (JsPath \ "created_at").read[DateTime] and
    (JsPath \ "followers_count").read[Int] and
    (JsPath \ "following_count").read[Int] and
    (JsPath \ "statuses_count").read[Int]
  )(Account.apply _)
}

case class AccountUpdateData(displayName: Option[String],
                             note: Option[String],
                             avatar: Option[String],
                             header: Option[String])

object AccountUpdateData {
  //noinspection ConvertExpressionToSAM
  implicit val writes: Writes[AccountUpdateData] = new Writes[AccountUpdateData] {
    override def writes(o: AccountUpdateData): JsValue = {
      val mappings = Seq(
        "display_name" -> o.displayName,
        "note" -> o.note,
        "avatar" -> o.avatar,
        "header" -> o.header
      ).collect { case (key, opt) if opt.nonEmpty => key -> Json.toJsFieldJsValueWrapper(opt.get) }

      Json.obj(mappings: _*)
    }
  }
} 
开发者ID:schwitzerm,项目名称:scaladon,代码行数:61,代码来源:Account.scala

示例6: Users

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

import javax.inject.Inject

import org.joda.time.DateTime
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.mvc.{Action, BodyParsers, Controller}
import play.modules.reactivemongo.{MongoController, ReactiveMongoApi, ReactiveMongoComponents}
import reactivemongo.bson.{BSONDocument, BSONObjectID}
import repos.UserRepoImpl



class Users @Inject()(val reactiveMongoApi: ReactiveMongoApi) extends Controller
  with MongoController with ReactiveMongoComponents{

  import models.UserFields._

  def userRepo = new UserRepoImpl(reactiveMongoApi)

  def create = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim Anlegen
    implicit request =>
      val name = (request.body \ Name).as[String]
      val password = (request.body \ Password).as[String]
      val email = (request.body \ EMail).as[String]
      userRepo.save(BSONDocument(
        Name -> name,
        Password -> password,
        EMail -> email,
        CreatedAt -> DateTime.now.toString
      )).map(result => Created("Created"))
  }

  def read(id: String) = Action.async{ implicit request =>
    userRepo.select(BSONDocument(Id -> BSONObjectID(id))).map(exercise => Ok(Json.toJson(exercise)))
  }


  def update(id: String) = Action.async(BodyParsers.parse.json) { // TODO: Prüfen dass name und email eindeutig sind beim updaten
    implicit request =>
      val name = (request.body \ Name).asOpt[String]
      val password = (request.body \ Password).asOpt[String]
      val email = (request.body \ EMail).asOpt[String]
      userRepo.update(BSONDocument( Id -> BSONObjectID(id)),
        BSONDocument("$set" -> BSONDocument(
          Name -> name,
          Password -> password,
          EMail -> EMail
      ))).map(result => Accepted)
  }

  def delete(id: String) = Action.async{
    userRepo.remove(BSONDocument(Id -> BSONObjectID(id))).map(result => Accepted("Deleted: "+ id ))
  }

} 
开发者ID:NorbertEbenhoeh,项目名称:projectX,代码行数:58,代码来源:Users.scala

示例7: RecordPaymentRequest

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

import models.Entry
import org.joda.time.{DateTime, DateTimeZone}

import scala.util.Try


case class RecordPaymentRequest(
                            coupleId: Long,
                            payerUserId: Long,
                            amount: Double,
                            submitterUserId: Long
                          ) {
  def toEntry: Try[Entry] = Try {
    val subPer = if (submitterUserId == payerUserId) 0 else 100
    Entry(
      id = None,
      coupleId = coupleId,
      date = DateTime.now(DateTimeZone.UTC),
      payerUserId = payerUserId,
      amount = amount,
      submitterUserId = submitterUserId,
      submitterPercent = subPer
    )
  }
} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPaymentRequest.scala

示例8: RecordPurchaseRequest

//设置package包名称以及导入依赖的类
package controllers.DTO
import models.Entry
import org.joda.time.{DateTime, DateTimeZone}

import scala.util.Try


case class RecordPurchaseRequest(
                               payerUserId: Long,
                               amount: Double,
                               submitterPercent: Long,
                               note: Option[String]
) {
  def toEntry(coupleId: Long, submitterUserId: Long): Try[Entry] = Try {
    Entry(
      id = None,
      coupleId = coupleId,
      date = DateTime.now(DateTimeZone.UTC),
      payerUserId = payerUserId,
      amount = amount,
      submitterUserId = submitterUserId,
      submitterPercent = submitterPercent,
      note = note
    )
  }

} 
开发者ID:JAGormley,项目名称:dutch-scala,代码行数:28,代码来源:RecordPurchaseRequest.scala

示例9: PersonEmploymentHistoryFactory

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

import domain.users.PersonEmploymentHistory
import org.joda.time.DateTime


class PersonEmploymentHistoryFactory {
  def createPersonEmploymentHistory(values: Map[String, String], date:DateTime, stringMap: Map[String, BigDecimal]):PersonEmploymentHistory={
    PersonEmploymentHistory(organisationId = values("organisationId"), userId = values("userId"), personEmploymentHistoryId = values("personEmploymentHistoryId"),
      companyName = values("companyName"), companyAddress = values("companyAddress"), companyTelephone = values("companyTelephone"),
      applicantSupervisor = values("applicantSupervisor"), contactSupervisor = values("contactSupervisor"), reasonsForLeaving = values("reasonsForLeaving"),
      startDate = date, endDate = date, startingSalary = stringMap("startingSalary"), endingSalary = stringMap("endingSalary"),
      currencyId = values("currencyId"), jobResponsibility = values("jobResponsibility"), jobId = values("jobId"), date = date,
      state = values("state"))
  }

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:18,代码来源:PersonEmploymentHistoryFactory.scala

示例10: PositionPackageFactory

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

import domain.position.PositionPackage
import org.joda.time.DateTime


class PositionPackageFactory {
  def createPositionPackageFactory(values:Map[String, String], date:DateTime): PositionPackage = {
  PositionPackage(positionId = values("positionId"),
    positionPackageId = values("positionPackageId"),
    gradeId = values("gradeId"),
    notchId = values("notchId"),
    state = values("state"),
    date = DateTime)
  }

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:18,代码来源:PositionPackageFactory.scala

示例11: TrainingInstitutionLocation

//设置package包名称以及导入依赖的类
package domain.training.institutions

import org.joda.time.DateTime
import play.api.libs.json.Json


case class TrainingInstitutionLocation(organisationId: String,
                                  TrainingInstitutionLocationId: String,
                                  name: String,
                                  locationTypeId: String,
                                  code: String,
                                  latitude: String,
                                  longitude: String,
                                  state: String,
                                  date: DateTime)
object TrainingInstitutionLocation{
  implicit val traningInstitutionFmt = Json.format[TrainingInstitutionLocation]

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:20,代码来源:TrainingInstitutionLocation.scala

示例12: PersonLanguage

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

import org.joda.time.DateTime
import play.api.libs.json.Json


case class PersonLanguage(organisationId: String,
                          userId: String,
                          personLanguageId: String,
                          languageId: String,
                          reading: String,
                          writing: String,
                          speaking: String,
                          date: DateTime,
                          state: String)

object PersonLanguage {
  implicit val personLangFmt = Json.format[PersonLanguage]

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:21,代码来源:UserLanguage.scala

示例13: PersonImages

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

import org.joda.time.DateTime
import play.api.libs.json.Json


case class PersonImages(organisationId: String,
                        userId: String,
                        personImageId: String,
                        url: String,
                        description: String,
                        mime: String,
                        size: Option[String],
                        date: DateTime)

object PersonImages {
  implicit val companyImagesFmt = Json.format[PersonImages]

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:20,代码来源:UserImage.scala

示例14: PersonDemographics

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

import org.joda.time.DateTime
import play.api.libs.json.Json


case class PersonDemographics(organisationId: String,
                              userId: String,
                              personDemographicsId: String,
                              genderId: String,
                              dateOfBirth: DateTime,
                              maritalStatusId: String,
                              numberOfDependencies: Int,
                              date: DateTime,
                              state: String)

object PersonDemographics {
  implicit val personDemoFmt = Json.format[PersonDemographics]

} 
开发者ID:Masebeni,项目名称:hwork,代码行数:21,代码来源:UserDemographics.scala

示例15: PersonAttachment

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


import org.joda.time.DateTime
import play.api.libs.json.Json


case class PersonAttachment(organisationId: String,
                            userId: String,
                            personAttachmentId: String,
                            url: String,
                            description: String,
                            mime: String,
                            date: DateTime
                           )

object PersonAttachment {
  implicit val personAttachmentFmt = Json.format[PersonAttachment]
} 
开发者ID:Masebeni,项目名称:hwork,代码行数:20,代码来源:UserAttachment.scala


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