java.time.format.DateTimeParseException Scala Examples
The following examples show how to use java.time.format.DateTimeParseException.
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: Preconditions.scala From scala-js-java-time with BSD 3-Clause "New" or "Revised" License | 5 votes |
package java.time import java.time.format.DateTimeParseException private[time] object Preconditions { // Like scala.Predef.require, but throws a DateTimeException. def requireDateTime(requirement: Boolean, message: => Any): Unit = { if (!requirement) throw new DateTimeException(message.toString) } def requireDateTimeParse(requirement: Boolean, message: => Any, charSequence: CharSequence, index: Int): Unit = { if (!requirement) throw new DateTimeParseException(message.toString, charSequence, index) } }
Example 2
Source File: TimestampFormatter.scala From XSQL with Apache License 2.0 | 5 votes |
package org.apache.spark.sql.catalyst.util import java.text.ParseException import java.time._ import java.time.format.DateTimeParseException import java.time.temporal.TemporalQueries import java.util.{Locale, TimeZone} import org.apache.spark.sql.catalyst.util.DateTimeUtils.instantToMicros sealed trait TimestampFormatter extends Serializable { @throws(classOf[ParseException]) @throws(classOf[DateTimeParseException]) @throws(classOf[DateTimeException]) def parse(s: String): Long def format(us: Long): String } class Iso8601TimestampFormatter( pattern: String, timeZone: TimeZone, locale: Locale) extends TimestampFormatter with DateTimeFormatterHelper { @transient private lazy val formatter = getOrCreateFormatter(pattern, locale) private def toInstant(s: String): Instant = { val temporalAccessor = formatter.parse(s) if (temporalAccessor.query(TemporalQueries.offset()) == null) { toInstantWithZoneId(temporalAccessor, timeZone.toZoneId) } else { Instant.from(temporalAccessor) } } override def parse(s: String): Long = instantToMicros(toInstant(s)) override def format(us: Long): String = { val secs = Math.floorDiv(us, DateTimeUtils.MICROS_PER_SECOND) val mos = Math.floorMod(us, DateTimeUtils.MICROS_PER_SECOND) val instant = Instant.ofEpochSecond(secs, mos * DateTimeUtils.NANOS_PER_MICROS) formatter.withZone(timeZone.toZoneId).format(instant) } } object TimestampFormatter { val defaultPattern: String = "yyyy-MM-dd HH:mm:ss" val defaultLocale: Locale = Locale.US def apply(format: String, timeZone: TimeZone, locale: Locale): TimestampFormatter = { new Iso8601TimestampFormatter(format, timeZone, locale) } def apply(format: String, timeZone: TimeZone): TimestampFormatter = { apply(format, timeZone, defaultLocale) } def apply(timeZone: TimeZone): TimestampFormatter = { apply(defaultPattern, timeZone, defaultLocale) } }
Example 3
Source File: InstantModule.scala From milan with Apache License 2.0 | 5 votes |
package com.amazon.milan.dataformats import java.time.format.{DateTimeFormatter, DateTimeParseException} import java.time.temporal.{TemporalAccessor, TemporalQuery} import java.time.{Instant, LocalDateTime, ZoneOffset} import com.fasterxml.jackson.core.JsonParser import com.fasterxml.jackson.databind.module.SimpleModule import com.fasterxml.jackson.databind.{DeserializationContext, JsonDeserializer} class InstantModule extends SimpleModule { this.addDeserializer[Instant](classOf[Instant], new MilanInstantDeserializer) } class MilanInstantDeserializer extends JsonDeserializer[Instant] { private val formatsToTry = List( DateTimeFormatter.ISO_INSTANT, DateTimeFormatter.ISO_DATE_TIME, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"), DateTimeFormatter.ISO_DATE) override def deserialize(parser: JsonParser, context: DeserializationContext): Instant = { val textValue = parser.getText this.parseInstant(textValue) } private val createInstant = new TemporalQuery[Instant] { override def queryFrom(temporal: TemporalAccessor): Instant = LocalDateTime.from(temporal).toInstant(ZoneOffset.UTC) } private def parseInstant(dateTimeString: String): Instant = { // Try a bunch of formats. // TODO: This is awful but will do for now. formatsToTry.map(formatter => this.tryParseFormat(dateTimeString, formatter)) .filter(_.isDefined) .map(_.get) .headOption match { case Some(instant) => instant case None => throw new DateTimeParseException(s"Unable to parse datetime string '$dateTimeString'.", dateTimeString, 0) } } private def tryParseFormat(dateTimeString: String, formatter: DateTimeFormatter): Option[Instant] = { try { Some(formatter.parse(dateTimeString, this.createInstant)) } catch { case _: DateTimeParseException => None } } }
Example 4
Source File: EventMarshalling.scala From 006877 with MIT License | 5 votes |
package aia.stream import java.time.ZonedDateTime import java.time.format.{ DateTimeFormatter, DateTimeParseException } import scala.util.Try import spray.json._ trait EventMarshalling extends DefaultJsonProtocol { implicit val dateTimeFormat = new JsonFormat[ZonedDateTime] { def write(dateTime: ZonedDateTime) = JsString(dateTime.format(DateTimeFormatter.ISO_INSTANT)) def read(value: JsValue) = value match { case JsString(str) => try { ZonedDateTime.parse(str) } catch { case e: DateTimeParseException => val msg = s"Could not deserialize $str to ZonedDateTime" deserializationError(msg) } case js => val msg = s"Could not deserialize $js to ZonedDateTime." deserializationError(msg) } } implicit val stateFormat = new JsonFormat[State] { def write(state: State) = JsString(State.norm(state)) def read(value: JsValue) = value match { case JsString("ok") => Ok case JsString("warning") => Warning case JsString("error") => Error case JsString("critical") => Critical case js => val msg = s"Could not deserialize $js to State." deserializationError(msg) } } implicit val eventFormat = jsonFormat7(Event) implicit val logIdFormat = jsonFormat2(LogReceipt) implicit val errorFormat = jsonFormat2(ParseError) }
Example 5
Source File: IsoInstant.scala From scala-commons with MIT License | 5 votes |
package com.avsystem.commons package serialization import java.time.Instant import java.time.format.DateTimeParseException import com.avsystem.commons.serialization.GenCodec.ReadFailure object IsoInstant { def format(millis: Long): String = { val res = Instant.ofEpochMilli(millis).toString // add trailing .000Z if omitted to align with JS implementation if (res.charAt(res.length - 5) == '.') res else res.substring(0, res.length - 1) + ".000Z" } def parse(string: String): Long = try Instant.parse(string).toEpochMilli catch { case _: DateTimeParseException => throw new ReadFailure(s"invalid ISO instant: $string") } }
Example 6
Source File: EpisodeSettingsExtractor.scala From scalalaz-gen with Apache License 2.0 | 5 votes |
package ru.scalalaz.gen.parsing import java.time.LocalDate import java.time.format.{ DateTimeFormatter, DateTimeParseException } import cats.Apply import cats.data.Validated.Valid import cats.data.{ Validated, ValidatedNel } import ru.scalalaz.gen.{ Enclosure, EpisodeSettings, SpecialPageSettings } object EpisodeSettingsExtractor { import ru.scalalaz.gen.parsing.EpisodeErrors._ def fromMap( map: Map[String, Option[String]] ): ValidatedNel[PageParseError, SpecialPageSettings] = new SettingsExtractor(map).extract class SettingsExtractor(map: Map[String, Option[String]]) { def extract: ValidatedNel[PageParseError, SpecialPageSettings] = Apply[ValidatedNel[PageParseError, *]].map2( read("title").toValidatedNel, read("date").andThen(parseDate).toValidatedNel ) { case (title, date) => //val enc = Enclosure(encUrl, if (encLength != "") encLength.toInt else -1) SpecialPageSettings(title, date) } private def read(key: String): Validated[PageParseError, String] = Validated.fromOption(map.get(key).flatten, MissingKey(key)) private def optRead(key: String): Validated[PageParseError, String] = Valid(map.get(key).flatten.getOrElse("")) private def parseDate( date: String ): Validated[PageParseError, LocalDate] = { def toDate = LocalDate.parse(date, DateTimeFormatter.ISO_LOCAL_DATE) Validated .catchOnly[DateTimeParseException](toDate) .leftMap(e => InvalidDate(e.getMessage)) } } }
Example 7
Source File: Rfc3339Util.scala From api-first-hand with MIT License | 5 votes |
package de.zalando.play.controllers import java.time.format.{ DateTimeFormatter, DateTimeParseException } import java.time.{ LocalDate, ZoneId, ZonedDateTime } object Rfc3339Util { private val fullDate = DateTimeFormatter.ofPattern("yyyy-MM-dd") private val shortDateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ") private val shortDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'") private val fullDTWithTicks = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'") private val dateTime = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSZ") def parseDateTime(datestring: String): ZonedDateTime = if (datestring.endsWith("Z") || datestring.endsWith("z")) parseFull(datestring) else parseParts(datestring) def parseDate(datestring: String): LocalDate = LocalDate.parse(datestring, fullDate) def writeDate(date: LocalDate): String = fullDate.format(date) def writeDateTime(date: ZonedDateTime): String = dateTime.format(date) private def parseParts(datestring: String): ZonedDateTime = { //step one, split off the timezone. val sepChar = if (datestring.indexOf('+') > 0) '+' else '-' val firstpart = datestring.substring(0, datestring.lastIndexOf(sepChar.toInt)) val secondpart = datestring.substring(datestring.lastIndexOf(sepChar.toInt)) //step two, remove the colon from the timezone offset val thirdpart = secondpart.substring(0, secondpart.indexOf(':')) + secondpart.substring(secondpart.indexOf(':') + 1) val dstring = firstpart + thirdpart try { ZonedDateTime.parse(dstring, shortDateTime) } catch { case pe: DateTimeParseException => ZonedDateTime.parse(dstring, dateTime) } } private def parseFull(datestring: String): ZonedDateTime = { val z = ZoneId.systemDefault() try { ZonedDateTime.parse(datestring, shortDTWithTicks.withZone(z)) } catch { case p: DateTimeParseException => ZonedDateTime.parse(datestring, fullDTWithTicks.withZone(z)) } } }