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


Scala Calendar类代码示例

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


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

示例1: DateUtil

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

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}


object DateUtil {

  private val dateFmt = "yyyy-MM-dd"

  def today(): String = {
    val date = new Date
    val sdf = new SimpleDateFormat(dateFmt)
    sdf.format(date)
  }

  def yesterday(): String = {
    val calender = Calendar.getInstance()
    calender.roll(Calendar.DAY_OF_YEAR, -1)
    val sdf = new SimpleDateFormat(dateFmt)
    sdf.format(calender.getTime())
  }

  def daysAgo(days: Int): String = {
    val calender = Calendar.getInstance()
    calender.roll(Calendar.DAY_OF_YEAR, -days)
    val sdf = new SimpleDateFormat(dateFmt)
    sdf.format(calender.getTime())
  }

} 
开发者ID:youzp,项目名称:spark-utils,代码行数:32,代码来源:DateUtil.scala

示例2: GMMClusteringPersist

//设置package包名称以及导入依赖的类
package org.sparksamples.gmm

import java.text.SimpleDateFormat

import org.apache.spark.SparkConf
import org.apache.spark.ml.clustering.{GaussianMixture}
import org.apache.spark.sql.SparkSession


object GMMClusteringPersist {
  val PATH = "/home/ubuntu/work/spark-2.0.0-bin-hadoop2.7/"
  val BASE = "./data/movie_lens_libsvm_2f"

  val time = System.currentTimeMillis()
  val formatter = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss")

  import java.util.Calendar
  val calendar = Calendar.getInstance()
  calendar.setTimeInMillis(time)
  val date_time = formatter.format(calendar.getTime())

  def main(args: Array[String]): Unit = {

    val spConfig = (new SparkConf).setMaster("local[1]").setAppName("SparkApp").
      set("spark.driver.allowMultipleContexts", "true")

    val spark = SparkSession
      .builder()
      .appName("Spark SQL Example")
      .config(spConfig)
      .getOrCreate()

    val datasetUsers = spark.read.format("libsvm").load(
      BASE + "/movie_lens_2f_users_libsvm/part-00000")
    datasetUsers.show(3)

    val gmmUsers = new GaussianMixture().setK(5).setSeed(1L)
    gmmUsers.setMaxIter(20)
    val modelUsers = gmmUsers.fit(datasetUsers)

    val predictedDataSetUsers = modelUsers.transform(datasetUsers)
    val predictionsUsers = predictedDataSetUsers.select("prediction").rdd.map(x=> x(0))
    predictionsUsers.saveAsTextFile(BASE + "/prediction/" + date_time + "/gmm_2f_users")


    val dataSetItems = spark.read.format("libsvm").load(BASE +
      "/movie_lens_2f_items_libsvm/part-00000")


    val gmmItems = new GaussianMixture().setK(5).setSeed(1L)
    val modelItems = gmmItems.fit(dataSetItems)

    val predictedDataSetItems = modelItems.transform(dataSetItems)
    val predictionsItems = predictedDataSetItems.select("prediction").rdd.map(x=> x(0))
    predictionsItems.saveAsTextFile(BASE + "/prediction/" + date_time + "/gmm_2f_items")
    spark.stop()
  }
} 
开发者ID:PacktPublishing,项目名称:Machine-Learning-with-Spark-Second-Edition,代码行数:59,代码来源:GMMClusteringPersist.scala

示例3: shows

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

import java.util.Calendar

trait Show[A] {
  def shows(a: A): String
}

object Show {
  def showA[A]: Show[A] = new Show[A] {
    def shows(a: A): String = a.toString 
  }
  implicit val stringShow  = showA[String]
  implicit val intShow     = showA[Int]
  implicit val longShow    = showA[Long]
  implicit val bigIntShow  = showA[BigInt]
  implicit val booleanShow = showA[Boolean]
  implicit val doubleShow  = showA[Double]
  implicit val calendarShow: Show[Calendar] = new Show[Calendar] {
    def shows(a: Calendar): String = javax.xml.bind.DatatypeConverter.printDateTime(a)
  }
  implicit def seqShow[A: Show]: Show[Seq[A]] = new Show[Seq[A]] {
    def shows(as: Seq[A]): String = {
      val f = implicitly[Show[A]]
      (as map f.shows).mkString(",")
    }
  }
} 
开发者ID:eed3si9n,项目名称:gigahorse-github,代码行数:29,代码来源:show.scala

