All Downloads are FREE. Search and download functionalities are using the official Maven repository.

uk.co.unclealex.days.DateAndTime.scala Maven / Gradle / Ivy

The newest version!
package uk.co.unclealex.days

import java.time.{
  Instant,
  LocalDateTime,
  OffsetDateTime,
  ZoneId,
  ZoneOffset,
  ZonedDateTime
}

case class DateAndTime(date: Date, time: Time) {
  override def toString: String = {
    f"$date ${time.hours}%02d:${time.minutes}%02d"
  }

  def toLocalDateTime: LocalDateTime = {
    LocalDateTime.of(date.toLocalDate, time.toLocalTime)
  }

  def toZonedDateTime(implicit zoneId: ZoneId): ZonedDateTime = {
    toLocalDateTime.atZone(zoneId)
  }

  def toOffsetDateTime(implicit zoneOffset: ZoneOffset): OffsetDateTime = {
    toLocalDateTime.atOffset(zoneOffset)
  }

  def toInstant(implicit zoneId: ZoneId): Instant = {
    toZonedDateTime.toInstant
  }

}

object DateAndTime {

  def apply(zonedDateTime: ZonedDateTime): DateAndTime = {
    Month.values.find(month =>
      month.month == zonedDateTime.getMonthValue
    ) match {
      case Some(month) =>
        DateAndTime(
          Date(
            MonthAndDay(zonedDateTime.getDayOfMonth, month),
            zonedDateTime.getYear
          ),
          Time(zonedDateTime.getHour, zonedDateTime.getMinute)
        )
      case None =>
        throw new IllegalArgumentException(
          s"Cannot find a month for $zonedDateTime"
        )
    }
  }

  def apply(offsetDateTime: OffsetDateTime): DateAndTime = {
    Month.values.find(month =>
      month.month == offsetDateTime.getMonthValue
    ) match {
      case Some(month) =>
        DateAndTime(
          Date(
            MonthAndDay(offsetDateTime.getDayOfMonth, month),
            offsetDateTime.getYear
          ),
          Time(offsetDateTime.getHour, offsetDateTime.getMinute)
        )
      case None =>
        throw new IllegalArgumentException(
          s"Cannot find a month for $offsetDateTime"
        )
    }
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy