java.time.LocalTime Scala Examples
The following examples show how to use java.time.LocalTime.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
Example 1
Source File: ChronoLocalDateTest.scala From scala-js-java-time with BSD 3-Clause "New" or "Revised" License | 6 votes |
package org.scalajs.testsuite.javalib.time.chrono import java.time.{DateTimeException, LocalTime, LocalDate} import java.time.chrono.ChronoLocalDate import org.junit.Test import org.junit.Assert._ import org.scalajs.testsuite.utils.AssertThrows._ class ChronoLocalDateTest { import ChronoLocalDate._ @Test def test_timeLineOrder(): Unit = { val ord = timeLineOrder val ds = Seq(LocalDate.MIN, LocalDate.of(2011, 2, 28), LocalDate.MAX) for { d1 <- ds d2 <- ds } { assertEquals(math.signum(d1.compareTo(d2)), math.signum(ord.compare(d1, d2))) } } @Test def test_from(): Unit = { for (d <- Seq(LocalDate.MIN, LocalDate.of(2011, 2, 28), LocalDate.MAX)) assertEquals(d, from(d)) for (t <- Seq(LocalTime.MIN, LocalTime.NOON, LocalTime.MAX)) expectThrows(classOf[DateTimeException], from(t)) } }
Example 2
Source File: GithubIssue387.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.github import java.time.LocalTime import com.sksamuel.avro4s.{Decoder, Encoder} import org.scalatest.matchers.should.Matchers import org.scalatest.wordspec.AnyWordSpec class GithubIssue387 extends AnyWordSpec with Matchers { val NANOSECONDS_IN_A_MICROSECOND = 1000 "LocalTime" must { "encode the value to a int represented as milliseconds since midnight" in { val localTime = LocalTime.now() val encoded = Encoder[LocalTime].encode(localTime) encoded shouldBe localTime.toNanoOfDay / NANOSECONDS_IN_A_MICROSECOND } "encode the value and truncate any precision beyond milliseconds" in { val encoded = Encoder[LocalTime].encode(LocalTime.MAX) encoded shouldBe LocalTime.MAX.toNanoOfDay / NANOSECONDS_IN_A_MICROSECOND } "encode and decode back to an equivalent LocalTime object when Local has microsecond precision" in { val localTime = LocalTime.now() val encoded = Encoder[LocalTime].encode(localTime) val decoded = Decoder[LocalTime].decode(encoded) decoded shouldBe localTime decoded.toNanoOfDay shouldBe localTime.toNanoOfDay } "encode and decode back to a LocalTime object with an equivalent time to microsecond precision" in { val encoded = Encoder[LocalTime].encode(LocalTime.MAX) val decoded = Decoder[LocalTime].decode(encoded) decoded should not be LocalTime.MAX // compare to a LocalTime.MAX that has had the time precision truncated to milliseconds decoded shouldBe LocalTime.ofNanoOfDay((LocalTime.MAX.toNanoOfDay / NANOSECONDS_IN_A_MICROSECOND) * NANOSECONDS_IN_A_MICROSECOND) } } }
Example 3
Source File: BqResultSetTest.scala From scalikejdbc-bigquery with Apache License 2.0 | 5 votes |
package scalikejdbc.bigquery import java.time.{LocalDate, LocalTime, ZoneId, ZonedDateTime} import com.google.cloud.bigquery._ import org.scalatest.flatspec.AnyFlatSpec class BqResultSetTest extends AnyFlatSpec { it should "be able to instantiate from null Schema" in { val tableResult = MockUtil.tableResultFromSeq(Nil, null) new BqResultSet(tableResult) } it should "correctly traversable" in { val row1 = Seq(BqParameter.String("first")).map(MockUtil.fieldValueFromParameter(_)) val row2 = Seq(BqParameter.String("second")).map(MockUtil.fieldValueFromParameter(_)) val row3 = Seq(BqParameter.String("third")).map(MockUtil.fieldValueFromParameter(_)) val schema = Schema.of(Field.of("name", LegacySQLTypeName.STRING)); val queryResult = MockUtil.tableResultFromSeq(Seq(row1, row2, row3), schema) val resultSet = new BqResultSet(queryResult) assert(resultSet.next()) assert(resultSet.next()) assert(resultSet.next()) assert(!resultSet.next()) } it should "correctly get value" in { val row = Seq( BqParameter.Int64(42L), BqParameter.Float64(3.14159), BqParameter.Bool(true), BqParameter.String("hello"), BqParameter.Bytes(Array[Byte](104, 101, 108, 108, 111)), BqParameter.Date(LocalDate.of(2017, 3, 22)), // BqParameter.DateTime BqParameter.Time(LocalTime.of(19, 58, 0, 0)), BqParameter.Timestamp(ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo"))) ).map(MockUtil.fieldValueFromParameter(_)) val fields = Seq( Field.of("int64_column", LegacySQLTypeName.INTEGER), Field.of("float64_column", LegacySQLTypeName.FLOAT), Field.of("bool_column", LegacySQLTypeName.BOOLEAN), Field.of("string_column", LegacySQLTypeName.STRING), Field.of("bytes_column", LegacySQLTypeName.BYTES), Field.of("date_column", LegacySQLTypeName.STRING), Field.of("time_column", LegacySQLTypeName.STRING), Field.of("timestamp_column", LegacySQLTypeName.TIMESTAMP) ) val schema = Schema.of(fields: _*) val queryResult = MockUtil.tableResultFromSeq(Seq(row), schema) val resultSet = new BqResultSet(queryResult) assert(resultSet.next()) // int64 assert(resultSet.getInt(0) == 42) assert(resultSet.getInt("int64_column") == 42) // float64 assert(resultSet.getDouble(1) == 3.14159) assert(resultSet.getDouble("float64_column") == 3.14159) // bool assert(resultSet.getBoolean(2) == true) assert(resultSet.getBoolean("bool_column") == true) // string assert(resultSet.getString(3) == "hello") assert(resultSet.getString("string_column") == "hello") // bytes assert(resultSet.getBytes(4).sameElements(Array[Byte](104, 101, 108, 108, 111))) assert(resultSet.getBytes("bytes_column").sameElements(Array[Byte](104, 101, 108, 108, 111))) // date assert(resultSet.getDate(5).toLocalDate == LocalDate.of(2017, 3, 22)) assert(resultSet.getDate("date_column").toLocalDate == LocalDate.of(2017, 3, 22)) // time assert(resultSet.getTime(6).toLocalTime == LocalTime.of(19, 58, 0, 0)) assert(resultSet.getTime("time_column").toLocalTime == LocalTime.of(19, 58, 0, 0)) // timestamp assert(resultSet.getTimestamp(7).toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant) assert(resultSet.getTimestamp("timestamp_column").toInstant == ZonedDateTime.of(2017, 3, 22, 19, 58, 0, 0, ZoneId.of("Asia/Tokyo")).toInstant) } }
Example 4
Source File: ArrayOfLocalTimesReading.scala From jsoniter-scala with MIT License | 5 votes |
package com.github.plokhotnyuk.jsoniter_scala.benchmark import java.nio.charset.StandardCharsets.UTF_8 import java.time.LocalTime import com.avsystem.commons.serialization.json._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.AVSystemCodecs._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.BorerJsonEncodersDecoders._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.DslPlatformJson._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.JacksonSerDesers._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.JsoniterScalaCodecs._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.SprayFormats._ import com.github.plokhotnyuk.jsoniter_scala.benchmark.UPickleReaderWriters._ import com.github.plokhotnyuk.jsoniter_scala.core._ import com.rallyhealth.weejson.v1.jackson.FromJson import com.rallyhealth.weepickle.v1.WeePickle.ToScala import io.circe.parser._ import org.openjdk.jmh.annotations.Benchmark import play.api.libs.json.Json import spray.json._ class ArrayOfLocalTimesReading extends ArrayOfLocalTimesBenchmark { @Benchmark def avSystemGenCodec(): Array[LocalTime] = JsonStringInput.read[Array[LocalTime]](new String(jsonBytes, UTF_8)) @Benchmark def borer(): Array[LocalTime] = io.bullet.borer.Json.decode(jsonBytes).to[Array[LocalTime]].value @Benchmark def circe(): Array[LocalTime] = decode[Array[LocalTime]](new String(jsonBytes, UTF_8)).fold(throw _, identity) @Benchmark def dslJsonScala(): Array[LocalTime] = dslJsonDecode[Array[LocalTime]](jsonBytes) @Benchmark def jacksonScala(): Array[LocalTime] = jacksonMapper.readValue[Array[LocalTime]](jsonBytes) @Benchmark def jsoniterScala(): Array[LocalTime] = readFromArray[Array[LocalTime]](jsonBytes) @Benchmark def playJson(): Array[LocalTime] = Json.parse(jsonBytes).as[Array[LocalTime]] @Benchmark def sprayJson(): Array[LocalTime] = JsonParser(jsonBytes).convertTo[Array[LocalTime]] @Benchmark def uPickle(): Array[LocalTime] = read[Array[LocalTime]](jsonBytes) @Benchmark def weePickle(): Array[LocalTime] = FromJson(jsonBytes).transform(ToScala[Array[LocalTime]]) }
Example 5
Source File: ArrayOfLocalDateTimesBenchmark.scala From jsoniter-scala with MIT License | 5 votes |
package com.github.plokhotnyuk.jsoniter_scala.benchmark import java.nio.charset.StandardCharsets.UTF_8 import java.time.{LocalDate, LocalDateTime, LocalTime} import org.openjdk.jmh.annotations.{Param, Setup} abstract class ArrayOfLocalDateTimesBenchmark extends CommonParams { @Param(Array("1", "10", "100", "1000", "10000", "100000", "1000000")) var size: Int = 1000 var obj: Array[LocalDateTime] = _ var jsonString: String = _ var jsonBytes: Array[Byte] = _ var preallocatedBuf: Array[Byte] = _ @Setup def setup(): Unit = { obj = (1 to size).map { i => val n = Math.abs(i * 1498724053) LocalDateTime.of(LocalDate.ofEpochDay(i), LocalTime.ofNanoOfDay(((n % 86000) | 0x1) * 1000000000L + (i % 4 match { case 0 => 0 case 1 => ((n % 1000) | 0x1) * 1000000 case 2 => ((n % 1000000) | 0x1) * 1000 case 3 => (n | 0x1) % 1000000000 }))) }.toArray jsonString = obj.mkString("[\"", "\",\"", "\"]") jsonBytes = jsonString.getBytes(UTF_8) preallocatedBuf = new Array[Byte](jsonBytes.length + 100) } }
Example 6
Source File: ArrayOfLocalTimesBenchmark.scala From jsoniter-scala with MIT License | 5 votes |
package com.github.plokhotnyuk.jsoniter_scala.benchmark import java.nio.charset.StandardCharsets.UTF_8 import java.time.LocalTime import org.openjdk.jmh.annotations.{Param, Setup} abstract class ArrayOfLocalTimesBenchmark extends CommonParams { @Param(Array("1", "10", "100", "1000", "10000", "100000", "1000000")) var size: Int = 1000 var obj: Array[LocalTime] = _ var jsonString: String = _ var jsonBytes: Array[Byte] = _ var preallocatedBuf: Array[Byte] = _ @Setup def setup(): Unit = { obj = (1 to size).map { i => val n = Math.abs(i * 1498724053) LocalTime.ofNanoOfDay(((n % 86000) | 0x1) * 1000000000L + (i % 4 match { case 0 => 0 case 1 => ((n % 1000) | 0x1) * 1000000 case 2 => ((n % 1000000) | 0x1) * 1000 case 3 => (n | 0x1) % 1000000000 })) }.toArray jsonString = obj.mkString("[\"", "\",\"", "\"]") jsonBytes = jsonString.getBytes(UTF_8) preallocatedBuf = new Array[Byte](jsonBytes.length + 100) } }
Example 7
Source File: Encoders.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.context.jasync import java.time.{ LocalDate, LocalDateTime, LocalTime, OffsetDateTime, ZoneId, ZonedDateTime } import java.util.Date import org.joda.time.{ DateTime => JodaDateTime, DateTimeZone => JodaDateTimeZone, LocalTime => JodaLocalTime, LocalDate => JodaLocalDate, LocalDateTime => JodaLocalDateTime } trait Encoders { this: JAsyncContext[_, _, _] => type Encoder[T] = AsyncEncoder[T] type EncoderSqlType = SqlTypes.SqlTypes case class AsyncEncoder[T](sqlType: DecoderSqlType)(implicit encoder: BaseEncoder[T]) extends BaseEncoder[T] { override def apply(index: Index, value: T, row: PrepareRow) = encoder.apply(index, value, row) } def encoder[T](sqlType: DecoderSqlType): Encoder[T] = encoder(identity[T], sqlType) def encoder[T](f: T => Any, sqlType: DecoderSqlType): Encoder[T] = AsyncEncoder[T](sqlType)(new BaseEncoder[T] { def apply(index: Index, value: T, row: PrepareRow) = row :+ f(value) }) implicit def mappedEncoder[I, O](implicit mapped: MappedEncoding[I, O], e: Encoder[O]): Encoder[I] = AsyncEncoder(e.sqlType)(new BaseEncoder[I] { def apply(index: Index, value: I, row: PrepareRow) = e(index, mapped.f(value), row) }) implicit def optionEncoder[T](implicit d: Encoder[T]): Encoder[Option[T]] = AsyncEncoder(d.sqlType)(new BaseEncoder[Option[T]] { def apply(index: Index, value: Option[T], row: PrepareRow) = { value match { case None => nullEncoder(index, null, row) case Some(v) => d(index, v, row) } } }) private[this] val nullEncoder: Encoder[Null] = encoder[Null](SqlTypes.NULL) implicit val stringEncoder: Encoder[String] = encoder[String](SqlTypes.VARCHAR) implicit val bigDecimalEncoder: Encoder[BigDecimal] = encoder[BigDecimal]((bd: BigDecimal) => bd.bigDecimal, SqlTypes.REAL) implicit val booleanEncoder: Encoder[Boolean] = encoder[Boolean](SqlTypes.BOOLEAN) implicit val byteEncoder: Encoder[Byte] = encoder[Byte](SqlTypes.TINYINT) implicit val shortEncoder: Encoder[Short] = encoder[Short](SqlTypes.SMALLINT) implicit val intEncoder: Encoder[Int] = encoder[Int](SqlTypes.INTEGER) implicit val longEncoder: Encoder[Long] = encoder[Long](SqlTypes.BIGINT) implicit val floatEncoder: Encoder[Float] = encoder[Float](SqlTypes.FLOAT) implicit val doubleEncoder: Encoder[Double] = encoder[Double](SqlTypes.DOUBLE) implicit val byteArrayEncoder: Encoder[Array[Byte]] = encoder[Array[Byte]](SqlTypes.VARBINARY) implicit val jodaDateTimeEncoder: Encoder[JodaDateTime] = encoder[JodaDateTime](SqlTypes.TIMESTAMP) implicit val jodaLocalDateEncoder: Encoder[JodaLocalDate] = encoder[JodaLocalDate](SqlTypes.DATE) implicit val jodaLocalDateTimeEncoder: Encoder[JodaLocalDateTime] = encoder[JodaLocalDateTime](SqlTypes.TIMESTAMP) implicit val dateEncoder: Encoder[Date] = encoder[Date]((d: Date) => new JodaLocalDateTime(d), SqlTypes.TIMESTAMP) implicit val encodeZonedDateTime: MappedEncoding[ZonedDateTime, JodaDateTime] = MappedEncoding(zdt => new JodaDateTime(zdt.toInstant.toEpochMilli, JodaDateTimeZone.forID(zdt.getZone.getId))) implicit val encodeOffsetDateTime: MappedEncoding[OffsetDateTime, JodaDateTime] = MappedEncoding(odt => new JodaDateTime(odt.toInstant.toEpochMilli, JodaDateTimeZone.forID(odt.getOffset.getId))) implicit val encodeLocalDate: MappedEncoding[LocalDate, JodaLocalDate] = MappedEncoding(ld => new JodaLocalDate(ld.getYear, ld.getMonthValue, ld.getDayOfMonth)) implicit val encodeLocalTime: MappedEncoding[LocalTime, JodaLocalTime] = MappedEncoding(lt => new JodaLocalTime(lt.getHour, lt.getMinute, lt.getSecond)) implicit val encodeLocalDateTime: MappedEncoding[LocalDateTime, JodaLocalDateTime] = MappedEncoding(ldt => new JodaLocalDateTime(ldt.atZone(ZoneId.systemDefault()).toInstant.toEpochMilli)) implicit val localDateEncoder: Encoder[LocalDate] = mappedEncoder(encodeLocalDate, jodaLocalDateEncoder) }
Example 8
Source File: Encoders.scala From quill with Apache License 2.0 | 5 votes |
package io.getquill.context.async import java.time.{ LocalDate, LocalDateTime, LocalTime, OffsetDateTime, ZoneId, ZonedDateTime } import java.util.Date import org.joda.time.{ DateTime => JodaDateTime, DateTimeZone => JodaDateTimeZone, LocalTime => JodaLocalTime, LocalDate => JodaLocalDate, LocalDateTime => JodaLocalDateTime } trait Encoders { this: AsyncContext[_, _, _] => type Encoder[T] = AsyncEncoder[T] type EncoderSqlType = SqlTypes.SqlTypes case class AsyncEncoder[T](sqlType: DecoderSqlType)(implicit encoder: BaseEncoder[T]) extends BaseEncoder[T] { override def apply(index: Index, value: T, row: PrepareRow) = encoder.apply(index, value, row) } def encoder[T](sqlType: DecoderSqlType): Encoder[T] = encoder(identity[T], sqlType) def encoder[T](f: T => Any, sqlType: DecoderSqlType): Encoder[T] = AsyncEncoder[T](sqlType)(new BaseEncoder[T] { def apply(index: Index, value: T, row: PrepareRow) = row :+ f(value) }) implicit def mappedEncoder[I, O](implicit mapped: MappedEncoding[I, O], e: Encoder[O]): Encoder[I] = AsyncEncoder(e.sqlType)(new BaseEncoder[I] { def apply(index: Index, value: I, row: PrepareRow) = e(index, mapped.f(value), row) }) implicit def optionEncoder[T](implicit d: Encoder[T]): Encoder[Option[T]] = AsyncEncoder(d.sqlType)(new BaseEncoder[Option[T]] { def apply(index: Index, value: Option[T], row: PrepareRow) = { value match { case None => nullEncoder(index, null, row) case Some(v) => d(index, v, row) } } }) private[this] val nullEncoder: Encoder[Null] = encoder[Null](SqlTypes.NULL) implicit val stringEncoder: Encoder[String] = encoder[String](SqlTypes.VARCHAR) implicit val bigDecimalEncoder: Encoder[BigDecimal] = encoder[BigDecimal](SqlTypes.REAL) implicit val booleanEncoder: Encoder[Boolean] = encoder[Boolean](SqlTypes.BOOLEAN) implicit val byteEncoder: Encoder[Byte] = encoder[Byte](SqlTypes.TINYINT) implicit val shortEncoder: Encoder[Short] = encoder[Short](SqlTypes.SMALLINT) implicit val intEncoder: Encoder[Int] = encoder[Int](SqlTypes.INTEGER) implicit val longEncoder: Encoder[Long] = encoder[Long](SqlTypes.BIGINT) implicit val floatEncoder: Encoder[Float] = encoder[Float](SqlTypes.FLOAT) implicit val doubleEncoder: Encoder[Double] = encoder[Double](SqlTypes.DOUBLE) implicit val byteArrayEncoder: Encoder[Array[Byte]] = encoder[Array[Byte]](SqlTypes.VARBINARY) implicit val jodaDateTimeEncoder: Encoder[JodaDateTime] = encoder[JodaDateTime](SqlTypes.TIMESTAMP) implicit val jodaLocalDateEncoder: Encoder[JodaLocalDate] = encoder[JodaLocalDate](SqlTypes.DATE) implicit val jodaLocalDateTimeEncoder: Encoder[JodaLocalDateTime] = encoder[JodaLocalDateTime](SqlTypes.TIMESTAMP) implicit val dateEncoder: Encoder[Date] = encoder[Date]((d: Date) => new JodaLocalDateTime(d), SqlTypes.TIMESTAMP) implicit val encodeZonedDateTime: MappedEncoding[ZonedDateTime, JodaDateTime] = MappedEncoding(zdt => new JodaDateTime(zdt.toInstant.toEpochMilli, JodaDateTimeZone.forID(zdt.getZone.getId))) implicit val encodeOffsetDateTime: MappedEncoding[OffsetDateTime, JodaDateTime] = MappedEncoding(odt => new JodaDateTime(odt.toInstant.toEpochMilli, JodaDateTimeZone.forID(odt.getOffset.getId))) implicit val encodeLocalDate: MappedEncoding[LocalDate, JodaLocalDate] = MappedEncoding(ld => new JodaLocalDate(ld.getYear, ld.getMonthValue, ld.getDayOfMonth)) implicit val encodeLocalTime: MappedEncoding[LocalTime, JodaLocalTime] = MappedEncoding(lt => new JodaLocalTime(lt.getHour, lt.getMinute, lt.getSecond)) implicit val encodeLocalDateTime: MappedEncoding[LocalDateTime, JodaLocalDateTime] = MappedEncoding(ldt => new JodaLocalDateTime(ldt.atZone(ZoneId.systemDefault()).toInstant.toEpochMilli)) implicit val localDateEncoder: Encoder[LocalDate] = mappedEncoder(encodeLocalDate, jodaLocalDateEncoder) }
Example 9
Source File: FutureDemo.scala From spark1.52 with Apache License 2.0 | 5 votes |
package scalaDemo import java.time.LocalTime import scala.concurrent.Future import java.time._ import java.time._ import scala.concurrent._ import scala.concurrent.duration._ import scala.concurrent._ import ExecutionContext.Implicits.global object FutureDemo extends App { Future { Thread.sleep(10000) println(s"This is the future at ${LocalTime.now}") } println(s"This is the present at ${LocalTime.now}") Thread.sleep(11000) Future { for (i <- 1 to 100) { print("A"); Thread.sleep(10) } } Future { for (i <- 1 to 100) { print("B"); Thread.sleep(10) } } Thread.sleep(2000) val f = Future { Thread.sleep(10000) 42 } println(f) Thread.sleep(11000) println(f) val f23 = Future { if (LocalTime.now.getHour > 12) throw new Exception("too late") 42 } Thread.sleep(1000) println(f23) val f4 = Future { Thread.sleep(10000); 42 } val result = Await.result(f4, 11.seconds) println(result) val f2 = Future { Thread.sleep(10000); 42 } Await.ready(f2, 11.seconds) val Some(t) = f2.value println(t) }
Example 10
Source File: JSDateTests.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.tests import java.time.{LocalDate, LocalTime} import cats.instances.option._ import cats.kernel.laws.discipline.OrderTests import dtc.instances.jsDate._ import dtc.js.JSDate import dtc.laws.{DateTimeTests, LocalDateTimeTests, ProviderTests} import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.{Arbitrary, Cogen} import dtc.instances.providers.realJSDateProvider class JSDateTests extends DTCSuiteJS { implicit val cogenT: Cogen[JSDate] = Cogen(_.jsGetTime.toLong) implicit val arbT: Arbitrary[JSDate] = Arbitrary(for { date <- arbitrary[LocalDate] time <- arbitrary[LocalTime] } yield JSDate.of(date, time)) val pairGen = overflowSafePairGen.map(t => (JSDate.of(t._1, t._2), t._3)) val ldtTests = LocalDateTimeTests[JSDate]( pairGen, genJSValidYear ) checkAll("JSDate", DateTimeTests[JSDate](pairGen).dateTime) checkAll("JSDate", ldtTests.localDateTime) checkAll("JSDate", ldtTests.monthUntilFractionHandling) checkAll("JSDate", OrderTests[JSDate].order) checkAll("JSDate", OrderTests[JSDate].partialOrder) checkAll("JSDate", OrderTests[JSDate].eqv) checkAll("JSDate", ProviderTests[JSDate](genTimeZone).provider) }
Example 11
Source File: DateEncoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.encoder import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.{AvroSchema, DefaultFieldMapper, Encoder, ImmutableRecord} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers //noinspection ScalaDeprecation class DateEncoderTest extends AnyFunSuite with Matchers { test("encode LocalTime as TIME-MILLIS") { case class Foo(s: LocalTime) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalTime.of(12, 50, 45))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(46245000000L))) } test("encode LocalDate as DATE") { case class Foo(s: LocalDate) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalDate.of(2018, 9, 10))) shouldBe ImmutableRecord(schema, Vector(java.lang.Integer.valueOf(17784))) } test("encode java.sql.Date as DATE") { case class Foo(s: Date) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Date.valueOf(LocalDate.of(2018, 9, 10)))) shouldBe ImmutableRecord(schema, Vector(java.lang.Integer.valueOf(17784))) } test("encode LocalDateTime as timestamp-nanos") { case class Foo(s: LocalDateTime) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 123))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739000000123L))) Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 123009))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739000123009L))) Encoder[Foo].encode(Foo(LocalDateTime.of(2018, 9, 10, 11, 58, 59, 328187943))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1536580739328187943L))) } test("encode Timestamp as TIMESTAMP-MILLIS") { case class Foo(s: Timestamp) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Timestamp.from(Instant.ofEpochMilli(1538312231000L)))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1538312231000L))) } test("encode Instant as TIMESTAMP-MILLIS") { case class Foo(s: Instant) val schema = AvroSchema[Foo] Encoder[Foo].encode(Foo(Instant.ofEpochMilli(1538312231000L))) shouldBe ImmutableRecord(schema, Vector(java.lang.Long.valueOf(1538312231000L))) } }
Example 12
Source File: DateDecoderTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.record.decoder import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.SchemaFor.TimestampNanosLogicalType import com.sksamuel.avro4s.{AvroSchema, Decoder, SchemaFor} import org.apache.avro.generic.GenericData import org.apache.avro.{LogicalTypes, SchemaBuilder} import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers //noinspection ScalaDeprecation class DateDecoderTest extends AnyFunSuite with Matchers { case class WithLocalTime(z: LocalTime) case class WithLocalDate(z: LocalDate) case class WithDate(z: Date) case class WithLocalDateTime(z: LocalDateTime) case class WithTimestamp(z: Timestamp) case class WithInstant(z: Instant) test("decode int to LocalTime") { val schema = AvroSchema[WithLocalTime] val record = new GenericData.Record(schema) record.put("z", 46245000000L) Decoder[WithLocalTime].decode(record) shouldBe WithLocalTime(LocalTime.of(12, 50, 45)) } test("decode int to LocalDate") { val schema = AvroSchema[WithLocalDate] val record = new GenericData.Record(schema) record.put("z", 17784) Decoder[WithLocalDate].decode(record) shouldBe WithLocalDate(LocalDate.of(2018, 9, 10)) } test("decode int to java.sql.Date") { val schema = AvroSchema[WithDate] val record = new GenericData.Record(schema) record.put("z", 17784) Decoder[WithDate].decode(record) shouldBe WithDate(Date.valueOf(LocalDate.of(2018, 9, 10))) } test("decode timestamp-millis to LocalDateTime") { val dateSchema = LogicalTypes.timestampMillis().addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376L) Decoder[WithLocalDateTime].withSchema(SchemaFor(schema)).decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376000000)) } test("decode timestamp-micros to LocalDateTime") { val dateSchema = LogicalTypes.timestampMicros().addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376001L) Decoder[WithLocalDateTime].withSchema(SchemaFor(schema)).decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376001000)) } test("decode timestamp-nanos to LocalDateTime") { val dateSchema = TimestampNanosLogicalType.addToSchema(SchemaBuilder.builder.longType) val schema = SchemaBuilder.record("foo").fields().name("z").`type`(dateSchema).noDefault().endRecord() val record = new GenericData.Record(schema) record.put("z", 1572707106376000002L) Decoder[WithLocalDateTime].decode(record) shouldBe WithLocalDateTime( LocalDateTime.of(2019, 11, 2, 15, 5, 6, 376000002)) } test("decode long to Timestamp") { val schema = AvroSchema[WithTimestamp] val record = new GenericData.Record(schema) record.put("z", 1538312231000L) Decoder[WithTimestamp].decode(record) shouldBe WithTimestamp(new Timestamp(1538312231000L)) } test("decode long to Instant") { val schema = AvroSchema[WithInstant] val record = new GenericData.Record(schema) record.put("z", 1538312231000L) Decoder[WithInstant].decode(record) shouldBe WithInstant(Instant.ofEpochMilli(1538312231000L)) } }
Example 13
Source File: DateSchemaTest.scala From avro4s with Apache License 2.0 | 5 votes |
package com.sksamuel.avro4s.schema import java.sql.{Date, Timestamp} import java.time.{Instant, LocalDate, LocalDateTime, LocalTime} import com.sksamuel.avro4s.AvroSchema import org.scalatest.funsuite.AnyFunSuite import org.scalatest.matchers.should.Matchers class DateSchemaTest extends AnyFunSuite with Matchers { test("generate date logical type for LocalDate") { case class LocalDateTest(date: LocalDate) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localdate.json")) val schema = AvroSchema[LocalDateTest] schema.toString(true) shouldBe expected.toString(true) } test("generate date logical type for Date") { case class DateTest(date: Date) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/date.json")) val schema = AvroSchema[DateTest] schema.toString(true) shouldBe expected.toString(true) } test("generate time logical type for LocalTime") { case class LocalTimeTest(time: LocalTime) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localtime.json")) val schema = AvroSchema[LocalTimeTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-nanos for LocalDateTime") { case class LocalDateTimeTest(time: LocalDateTime) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/localdatetime.json")) val schema = AvroSchema[LocalDateTimeTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-millis logical type for Instant") { case class InstantTest(instant: Instant) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/instant.json")) val schema = AvroSchema[InstantTest] schema.toString(true) shouldBe expected.toString(true) } test("generate timestamp-millis logical type for Timestamp") { case class TimestampTest(ts: Timestamp) val expected = new org.apache.avro.Schema.Parser().parse(getClass.getResourceAsStream("/timestamp.json")) val schema = AvroSchema[TimestampTest] schema.toString(true) shouldBe expected.toString(true) } }
Example 14
Source File: localtime.scala From cats-time with MIT License | 5 votes |
package io.chrisdavenport.cats.time.instances import cats._ import cats.implicits._ import java.time.LocalTime import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter.ISO_LOCAL_TIME trait localtime { final def showLocalTime(formatter: DateTimeFormatter): Show[LocalTime] = Show[String].contramap(_.format(formatter)) implicit final val localtimeInstances = new Show[LocalTime] with Order[LocalTime] with Hash[LocalTime]{ override def hash(x: LocalTime): Int = x.hashCode override def compare(x: LocalTime, y: LocalTime): Int = x.compareTo(y) override def show(x: LocalTime): String = x.format(ISO_LOCAL_TIME) } } object localtime extends localtime
Example 15
Source File: Implicits.scala From scala-cass with MIT License | 5 votes |
package com.weather.scalacass.jdk8 import com.weather.scalacass.{ CassFormatDecoder, CassFormatEncoder } import com.weather.scalacass.CassFormatDecoderVersionSpecific.codecCassFormatDecoder import CassFormatEncoder.sameTypeCassFormatEncoder import java.time.{ Instant, LocalDate, LocalTime, ZonedDateTime } import com.datastax.driver.core.{ Cluster, DataType } import com.google.common.reflect.TypeToken object Implicits { implicit val timeEncoder: CassFormatEncoder[LocalTime] = sameTypeCassFormatEncoder(DataType.time) implicit val timeDecoder: CassFormatDecoder[LocalTime] = codecCassFormatDecoder(TypeToken.of(classOf[LocalTime])) implicit val dateEncoder: CassFormatEncoder[LocalDate] = sameTypeCassFormatEncoder(DataType.date) implicit val dateDecoder: CassFormatDecoder[LocalDate] = codecCassFormatDecoder(TypeToken.of(classOf[LocalDate])) implicit val instantEncoder: CassFormatEncoder[Instant] = sameTypeCassFormatEncoder(DataType.timestamp) implicit val instantDecoder: CassFormatDecoder[Instant] = codecCassFormatDecoder(TypeToken.of(classOf[Instant])) implicit def zonedDateTimeEncoder(implicit cluster: Cluster): CassFormatEncoder[ZonedDateTime] = sameTypeCassFormatEncoder(cluster.getMetadata.newTupleType(DataType.timestamp, DataType.varchar)) implicit val zonedDateTimeDecoder: CassFormatDecoder[ZonedDateTime] = codecCassFormatDecoder(TypeToken.of(classOf[ZonedDateTime])) }
Example 16
Source File: JavaLocalTimeGenerators.scala From scalacheck-ops with Apache License 2.0 | 5 votes |
package org.scalacheck.ops.time import java.time.{Clock, Duration, LocalTime} import org.scalacheck.Gen trait JavaLocalTimeGenerators extends AbstractTimeGenerators { override type InstantType = LocalTime override type DurationType = Duration override type ParamsType = Clock override val defaultParams: Clock = Clock.systemUTC() override val defaultRange: Duration = Duration.ofHours(24) override protected[time] def now(implicit params: Clock): LocalTime = LocalTime.now(params) override def between(start: LocalTime, end: LocalTime)(implicit params: Clock): Gen[LocalTime] = { for { nanoOfDay <- Gen.choose(start.toNanoOfDay, end.toNanoOfDay) } yield LocalTime.ofNanoOfDay(nanoOfDay) } override protected[time] def addToCeil(instant: LocalTime, duration: Duration) (implicit params: Clock): LocalTime = { instant plus duration } override protected[time] def subtractToFloor(instant: LocalTime, duration: Duration) (implicit params: Clock): LocalTime = { instant minus duration } } object JavaLocalTimeGenerators extends JavaLocalTimeGenerators { final val MAX_NANOS = 999999999 }
Example 17
Source File: ParameterMappers.scala From neotypes with MIT License | 5 votes |
package neotypes package implicits.mappers import java.time.{Duration, LocalDate, LocalDateTime, LocalTime, Period, OffsetDateTime, OffsetTime, ZonedDateTime} import java.util.UUID import mappers.ParameterMapper import org.neo4j.driver.v1.Value import org.neo4j.driver.v1.types.{IsoDuration, Point} import scala.collection.Iterable import scala.jdk.CollectionConverters._ trait ParameterMappers { implicit final val BooleanParameterMapper: ParameterMapper[Boolean] = ParameterMapper.fromCast(Boolean.box) implicit final val ByteArrayParameterMapper: ParameterMapper[Array[Byte]] = ParameterMapper.identity implicit final val DoubleParameterMapper: ParameterMapper[Double] = ParameterMapper.fromCast(Double.box) implicit final val DurationParameterMapper: ParameterMapper[Duration] = ParameterMapper.identity implicit final val FloatParameterMapper: ParameterMapper[Float] = ParameterMapper.fromCast(Float.box) implicit final val IntParameterMapper: ParameterMapper[Int] = ParameterMapper.fromCast(Int.box) implicit final val IsoDurationParameterMapper: ParameterMapper[IsoDuration] = ParameterMapper.identity implicit final val LocalDateParameterMapper: ParameterMapper[LocalDate] = ParameterMapper.identity implicit final val LocalDateTimeParameterMapper: ParameterMapper[LocalDateTime] = ParameterMapper.identity implicit final val LocalTimeParameterMapper: ParameterMapper[LocalTime] = ParameterMapper.identity implicit final val LongParameterMapper: ParameterMapper[Long] = ParameterMapper.fromCast(Long.box) implicit final val OffsetDateTimeParameterMapper: ParameterMapper[OffsetDateTime] = ParameterMapper.identity implicit final val OffsetTimeParameterMapper: ParameterMapper[OffsetTime] = ParameterMapper.identity implicit final val PeriodParameterMapper: ParameterMapper[Period] = ParameterMapper.identity implicit final val PointParameterMapper: ParameterMapper[Point] = ParameterMapper.identity implicit final val StringParameterMapper: ParameterMapper[String] = ParameterMapper.identity implicit final val UUIDParameterMapper: ParameterMapper[UUID] = ParameterMapper[String].contramap(_.toString) implicit final val ValueParameterMapper: ParameterMapper[Value] = ParameterMapper.identity implicit final val ZonedDateTimeParameterMapper: ParameterMapper[ZonedDateTime] = ParameterMapper.identity private final def iterableParameterMapper[T](mapper: ParameterMapper[T]): ParameterMapper[Iterable[T]] = ParameterMapper.fromCast { col => col.iterator.map(v => mapper.toQueryParam(v).underlying).asJava } implicit final def collectionParameterMapper[T, C[_]](implicit mapper: ParameterMapper[T], ev: C[T] <:< Iterable[T]): ParameterMapper[C[T]] = iterableParameterMapper(mapper).contramap(ev) private final def iterableMapParameterMapper[V](mapper: ParameterMapper[V]): ParameterMapper[Iterable[(String, V)]] = ParameterMapper.fromCast { col => col.iterator.map { case (key, v) => key -> mapper.toQueryParam(v).underlying }.toMap.asJava } implicit final def mapParameterMapper[V, M[_, _]](implicit mapper: ParameterMapper[V], ev: M[String, V] <:< Iterable[(String, V)]): ParameterMapper[M[String, V]] = iterableMapParameterMapper(mapper).contramap(ev) implicit final def optionAnyRefParameterMapper[T](implicit mapper: ParameterMapper[T]): ParameterMapper[Option[T]] = ParameterMapper.fromCast { optional => optional.map(v => mapper.toQueryParam(v).underlying).orNull } }
Example 18
Source File: zoned.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.cats.instances import java.time.{DayOfWeek, Duration, LocalDate, LocalTime} import cats.Invariant import dtc.{Offset, TimeZoneId, Zoned} object zoned extends CatsZonedInstances trait CatsZonedInstances { implicit val zonedInvariant: Invariant[Zoned] = new Invariant[Zoned] { def imap[A, B](ev: Zoned[A])(f: A => B)(g: B => A): Zoned[B] = new Zoned[B] { def compare(x: B, y: B): Int = ev.compare(g(x), g(y)) def zone(t: B): TimeZoneId = ev.zone(g(t)) def millisecond(x: B): Int = ev.millisecond(g(x)) def second(t: B): Int = ev.second(g(t)) def minute(t: B): Int = ev.minute(g(t)) def hour(t: B): Int = ev.hour(g(t)) def dayOfMonth(t: B): Int = ev.dayOfMonth(g(t)) def dayOfWeek(x: B): DayOfWeek = ev.dayOfWeek(g(x)) def month(t: B): Int = ev.month(g(t)) def year(t: B): Int = ev.year(g(t)) def capture(date: LocalDate, time: LocalTime, zone: TimeZoneId): B = f(ev.capture(date, time, zone)) def withZoneSameInstant(x: B, zone: TimeZoneId): B = f(ev.withZoneSameInstant(g(x), zone)) def withZoneSameLocal(x: B, zone: TimeZoneId): B = f(ev.withZoneSameLocal(g(x), zone)) def offset(x: B): Offset = ev.offset(g(x)) def date(x: B): LocalDate = ev.date(g(x)) def time(x: B): LocalTime = ev.time(g(x)) def plus(x: B, d: Duration): B = f(ev.plus(g(x), d)) def minus(x: B, d: Duration): B = f(ev.minus(g(x), d)) def plusDays(x: B, days: Int): B = f(ev.plusDays(g(x), days)) def plusMonths(x: B, months: Int): B = f(ev.plusMonths(g(x), months)) def plusYears(x: B, years: Int): B = f(ev.plusYears(g(x), years)) def withYear(x: B, year: Int): B = f(ev.withYear(g(x), year)) def withMonth(x: B, month: Int): B = f(ev.withMonth(g(x), month)) def withDayOfMonth(x: B, dayOfMonth: Int): B = f(ev.withDayOfMonth(g(x), dayOfMonth)) def withHour(x: B, hour: Int): B = f(ev.withHour(g(x), hour)) def withMinute(x: B, minute: Int): B = f(ev.withMinute(g(x), minute)) def withSecond(x: B, second: Int): B = f(ev.withSecond(g(x), second)) def withMillisecond(x: B, millisecond: Int): B = f(ev.withMillisecond(g(x), millisecond)) def withTime(x: B, time: LocalTime): B = f(ev.withTime(g(x), time)) def withDate(x: B, date: LocalDate): B = f(ev.withDate(g(x), date)) def yearsUntil(x: B, until: B): Long = ev.yearsUntil(g(x), g(until)) def monthsUntil(x: B, until: B): Long = ev.monthsUntil(g(x), g(until)) def daysUntil(x: B, until: B): Long = ev.daysUntil(g(x), g(until)) def hoursUntil(x: B, until: B): Long = ev.hoursUntil(g(x), g(until)) def minutesUntil(x: B, until: B): Long = ev.minutesUntil(g(x), g(until)) def secondsUntil(x: B, until: B): Long = ev.secondsUntil(g(x), g(until)) def millisecondsUntil(x: B, until: B): Long = ev.millisecondsUntil(g(x), g(until)) def utc(x: B): (LocalDate, LocalTime) = ev.utc(g(x)) } } }
Example 19
Source File: MomentZonedDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.tests import java.time.{Duration, LocalDate, LocalTime} import cats.instances.option._ import cats.kernel.laws.discipline.OrderTests import dtc.{TimeZoneId, Zoned} import dtc.js.MomentZonedDateTime import dtc.laws.{DateTimeTests, ProviderTests, ZonedDateTimeTestData, ZonedDateTimeTests} import org.scalacheck.Arbitrary.arbitrary import org.scalacheck.{Arbitrary, Cogen, Gen} import dtc.instances.moment.providers.realMomentZonedDateTimeProvider abstract class MomentZonedDateTimeTests(instance: Zoned[MomentZonedDateTime]) extends DTCSuiteJS { implicit val zonedInstance: Zoned[MomentZonedDateTime] = instance implicit val arbT: Arbitrary[MomentZonedDateTime] = Arbitrary(for { date <- arbitrary[LocalDate] time <- arbitrary[LocalTime] zone <- arbitrary[TimeZoneId] } yield MomentZonedDateTime.of(date, time, zone)) implicit val cogenT: Cogen[MomentZonedDateTime] = cogenMomentDateTime[MomentZonedDateTime] val pairGen: Gen[(MomentZonedDateTime, Duration)] = for { zone <- arbitrary[TimeZoneId] pair <- overflowSafePairGen } yield (MomentZonedDateTime.of(pair._1, pair._2, zone), pair._3) def genDateFromPeriod(period: SameZoneOffsetPeriod): Gen[MomentZonedDateTime] = genDateTimeFromSameOffsetPeriod(period).map(tpl => MomentZonedDateTime.of(tpl._1, tpl._2, tpl._3)) val overflowSafePairGenWithinSameOffset: Gen[(MomentZonedDateTime, Duration)] = for { period <- arbitrary[SameZoneOffsetPeriod] dateTime <- genDateFromPeriod(period) duration <- genDateFromPeriod(period) .map(other => dateTime.millisecondsUntil(other)) .map(Duration.ofMillis) } yield (dateTime, duration) val genZonedTestDataSuite: Gen[ZonedDateTimeTestData[MomentZonedDateTime]] = pairGen.map { case (date, duration) => val target = date.plus(duration) ZonedDateTimeTestData(date, duration, target.offset, target.toLocalTime, target.toLocalDate) } checkAll("MomentZonedDateTime", DateTimeTests[MomentZonedDateTime](pairGen).dateTime) checkAll("MomentZonedDateTime", ZonedDateTimeTests[MomentZonedDateTime]( overflowSafePairGenWithinSameOffset, genZonedTestDataSuite, genJSValidYear, genTimeZone ).zonedDateTime) checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].order) checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].partialOrder) checkAll("MomentZonedDateTime", OrderTests[MomentZonedDateTime].eqv) checkAll("MomentZonedDateTime", ProviderTests[MomentZonedDateTime](genTimeZone).provider) } class MomentZonedDateTimeWithStrictEqualityTests extends MomentZonedDateTimeTests(dtc.instances.moment.momentZonedWithStrictEquality) class MomentZonedDateTimeWithCrossZoneEqualityTests extends MomentZonedDateTimeTests(dtc.instances.moment.momentZonedWithCrossZoneEquality)
Example 20
Source File: MomentLocalDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.tests import java.time.{LocalDate, LocalTime} import cats.instances.option._ import cats.kernel.laws.discipline.OrderTests import dtc.instances.moment._ import dtc.js.MomentLocalDateTime import dtc.laws.{DateTimeTests, LocalDateTimeTests, ProviderTests} import org.scalacheck.Arbitrary import org.scalacheck.Arbitrary.arbitrary import dtc.instances.moment.providers.realMomentLocalDateTimeProvider class MomentLocalDateTimeTests extends DTCSuiteJS { implicit val arbT: Arbitrary[MomentLocalDateTime] = Arbitrary(for { date <- arbitrary[LocalDate] time <- arbitrary[LocalTime] } yield MomentLocalDateTime.of(date, time)) implicit val cogenT = cogenMomentDateTime[MomentLocalDateTime] val pairGen = overflowSafePairGen.map(t => (MomentLocalDateTime.of(t._1, t._2), t._3)) val ldtTests = LocalDateTimeTests[MomentLocalDateTime]( pairGen, genJSValidYear ) checkAll("MomentLocalDateTimeTests", DateTimeTests[MomentLocalDateTime](pairGen).dateTime) checkAll("MomentLocalDateTimeTests", ldtTests.localDateTime) // see: https://github.com/moment/moment/issues/3029 // checkAll("MomentLocalDateTimeTests", ldtTests.localDateTime) checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].order) checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].partialOrder) checkAll("MomentLocalDateTimeTests", OrderTests[MomentLocalDateTime].eqv) checkAll("MomentLocalDateTimeTests", ProviderTests[MomentLocalDateTime](genTimeZone).provider) }
Example 21
Source File: DTCSuite.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.tests import java.time.temporal.ChronoField import java.time.temporal.ChronoUnit._ import java.time.{Duration, LocalDate, LocalTime} import dtc.TimeZoneId import org.scalacheck.{Arbitrary, Gen} import org.scalatest.funspec.AnyFunSpecLike import org.scalatest.matchers.should.Matchers import org.scalatestplus.scalacheck.ScalaCheckDrivenPropertyChecks import org.typelevel.discipline.scalatest.FunSpecDiscipline trait DTCSuite extends AnyFunSpecLike with Matchers with ScalaCheckDrivenPropertyChecks with FunSpecDiscipline { override implicit val generatorDrivenConfig: PropertyCheckConfiguration = PropertyCheckConfiguration( minSuccessful = 100 ) private val nanoOfDayRange = ChronoField.NANO_OF_DAY.range() val genLocalTime: Gen[LocalTime] = Gen.choose(nanoOfDayRange.getMinimum, nanoOfDayRange.getMaximum).map(LocalTime.ofNanoOfDay) implicit val arbLocalTime: Arbitrary[LocalTime] = Arbitrary(genLocalTime) val genDuration: Gen[Duration] = Gen.choose(Long.MinValue / 1000, Long.MaxValue / 1000) .map(l => Duration.of(l, MILLIS)) implicit val arbDuration = Arbitrary(genDuration) def genDateTimeFromSameOffsetPeriod(period: SameZoneOffsetPeriod): Gen[(LocalDate, LocalTime, TimeZoneId)] = for { date <- Gen.choose(period.startDate.toEpochDay + 1L, period.endDate.toEpochDay - 1L).map(LocalDate.ofEpochDay) timeBounds <- Gen.const( if (date == period.startDate && date == period.endDate) (period.startTime, period.endTime) else if (date == period.startDate) (period.startTime, LocalTime.MAX) else if (date == period.endDate) (LocalTime.MAX, period.endTime) else (LocalTime.MIN, LocalTime.MAX) ) time <- Gen.choose(timeBounds._1.toNanoOfDay, timeBounds._2.toNanoOfDay).map(LocalTime.ofNanoOfDay) } yield (date, time, period.zone) }
Example 22
Source File: package.scala From dtc with Apache License 2.0 | 5 votes |
package dtc import java.time.{DayOfWeek, LocalDate, LocalTime} import cats.kernel.Eq import org.scalacheck.Prop import org.scalacheck.Prop._ import org.scalacheck.util.Pretty package object laws { case class NotChangedValidator[T](before: T, after: T) { def apply[P](name: String, props: (T => P)*)(implicit E: Eq[P]): Prop = { val falsy = props.filter(prop => E.neqv(prop(before), prop(after))) if (falsy.isEmpty) proved else falsified :| { val b = Pretty.pretty(before, Pretty.Params(0)) val a = Pretty.pretty(after, Pretty.Params(0)) s"(Property $name changed. Before: $b, after: $a)" } } } def notChanged[T, P](before: T, after: T) = NotChangedValidator(before, after) // eq instances implicit val eqLocalTime: Eq[LocalTime] = Eq.fromUniversalEquals implicit val eqLocalDate: Eq[LocalDate] = Eq.fromUniversalEquals implicit val eqDayOfWeek: Eq[DayOfWeek] = Eq.fromUniversalEquals }
Example 23
Source File: LocalDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.laws import java.time.{Duration, LocalDate, LocalTime} import dtc.Local import org.scalacheck.{Arbitrary, Gen} import org.typelevel.discipline.Laws trait LocalDateTimeTests[A] extends Laws { def generalLaws: GeneralLocalDateTimeLaws[A] def laws: LocalDateTimeLaws[A] def localDateTime(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = { new DefaultRuleSet( name = "LocalDateTime", parent = None, "seconds addition laws" -> generalLaws.secondsAddition, "minutes addition laws" -> generalLaws.minutesAddition, "hours addition laws" -> generalLaws.hoursAddition, "constructor consistency" -> laws.constructorConsistency, "plain constructor consistency" -> laws.plainConstructorConsistency, "withYear laws" -> generalLaws.withYear, "withMonth laws" -> generalLaws.withMonth, "withDayOfMonth laws" -> generalLaws.withDayOfMonth, "withHour laws" -> generalLaws.withHour, "withMinute laws" -> generalLaws.withMinute, "withSecond laws" -> generalLaws.withSecond, "withMillisecond laws" -> generalLaws.withMillisecond, "withTime laws" -> generalLaws.withTime, "withDate laws" -> generalLaws.withDate, "daysUntil is consistent with addition" -> generalLaws.daysUntilIsConsistentWithPlus, "monthsUntil is consistent with addition" -> generalLaws.monthsUntilIsConsistentWithPlus, "yearsUntil counts only number of full years" -> generalLaws.yearsUntilCountsOnlyFullUnits ) } // see: https://github.com/moment/moment/issues/3029 def monthUntilFractionHandling(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = { new DefaultRuleSet( name = "LocalDateTime", parent = None, "monthsUntil counts only number of full months" -> generalLaws.monthsUntilCountsOnlyFullUnits ) } } object LocalDateTimeTests { def apply[A: Local]( gDateAndDuration: Gen[(A, Duration)], gValidYear: Gen[Int])( implicit arbA: Arbitrary[A], arbLocalTime: Arbitrary[LocalTime], arbLocalDate: Arbitrary[LocalDate]): LocalDateTimeTests[A] = new LocalDateTimeTests[A] { def laws: LocalDateTimeLaws[A] = LocalDateTimeLaws[A]( arbLocalTime.arbitrary, arbLocalDate.arbitrary ) def generalLaws: GeneralLocalDateTimeLaws[A] = GeneralLocalDateTimeLaws[A]( gDateAndDuration, arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear ) } }
Example 24
Source File: DateTimeLaws.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.laws import java.time.{Duration, LocalDate, LocalTime} import dtc._ import cats.kernel.instances.int._ import cats.kernel.instances.long._ import cats.kernel.laws.discipline.catsLawsIsEqToProp import dtc.TimePoint import org.scalacheck.Prop._ import org.scalacheck.{Arbitrary, Gen, Prop} import dtc.syntax.all._ import cats.kernel.laws._ trait DateTimeLaws[A] { implicit def D: TimePoint[A] val genA: Gen[A] val genAdditionSafeDateAndDuration: Gen[(A, Duration)] // take into account that nanos are always positive in the Duration. private def fullNumberOfSeconds(d: Duration) = { val seconds = d.getSeconds if (seconds >= 0 || d.getNano == 0) seconds else seconds + 1 } def additionAndSubtractionOfSameDuration: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) => D.plus(D.plus(x, d), d.negated()) <-> x } def additionOfZero: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, _) => D.plus(x, Duration.ZERO) <-> x } def additionOfNonZero: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) => Prop(d.isZero || (d.isNegative && D.lt(D.plus(x, d), x)) || D.gt(D.plus(x, d), x)) } def millisAddition: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) => D.plus(x, d).millisecond <-> ((x.millisecond + d.toMillis) %% 1000) } def untilSelfIsAlwaysZero: Prop = forAll(genA) { x: A => (D.millisecondsUntil(x, x) <-> 0L) && (D.secondsUntil(x, x) <-> 0L) && (D.minutesUntil(x, x) <-> 0L) && (D.hoursUntil(x, x) <-> 0L) && (D.daysUntil(x, x) <-> 0L) && (D.monthsUntil(x, x) <-> 0L) && (D.yearsUntil(x, x) <-> 0L) } def untilIsConsistentWithPlus: Prop = forAll(genAdditionSafeDateAndDuration) { case (x, d) => val altered = D.plus(x, d) val truncated = truncateToMillis(d) (D.millisecondsUntil(x, altered) <-> truncated.toMillis) && (D.secondsUntil(x, altered) <-> fullNumberOfSeconds(truncated)) && (D.minutesUntil(x, altered) <-> fullNumberOfSeconds(truncated) / SecondsInMinute) && (D.hoursUntil(x, altered) <-> fullNumberOfSeconds(truncated) / (SecondsInMinute * MinutesInHour)) } def dateMustNotThrow: Prop = forAll(genA) { x: A => D.date(x) proved } def timeMustNotThrow: Prop = forAll(genA) { x: A => D.time(x) proved } def dateFieldsAreConsistentWithToLocalDate: Prop = forAll(genA) { x: A => catsLawsIsEqToProp(x.date.getDayOfWeek <-> x.dayOfWeek) && (LocalDate.of(x.year, x.month, x.dayOfMonth) <-> x.date) } def timeFieldsAreConsistentWithToLocalTime: Prop = forAll(genA) { x: A => LocalTime.of(x.hour, x.minute, x.second, millisToNanos(x.millisecond)) <-> x.time } } object DateTimeLaws { def apply[A](gDateAndDuration: Gen[(A, Duration)])( implicit ev: TimePoint[A], arbA: Arbitrary[A]): DateTimeLaws[A] = new DateTimeLaws[A] { def D: TimePoint[A] = ev val genA: Gen[A] = arbA.arbitrary val genAdditionSafeDateAndDuration: Gen[(A, Duration)] = gDateAndDuration } }
Example 25
Source File: LocalDateTimeLaws.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.laws import java.time.temporal.{ChronoField, ChronoUnit} import java.time.{LocalDate, LocalTime} import cats.kernel.laws._ import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p} import dtc.Local import dtc.syntax.local._ import org.scalacheck.{Gen, Prop} import org.scalacheck.Prop.forAll trait LocalDateTimeLaws[A] { implicit def D: Local[A] val genLocalDate: Gen[LocalDate] val genLocalTime: Gen[LocalTime] def constructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) => val dt = D.of(date, time) p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS)) } def plainConstructorConsistency: Prop = forAll(genLocalDate, genLocalTime) { (date: LocalDate, time: LocalTime) => val dt = D.of( date.getYear, date.getMonthValue, date.getDayOfMonth, time.getHour, time.getMinute, time.getSecond, time.get(ChronoField.MILLI_OF_SECOND)) p(dt.date <-> date) && (dt.time <-> time.truncatedTo(ChronoUnit.MILLIS)) } } object LocalDateTimeLaws { def apply[A]( gLocalTime: Gen[LocalTime], gLocalDate: Gen[LocalDate])( implicit ev: Local[A]): LocalDateTimeLaws[A] = new LocalDateTimeLaws[A] { def D: Local[A] = ev val genLocalDate: Gen[LocalDate] = gLocalDate val genLocalTime: Gen[LocalTime] = gLocalTime } }
Example 26
Source File: ZonedDateTimeTests.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.laws import java.time.{Duration, LocalDate, LocalTime} import dtc.{TimeZoneId, Zoned} import org.scalacheck.{Arbitrary, Gen} import org.typelevel.discipline.Laws trait ZonedDateTimeTests[A] extends Laws { def generalLocalDateTimeLaws: GeneralLocalDateTimeLaws[A] def laws: ZonedDateTimeLaws[A] def zonedDateTime(implicit arbA: Arbitrary[A], arbD: Arbitrary[Duration]): RuleSet = { new DefaultRuleSet( name = "ZonedDateTime", parent = None, "[within same offset] seconds addition laws" -> generalLocalDateTimeLaws.secondsAddition, "[within same offset] minutes addition laws" -> generalLocalDateTimeLaws.minutesAddition, "[within same offset] hours addition laws" -> generalLocalDateTimeLaws.hoursAddition, "[within same offset] withYear laws" -> generalLocalDateTimeLaws.withYear, "[within same offset] withMonth laws" -> generalLocalDateTimeLaws.withMonth, "[within same offset] withDayOfMonth laws" -> generalLocalDateTimeLaws.withDayOfMonth, "[within same offset] withHour laws" -> generalLocalDateTimeLaws.withHour, "[within same offset] withMinute laws" -> generalLocalDateTimeLaws.withMinute, "[within same offset] withSecond laws" -> generalLocalDateTimeLaws.withSecond, "[within same offset] withMillisecond laws" -> generalLocalDateTimeLaws.withMillisecond, "[within same offset] withTime laws" -> generalLocalDateTimeLaws.withTime, "[within same offset] withDate laws" -> generalLocalDateTimeLaws.withDate, "[within same offset] daysUntil is consistent with addition" -> generalLocalDateTimeLaws.daysUntilIsConsistentWithPlus, "[within same offset] monthsUntil is consistent with addition" -> generalLocalDateTimeLaws.monthsUntilIsConsistentWithPlus, "[within same offset] yearsUntil counts only number of full years" -> generalLocalDateTimeLaws.yearsUntilCountsOnlyFullUnits, "cross-offset addition" -> laws.crossOffsetAddition, "withZoneSameInstant gives the same instant" -> laws.withZoneSameInstantGivesSameInstant, "local time difference is the offset" -> laws.localTimeAndOffsetCorrelation ) } } object ZonedDateTimeTests { def apply[A: Zoned]( gDateAndDurationWithinSameDST: Gen[(A, Duration)], gDataSuite: Gen[ZonedDateTimeTestData[A]], gValidYear: Gen[Int], gTimeZone: Gen[TimeZoneId])( implicit arbA: Arbitrary[A], arbLocalTime: Arbitrary[LocalTime], arbLocalDate: Arbitrary[LocalDate]): ZonedDateTimeTests[A] = new ZonedDateTimeTests[A] { def generalLocalDateTimeLaws: GeneralLocalDateTimeLaws[A] = GeneralLocalDateTimeLaws[A]( gDateAndDurationWithinSameDST, arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear ) def laws: ZonedDateTimeLaws[A] = ZonedDateTimeLaws[A]( gDateAndDurationWithinSameDST, gDataSuite, arbLocalTime.arbitrary, arbLocalDate.arbitrary, gValidYear, gTimeZone ) } }
Example 27
Source File: ZonedDateTimeLaws.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.laws import java.time.temporal.ChronoUnit import java.time.{Duration, LocalDate, LocalTime} import cats.kernel.laws.discipline.{catsLawsIsEqToProp => p} import cats.kernel.laws._ import cats.instances.long._ import dtc._ import dtc.syntax.zoned._ import org.scalacheck.Prop._ import org.scalacheck.{Arbitrary, Gen, Prop} trait ZonedDateTimeLaws[A] { implicit def D: Zoned[A] val genA: Gen[A] val genDateAndDurationWithinSameOffset: Gen[(A, Duration)] val genDataSuite: Gen[ZonedDateTimeTestData[A]] val genLocalDate: Gen[LocalDate] val genLocalTime: Gen[LocalTime] val genValidYear: Gen[Int] val genTimeZone: Gen[TimeZoneId] def crossOffsetAddition: Prop = forAll(genDataSuite) { data => val target = D.plus(data.source, data.diff) p(D.offset(target) <-> data.targetOffset) && (D.date(target) <-> data.targetDate) && (D.time(target) <-> data.targetTime.truncatedTo(ChronoUnit.MILLIS)) } def localTimeAndOffsetCorrelation: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) => val target = D.withZoneSameInstant(date, zone) D.time(date) <-> D.time(target).plusSeconds((date.offset.seconds - target.offset.seconds).toLong) } def withZoneSameInstantGivesSameInstant: Prop = forAll(genA, genTimeZone) { (date: A, zone: TimeZoneId) => val target = D.withZoneSameInstant(date, zone) p(D.zone(target) <-> zone) && (D.millisecondsUntil(date, target) <-> 0L) } } object ZonedDateTimeLaws { def apply[A]( gDateAndDurationWithinSameDST: Gen[(A, Duration)], gDataSuite: Gen[ZonedDateTimeTestData[A]], gLocalTime: Gen[LocalTime], gLocalDate: Gen[LocalDate], gValidYear: Gen[Int], gTimeZone: Gen[TimeZoneId])( implicit ev: Zoned[A], arbA: Arbitrary[A]): ZonedDateTimeLaws[A] = new ZonedDateTimeLaws[A] { def D: Zoned[A] = ev val genTimeZone: Gen[TimeZoneId] = gTimeZone val genDateAndDurationWithinSameOffset: Gen[(A, Duration)] = gDateAndDurationWithinSameDST val genDataSuite: Gen[ZonedDateTimeTestData[A]] = gDataSuite val genLocalDate: Gen[LocalDate] = gLocalDate val genLocalTime: Gen[LocalTime] = gLocalTime val genValidYear: Gen[Int] = gValidYear val genA: Gen[A] = arbA.arbitrary } }
Example 28
Source File: Main.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.examples import java.time.{Duration, LocalDate, LocalTime} import dtc.instances.jsDate._ import dtc.js.JSDate import scala.scalajs.js.annotation.JSExportTopLevel // scalastyle:off object Main { @JSExportTopLevel("Main") def main() = { val calendar = Calendar(List( CalendarEvent( JSDate.of(LocalDate.now(), LocalTime.of(10, 0)), JSDate.of(LocalDate.now(), LocalTime.of(11, 0)), "Breakfast" ), CalendarEvent( JSDate.of(LocalDate.now().plusDays(2), LocalTime.of(12, 0)), JSDate.of(LocalDate.now().plusDays(2), LocalTime.of(14, 0)), "Meeting" ), CalendarEvent( JSDate.of(2016, 10, 9, 11, 0), JSDate.of(2016, 10, 9, 11, 0), "Birthday party" ) )) println(calendar.eventsAfter(JSDate.now).mkString(", ")) println(calendar.onlyWorkDays.mkString(", ")) val period = Period(JSDate.now, JSDate.now.plus(Duration.ofDays(1L))) println(period.durationInMinutes) println(period.durationInSeconds) println(period.hours.mkString("\n")) } }
Example 29
Source File: Main.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.examples import java.time.{LocalDate, LocalDateTime, LocalTime, Month} import dtc.instances.localDateTime._ // scalastyle:off object Main extends App { val calendar = Calendar(List( CalendarEvent( LocalDateTime.of(LocalDate.now(), LocalTime.of(10, 0)), LocalDateTime.of(LocalDate.now(), LocalTime.of(11, 0)), "Breakfast" ), CalendarEvent( LocalDateTime.of(LocalDate.now().minusDays(2), LocalTime.of(12, 0)), LocalDateTime.of(LocalDate.now().minusDays(2), LocalTime.of(14, 0)), "Meeting" ), CalendarEvent( LocalDateTime.of(2016, Month.OCTOBER, 9, 11, 0), LocalDateTime.of(2016, Month.OCTOBER, 9, 11, 0), "Birthday party" ) )) println(calendar.eventsAfter(LocalDateTime.now().minusDays(1L)).mkString(", ")) println(calendar.onlyWorkDays.mkString(", ")) val period = Period(LocalDateTime.now(), LocalDateTime.now().plusDays(1L)) println(period.durationInMinutes) println(period.durationInSeconds) println(period.hours.mkString("\n")) }
Example 30
Source File: package.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.instances import java.time.{DayOfWeek, Duration, LocalDate, LocalTime} import dtc.{Local, Capture, TimeZoneId, Zoned} import dtc.js.{MomentDateTime, MomentLocalDateTime, MomentZonedDateTime} package object moment { implicit val momentZonedWithStrictEquality: Zoned[MomentZonedDateTime] = new MomentZonedDateTimeInstanceWithoutOrder { def compare(x: MomentZonedDateTime, y: MomentZonedDateTime): Int = MomentZonedDateTime.compareStrict(x, y) } implicit val momentLocalDTC: Local[MomentLocalDateTime] = new Local[MomentLocalDateTime] { def date(x: MomentLocalDateTime): LocalDate = x.toLocalDate def time(x: MomentLocalDateTime): LocalTime = x.toLocalTime def plus(x: MomentLocalDateTime, d: Duration): MomentLocalDateTime = x.plus(d) def minus(x: MomentLocalDateTime, d: Duration): MomentLocalDateTime = x.minus(d) def plusDays(x: MomentLocalDateTime, days: Int): MomentLocalDateTime = x.plusDays(days) def plusMonths(x: MomentLocalDateTime, months: Int): MomentLocalDateTime = x.plusMonths(months) def plusYears(x: MomentLocalDateTime, years: Int): MomentLocalDateTime = x.plusYears(years) def compare(x: MomentLocalDateTime, y: MomentLocalDateTime): Int = MomentDateTime.compare(x, y) def of(date: LocalDate, time: LocalTime): MomentLocalDateTime = MomentLocalDateTime.of(date, time) def of( year: Int, month: Int, day: Int, hour: Int, minute: Int, second: Int, millisecond: Int): MomentLocalDateTime = MomentLocalDateTime.of(year, month, day, hour, minute, second, millisecond) def withYear(x: MomentLocalDateTime, year: Int): MomentLocalDateTime = x.withYear(year) def withMonth(x: MomentLocalDateTime, month: Int): MomentLocalDateTime = x.withMonth(month) def withDayOfMonth(x: MomentLocalDateTime, dayOfMonth: Int): MomentLocalDateTime = x.withDayOfMonth(dayOfMonth) def withHour(x: MomentLocalDateTime, hour: Int): MomentLocalDateTime = x.withHour(hour) def withMinute(x: MomentLocalDateTime, minute: Int): MomentLocalDateTime = x.withMinute(minute) def withSecond(x: MomentLocalDateTime, second: Int): MomentLocalDateTime = x.withSecond(second) def withMillisecond(x: MomentLocalDateTime, millisecond: Int): MomentLocalDateTime = x.withMillisecond(millisecond) def withTime(x: MomentLocalDateTime, time: LocalTime): MomentLocalDateTime = x.withTime(time) def withDate(x: MomentLocalDateTime, date: LocalDate): MomentLocalDateTime = x.withDate(date) def dayOfWeek(x: MomentLocalDateTime): DayOfWeek = x.dayOfWeek def dayOfMonth(x: MomentLocalDateTime): Int = x.dayOfMonth def month(x: MomentLocalDateTime): Int = x.month def year(x: MomentLocalDateTime): Int = x.year def millisecond(x: MomentLocalDateTime): Int = x.millisecond def second(x: MomentLocalDateTime): Int = x.second def minute(x: MomentLocalDateTime): Int = x.minute def hour(x: MomentLocalDateTime): Int = x.hour def yearsUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.yearsUntil(until) def monthsUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.monthsUntil(until) def daysUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.daysUntil(until) def hoursUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.hoursUntil(until) def minutesUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.minutesUntil(until) def secondsUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.secondsUntil(until) def millisecondsUntil(x: MomentLocalDateTime, until: MomentLocalDateTime): Long = x.millisecondsUntil(until) } implicit val captureMomentLocalDateTime: Capture[MomentLocalDateTime] = new Capture[MomentLocalDateTime] { def capture(date: LocalDate, time: LocalTime, zone: TimeZoneId): MomentLocalDateTime = MomentZonedDateTime.of(date, time, zone).withZoneSameInstant(TimeZoneId.UTC).toLocal } }
Example 31
Source File: MomentZonedDateTimeInstanceWithoutOrder.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.instances.moment import java.time.{DayOfWeek, Duration, LocalDate, LocalTime} import dtc.js.MomentZonedDateTime import dtc.{Offset, TimeZoneId, Zoned} trait MomentZonedDateTimeInstanceWithoutOrder extends Zoned[MomentZonedDateTime] { def capture(date: LocalDate, time: LocalTime, zone: TimeZoneId): MomentZonedDateTime = MomentZonedDateTime.of(date, time, zone) def withZoneSameInstant(x: MomentZonedDateTime, zone: TimeZoneId): MomentZonedDateTime = x.withZoneSameInstant(zone) def withZoneSameLocal(x: MomentZonedDateTime, zone: TimeZoneId): MomentZonedDateTime = x.withZoneSameLocal(zone) def zone(x: MomentZonedDateTime): TimeZoneId = x.zone def date(x: MomentZonedDateTime): LocalDate = x.toLocalDate def time(x: MomentZonedDateTime): LocalTime = x.toLocalTime def plus(x: MomentZonedDateTime, d: Duration): MomentZonedDateTime = x.plus(d) def minus(x: MomentZonedDateTime, d: Duration): MomentZonedDateTime = x.minus(d) def plusDays(x: MomentZonedDateTime, days: Int): MomentZonedDateTime = x.plusDays(days) def plusMonths(x: MomentZonedDateTime, months: Int): MomentZonedDateTime = x.plusMonths(months) def plusYears(x: MomentZonedDateTime, years: Int): MomentZonedDateTime = x.plusYears(years) def offset(x: MomentZonedDateTime): Offset = x.offset def withYear(x: MomentZonedDateTime, year: Int): MomentZonedDateTime = x.withYear(year) def withMonth(x: MomentZonedDateTime, month: Int): MomentZonedDateTime = x.withMonth(month) def withDayOfMonth(x: MomentZonedDateTime, dayOfMonth: Int): MomentZonedDateTime = x.withDayOfMonth(dayOfMonth) def withHour(x: MomentZonedDateTime, hour: Int): MomentZonedDateTime = x.withHour(hour) def withMinute(x: MomentZonedDateTime, minute: Int): MomentZonedDateTime = x.withMinute(minute) def withSecond(x: MomentZonedDateTime, second: Int): MomentZonedDateTime = x.withSecond(second) def withMillisecond(x: MomentZonedDateTime, millisecond: Int): MomentZonedDateTime = x.withMillisecond(millisecond) def withTime(x: MomentZonedDateTime, time: LocalTime): MomentZonedDateTime = x.withTime(time) def withDate(x: MomentZonedDateTime, date: LocalDate): MomentZonedDateTime = x.withDate(date) def dayOfWeek(x: MomentZonedDateTime): DayOfWeek = x.dayOfWeek def dayOfMonth(x: MomentZonedDateTime): Int = x.dayOfMonth def month(x: MomentZonedDateTime): Int = x.month def year(x: MomentZonedDateTime): Int = x.year def millisecond(x: MomentZonedDateTime): Int = x.millisecond def second(x: MomentZonedDateTime): Int = x.second def minute(x: MomentZonedDateTime): Int = x.minute def hour(x: MomentZonedDateTime): Int = x.hour def yearsUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.yearsUntil(until) def monthsUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.monthsUntil(until) def daysUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.daysUntil(until) def hoursUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.hoursUntil(until) def minutesUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.minutesUntil(until) def secondsUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.secondsUntil(until) def millisecondsUntil(x: MomentZonedDateTime, until: MomentZonedDateTime): Long = x.millisecondsUntil(until) def utc(x: MomentZonedDateTime): (LocalDate, LocalTime) = { val utcTime = x.withZoneSameInstant(TimeZoneId.UTC) utcTime.toLocalDate -> utcTime.toLocalTime } }
Example 32
Source File: MomentDateTime.scala From dtc with Apache License 2.0 | 5 votes |
package dtc.js import java.time.temporal.ChronoField import java.time.{DayOfWeek, Duration, LocalDate, LocalTime} import dtc._ import moment.{Date, Moment, Units} import scala.scalajs.js.Array def underlyingMoment: Date = copy def dayOfWeek: DayOfWeek = DayOfWeek.of(dayOfWeekJSToJVM(underlying.day())) def dayOfMonth: Int = underlying.date() def month: Int = underlying.month() + 1 def year: Int = underlying.year() def hour: Int = underlying.hour() def minute: Int = underlying.minute() def second: Int = underlying.second() def millisecond: Int = underlying.millisecond() def withYear(year: Int): T = updated(_.year(year.toDouble)) def withMonth(month: Int): T = updated(_.month(month.toDouble - 1)) def withDayOfMonth(dayOfMonth: Int): T = updated(_.date(dayOfMonth.toDouble)) def withHour(hour: Int): T = updated(_.hour(hour.toDouble)) def withMinute(minute: Int): T = updated(_.minute(minute.toDouble)) def withSecond(second: Int): T = updated(_.second(second.toDouble)) def withMillisecond(millisecond: Int): T = updated(_.millisecond(millisecond.toDouble)) def withTime(time: LocalTime): T = updated(_ .hour(time.getHour.toDouble) .minute(time.getMinute.toDouble) .second(time.getSecond.toDouble) .millisecond(time.get(ChronoField.MILLI_OF_SECOND).toDouble) ) def withDate(date: LocalDate): T = updated(_ .year(date.getYear.toDouble) .month(date.getMonthValue.toDouble - 1) .date(date.getDayOfMonth.toDouble) ) def toLocalDate: LocalDate = LocalDate.of(year, month, dayOfMonth) def toLocalTime: LocalTime = LocalTime.of(hour, minute, second, millisToNanos(millisecond)) def yearsUntil(other: T): Long = other.underlying.diff(underlying, Units.Year).toLong def monthsUntil(other: T): Long = other.underlying.diff(underlying, Units.Month).toLong def daysUntil(other: T): Long = other.underlying.diff(underlying, Units.Day).toLong def millisecondsUntil(other: T): Long = other.underlying.diff(underlying, Units.Millisecond).toLong def secondsUntil(other: T): Long = other.underlying.diff(underlying, Units.Second).toLong def minutesUntil(other: T): Long = other.underlying.diff(underlying, Units.Minute).toLong def hoursUntil(other: T): Long = other.underlying.diff(underlying, Units.Hour).toLong def plus(d: Duration): T = plusMillis(d.toMillis) def minus(d: Duration): T = plusMillis(-d.toMillis) def plusDays(n: Int): T = updated(_.add(n.toDouble, Units.Day)) def plusMonths(n: Int): T = updated(_.add(n.toDouble, Units.Month)) def plusYears(n: Int): T = updated(_.add(n.toDouble, Units.Year)) def plusMillis(n: Long): T def format(formatString: String): String = underlying.format(formatString) override def toString: String = underlying.toString } object MomentDateTime { def compare[T <: MomentDateTime[T]](x: T, y: T): Int = Ordering.Double.compare(x.underlying.value(), y.underlying.value()) private[js] def constructorArray(date: LocalDate, time: LocalTime): Array[Int] = Array( date.getYear, date.getMonthValue - 1, date.getDayOfMonth, time.getHour, time.getMinute, time.getSecond, time.get(ChronoField.MILLI_OF_SECOND) ) private[js] def utcMoment(date: LocalDate, time: LocalTime): Date = Moment.utc(constructorArray(date, time)) }
Example 33
Source File: Status.scala From daf-semantics with Apache License 2.0 | 5 votes |
package it.almawave.kb.http.endpoints import java.time.LocalTime import io.swagger.annotations.Api import javax.ws.rs.Path import javax.ws.rs.GET import javax.ws.rs.Produces import io.swagger.annotations.ApiOperation import javax.ws.rs.core.MediaType import org.slf4j.LoggerFactory import javax.ws.rs.core.Context import javax.ws.rs.core.UriInfo import javax.ws.rs.core.Request import it.almawave.linkeddata.kb.utils.JSONHelper import java.time.LocalDateTime import java.time.ZonedDateTime import java.time.format.DateTimeFormatter import java.util.Locale import java.time.ZoneId @Api(tags = Array("catalog")) @Path("/status") class Status { private val logger = LoggerFactory.getLogger(this.getClass) @Context var uriInfo: UriInfo = null @GET @Produces(Array(MediaType.APPLICATION_JSON)) @ApiOperation(nickname = "status", value = "endpoint status") def status() = { val base_uri = uriInfo.getBaseUri val msg = s"the service is running at ${base_uri}" logger.info(msg) val _now = now() StatusMsg(_now._1, _now._2, msg) } def now() = { val zdt = ZonedDateTime.now(ZoneId.of("+1")) val dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ") (zdt.format(dtf), zdt) } } case class StatusMsg( now: String, dateTime: ZonedDateTime, msg: String )