示例4: CheckResult

//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.DataQuality.checks

import java.text.SimpleDateFormat
import java.util.Calendar



case class CheckResult(
                         checkId: String,
                         checkName: String,
                         checkDescription: String,
                         checkedFile: String,
                         baseMetric: String,
                         comparedMetric: Option[String],
                         comparedThreshold: Double,
                         status: String,
                         message: String,
                         execData:String = {
                           val formatDate = new SimpleDateFormat("yyyy-MM-dd:hhmmss")
                           val now  = Calendar.getInstance().getTime
                           formatDate.format(now)
                         }
                      ) 
开发者ID:agile-lab-dev,项目名称:DataQuality,代码行数:24,代码来源:CheckResult.scala

示例5: getType

//设置package包名称以及导入依赖的类
package it.agilelab.bigdata.DataQuality.metrics

import java.text.SimpleDateFormat
import java.util.Calendar





trait MetricResult {
  val id: String
  val name: String
  val result: Double
  val execDate: String = {
    val format = new SimpleDateFormat("yyyy-MM-dd")
    format.format(Calendar.getInstance().getTime)
  }
  val sourceId: String
  def getType: String
}

case class ColumnMetricResult(
                               id:String,
                               name: String,
                               sourceId: String,
                               columnName: String,
                               result: Double
                             ) extends MetricResult {
  override def getType = "Column"
}

case class FileMetricResult(
                             id:String,
                             name: String,
                             sourceId: String,
                             result: Double
                           ) extends MetricResult {
  override def getType: String = "File"
}

case class ComposedMetricResult(
                               id: String,
                               name: String,
                               sourceId: String,
                               formula: String,
                               result: Double
                               ) extends MetricResult {
  override def getType: String = "Composed"
} 
开发者ID:agile-lab-dev,项目名称:DataQuality,代码行数:50,代码来源:MetricResult.scala

示例6: getCurrentTime

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

import java.text.SimpleDateFormat
import java.util.Calendar


  def getCurrentTime(format:SimpleDateFormat):String = {
    val now = Calendar.getInstance().getTime()
    val times = format.format(now)
    times
  }


  def dateAdd(date:String,interval:Int):String={
    val calendar = Calendar.getInstance()
    val de = yyyyMMdd.parse(date)
    calendar.setTime(de)
    calendar.add(Calendar.DATE,interval)
    yyyyMMdd.format(calendar.getTime)
  }

} 
开发者ID:jacktomcat,项目名称:ytda,代码行数:23,代码来源:DateTools.scala

示例7: TestYoutube

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

import java.text.SimpleDateFormat
import java.util.Calendar


object TestYoutube {


  def main(args: Array[String]) {
    val now = Calendar.getInstance().getTime()
    val format = new SimpleDateFormat("yyyy-MM-dd")
    val times = format.format(now)

    val inc_sql="INSERT TABLE episodes_day_count " +
      "select " +
      "enc.id," +
      "enc.yt_view_count now_view_count," +
      "eyc.yt_view_count yesterday_view_count," +
      "enc.yt_view_count - eyc.yt_view_count today_view_count, " +
      "'"+times+"' view_date "+
      "from episodes_now_count enc left join episodes_yesterday_count eyc on enc.id=eyc.id"

    println(inc_sql)
  }
} 
开发者ID:jacktomcat,项目名称:ytda,代码行数:27,代码来源:TestYoutube.scala

示例8: DateUtils

//设置package包名称以及导入依赖的类
package com.zjlp.face.spark.util

import java.text.SimpleDateFormat
import java.util.{Calendar, Date}

object DateUtils extends scala.Serializable {
  private val cal = Calendar.getInstance()

  
  def getQuarterStartTime(strDate: String, formatText: String): String = {
    val c = strToCalendar(strDate, formatText)
    val currentMonth = c.get(Calendar.MONTH) + 1
    if (currentMonth >= 1 && currentMonth <= 3)
      c.set(Calendar.MONTH, 0)
    else if (currentMonth >= 4 && currentMonth <= 6)
      c.set(Calendar.MONTH, 3)
    else if (currentMonth >= 7 && currentMonth <= 9)
      c.set(Calendar.MONTH, 6)
    else if (currentMonth >= 10 && currentMonth <= 12)
      c.set(Calendar.MONTH, 9)
    c.set(Calendar.DATE, 1)
    new SimpleDateFormat(formatText).format(c.getTime)
  }
} 
开发者ID:luciuschina,项目名称:spark-relation-search,代码行数:25,代码来源:DateUtils.scala

示例9: Entrypoint

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

import java.util.Calendar

object Entrypoint extends App {

  case class Config(entity: String = "", dest: String = "elasticsearch",
                    query: String = "", dateFilter: Option[Calendar] = None)

  private val supportedEntities = "test-group" :: "test-session" :: Nil
  private val destinations = "elasticsearch" :: "solr" :: Nil

  val parser = new scopt.OptionParser[Config]("cassandra-exporter") {
    head("cassandra-exporter")

    opt[String]("entity").required().action((x, c) =>
      c.copy(entity = x)).text("entity to export, e.g. test-session, test-group").
      validate(f => if (supportedEntities.contains(f)) success else failure(s"$f is not supported"))

    opt[String]("dest").required().action((x, c) =>
      c.copy(dest = x)).text("export destination, e.g. elasticsearch, solr").
      validate(f => if (destinations.contains(f)) success else failure(s"$f is not supported"))

    opt[String]("query").optional().action((x, c) =>
      c.copy(query = x)).text("cassandra query to call on export")

    opt[Calendar]("dateFilter").optional().action((x, c) =>
      c.copy(dateFilter = Some(x))).text("date to filter out records in the pipeline")

    help("help").text("prints this usage text")
  }

  parser.parse(args, Config()) match {
    case Some(Config("test-group", "elasticsearch", query, dateFilter)) =>
      TestGroupExporter(query, dateFilter.map(_.getTime))
    case Some(Config("test-group", "solr", query, dateFilter)) =>
      TestGroupExporterSolr(query, dateFilter.map(_.getTime))
    case Some(Config("test-session", "elasticsearch", query, dateFilter)) =>
      TestSessionExporter(query, dateFilter.map(_.getTime))
    case Some(Config("test-session", "solr", query, dateFilter)) =>
      TestSessionExporterSolr(query, dateFilter.map(_.getTime))
    case _ =>
    // arguments are bad, error message will have been displayed
  }
} 
开发者ID:ef-ice,项目名称:cassandra-exporter,代码行数:46,代码来源:Entrypoint.scala

示例10: RichDate

//设置package包名称以及导入依赖的类
package me.danielpes.spark.datetime

import java.util.Calendar

private[datetime] class RichDate[A <: java.util.Date](val datetime: A) {

  private def getCalendar: Calendar = {
    val c = Calendar.getInstance()
    c.setTime(datetime)
    c
  }

  def +(period: Period): A = {
    val c = getCalendar
    c.add(Calendar.MONTH, period.totalMonths)
    val totalMillis = c.getTimeInMillis + period.totalMilliseconds

    datetime match {
      case _: java.sql.Date => new java.sql.Date(totalMillis).asInstanceOf[A]
      case _: java.sql.Timestamp => new java.sql.Timestamp(totalMillis).asInstanceOf[A]
    }
  }

  def -(p: Period): A = this + (-p)

  def between[B <: java.util.Date](lower: B, upper: B, includeBounds: Boolean = true): Boolean = {
    if (includeBounds) datetime.getTime >= lower.getTime && datetime.getTime <= upper.getTime
    else datetime.getTime > lower.getTime && datetime.getTime < upper.getTime
  }

  def toTimestamp: java.sql.Timestamp = new java.sql.Timestamp(datetime.getTime)
  def toDate: java.sql.Date = {
    // We need to reset the time, because java.sql.Date contains time information internally.
    val c = getCalendar
    c.set(Calendar.MILLISECOND, 0)
    c.set(Calendar.SECOND, 0)
    c.set(Calendar.MINUTE, 0)
    c.set(Calendar.HOUR_OF_DAY, 0)
    new java.sql.Date(c.getTimeInMillis)
  }
} 
开发者ID:danielpes,项目名称:spark-datetime-lite,代码行数:42,代码来源:RichDate.scala

示例11: RunDesignTemplateReader

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



import java.nio.file.Path
import java.text.SimpleDateFormat
import java.util.{Calendar, UUID}

import com.pacbio.common.models.{XmlTemplateReader => GenTemplateReader}
import scala.xml.Node

class RunDesignTemplateReader(xmlFile: Path) {
  private def randomId(): UUID = UUID.randomUUID()
  private def randomContextId(): String = toRandomMovieContextId("SIM")
  private var subreadSetUuid : Option[UUID] = None

  def toRandomMovieContextId(instrument:String) = {
    val sx = new SimpleDateFormat("yyMMdd_HHmmss").format(Calendar.getInstance().getTime)
    s"m${instrument}_$sx"
  }


  private val getSubreadsetUuid = {
    subreadSetUuid = Some(randomId())
    subreadSetUuid.get
  }

  def read :Node =
    GenTemplateReader
      .fromFile(xmlFile)
      .globally()            .substitute("{RUN_ID}", randomId())
      .perInstance()         .substitute("{STATUS}", "Ready")
      //.perInstance()         .substitute("{movieLengthInMins}", movieLenInMins())
      .perNode("SubreadSet") .substituteMap {
      val collectionContextId = randomContextId()
      Map(
        "{SUBREAD_ID}"           -> (() => getSubreadsetUuid),
        "{EXTERNAL_RESOURCE_ID}" -> (() => randomId())
        //"{collectionContextId}" -> (() => collectionContextId),
        //"{collectionPathUri}"   -> (() => s"//pbi/collections/xfer-test/$collectionContextId/1_A01/$runId/")
        //"{movieLengthInMins}"   -> (() => movieLengthInMins)
      )
    }.result()

  def readStr = read.mkString

  def readRundesignTemplateInfo = RunDesignTemplateInfo(readStr, subreadSetUuid.get)
} 
开发者ID:PacificBiosciences,项目名称:smrtflow,代码行数:49,代码来源:RunDesignTemplateReader.scala

示例12: index

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

import javax.inject._
import play.api._
import play.api.mvc._

import play.api.data._
import play.api.data.Forms._

import models.Task
import java.util.Calendar
import java.text.SimpleDateFormat


  def index = Action {
    //Ok(views.html.index("Your new application is ready."))
    Redirect(routes.HomeController.tasks)
  }

  def tasks = Action {
      Ok(views.html.index(Task.all(), taskForm))
  }

  def deleteTask(id: Long) = Action {
  	Task.delete(id)
  	Redirect(routes.HomeController.tasks)
  }

  def completeTask(id: Long) = Action {
        Task.complete(id)
        Redirect(routes.HomeController.tasks)
  }

  val taskForm = Form(
    tuple (
      "label" -> nonEmptyText,
      "who" -> nonEmptyText
    )
  )

  def newTask = Action { implicit request =>
      taskForm.bindFromRequest.fold(
        errors => BadRequest(views.html.index(Task.all(), errors)),
        x=>x match { case(label,who) => {
          // ???????? ??????? ?????
          val today = Calendar.getInstance().getTime()
          val timeFormat = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss")
          val time = timeFormat.format(today)
          //----------------------------
          Task.create(label, who, time)
          Redirect(routes.HomeController.tasks)
          }
        }
      )
  }
} 
开发者ID:smoothcriminal78,项目名称:todoapplic,代码行数:57,代码来源:HomeController.scala

示例13: Block

//设置package包名称以及导入依赖的类
package dk.diku.freechain

import org.json4s._
import org.json4s.native.JsonMethods._
import java.text.SimpleDateFormat
import java.util.Calendar
import com.roundeights.hasher.Implicits._

case class Block(loaves: Seq[Loaf], height: Int,
  previousBlockHash: String, timestamp: String,
  data: JValue, hash: String)(implicit validator: Validator) {

  lazy val calculateHash: String = {
    val strippedJson = compact(render(Loaf.sortJson(JObject(
      toJson.obj.filter(_._1 != "hash")
    ))))
    strippedJson.toString.sha256
  }

  lazy val validate: Boolean =
    (loaves.foldLeft(true) ((and, l) => and && l.validate)) &&
    validator.block(this)

  lazy val toJson = JObject(
    "loaves" -> JArray(loaves.map(l => l.toJson).toList),
    "height" -> JInt(height),
    "previous_block_hash" -> JString(previousBlockHash),
    "timestamp" -> JString(timestamp),
    "data" -> data,
    "hash" -> JString(hash)
  )
}

object Block {

  def generateBlock(loaves: Seq[Loaf], previousBlock: Block, data: JValue)
    (implicit validator: Validator) = {
    val timestamp: String = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").
      format(Calendar.getInstance().getTime())
    val hash = new Block(loaves, previousBlock.height+1,
      previousBlock.hash, timestamp, data, "").calculateHash
    new Block(loaves, previousBlock.height+1,
      previousBlock.hash, timestamp, data, hash)
  }
} 
开发者ID:peteremiljensen,项目名称:freechain-scala,代码行数:46,代码来源:Block.scala

示例14: Listing2_4

//设置package包名称以及导入依赖的类
package net.nomadicalien.ch2

import java.util.Calendar

import net.nomadicalien.ch2.Listing2_1.{Amount, DateRange}
import net.nomadicalien.ch2.Listing2_3.{Account, SavingsAccount}

import scala.util.Try


object Listing2_4 {

  import Listing2_3.AccountService._

  //Sample list of savings accounts
  val s1 = SavingsAccount("dg", "sb001")
  val s2 = SavingsAccount("sr", "sb002")
  val s3 = SavingsAccount("ty", "sb003")

  val dateRange = {
    val d1 = {
      val c = Calendar.getInstance()
      c.set(2016, Calendar.JANUARY, 1)
      c.getTime
    }
    val d2 = {
      val c = Calendar.getInstance()
      c.set(2017, Calendar.JANUARY, 1)
      c.getTime
    }
    DateRange(d1, d2)
  }

  // Maps over a list of savings accounts; computes interest for each of them
  List(s1, s2, s3).map(calculateInterest(_, dateRange))

  //Finds total interest accumulated in a list of savings accounts
  List(s1, s2, s3).map(calculateInterest(_, dateRange)).foldLeft(0: Amount)((a, e) => e.map(_ + a).getOrElse(a))

  // Gets list of interest calculated using the e filter combinator
  List(s1, s2, s3).map(calculateInterest(_, dateRange)).filter(_.isSuccess)

  def getCurrencyBalance(a: Account): Try[Amount]                      = ???
  def getAccountFrom(no: String): Try[Account]                         = ???
  def calculateNetAssetValue(a: Account, balance: Amount): Try[Amount] = ???

  // Lists net asset value from an account number if net asset value > 100,000
  val result: Try[(Account, Amount)] = for {
    s <- getAccountFrom("a1")
    b <- getCurrencyBalance(s)
    v <- calculateNetAssetValue(s, b)
    if v > 100000.0
  } yield (s, v)
} 
开发者ID:BusyByte,项目名称:functional-n-reactive-domain-modeling,代码行数:55,代码来源:Listing2_4.scala

示例15: DisclosureReportGenerators

//设置package包名称以及导入依赖的类
package hmda.publication.reports.disclosure

import java.util.Calendar
import hmda.publication.reports.ReportGenerators._
import org.scalacheck.Gen
import hmda.publication.reports.util.DateUtil._

object DisclosureReportGenerators {

  implicit def d51Gen: Gen[D51] = {
    for {
      respId <- Gen.alphaStr
      instName <- Gen.alphaStr
      year = Calendar.getInstance().get(Calendar.YEAR)
      reportDate = formatDate(Calendar.getInstance().toInstant)
      msa <- msaReportGen
      applicantIncomes <- Gen.listOfN(5, applicantIncomeGen)
      total <- totalDispositionGen
    } yield D51(respId, instName, year, reportDate, msa, applicantIncomes, total)
  }

} 
开发者ID:cfpb,项目名称:hmda-platform,代码行数:23,代码来源:DisclosureReportGenerators.scala


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