diff -r 69e26359f2c8 -r cf829ec742b3 src/main/scala/net/tz/lift/util/Helpers.scala --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/src/main/scala/net/tz/lift/util/Helpers.scala Sun Apr 03 15:55:02 2011 +0200 @@ -0,0 +1,79 @@ +/* + * Copyright 2011 Tomas Zeman + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package net.tz.lift.util + +import java.text.SimpleDateFormat +import java.util.Date +import net.liftweb.http.LiftRules +import net.liftweb.util.Helpers.tryo +import org.joda.time.{DateMidnight, DateTime, Period, ReadableInstant} +import org.joda.time.format.{DateTimeFormat, PeriodFormatterBuilder} +import scala.xml.{NodeSeq, Text} + +object AsIsoDateTime { + val df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss") + def unapply(in: String): Option[Date] = tryo { df.parse(in) } + def apply(d: Date): String = df.format(d) +} + +object AsDate { + import DateExtension._ + def unapply(in: String): Option[Date] = LiftRules.dateTimeConverter(). + parseDate(in).map(_.noTime) + def apply(d: Date) = LiftRules.dateTimeConverter().formatDate(d) +} + +object AsDateTime { + def unapply(in: String): Option[Date] = LiftRules.dateTimeConverter(). + parseDateTime(in) + def apply(d: Date) = LiftRules.dateTimeConverter().formatDateTime(d) +} + +object AsDateMidnight { + lazy val fmt = DateTimeFormat.forPattern("yyyy-MM-dd") + def unapply(in: String): Option[DateMidnight] = apply(in) + def apply(in: String): Option[DateMidnight] = tryo { + fmt.parseDateTime(in).toDateMidnight + } + def apply(d: ReadableInstant) = fmt.print(d) + + implicit def dt2d(d: DateTime): Date = d.toDate + implicit def dm2d(d: DateMidnight): Date = d.toDate + implicit def d2dm(d: Date): DateMidnight = new DateMidnight(d) + implicit def dm2dt(d: DateMidnight): DateTime = d.toDateTime +} + +object AsTimePeriod { + lazy val fmt = (new PeriodFormatterBuilder).printZeroAlways. + minimumPrintedDigits(2).appendHours. + appendSeparator(":").appendMinutes.toFormatter + lazy val fmtDt = DateTimeFormat.forPattern("HH:mm") + + /** Parses HH:mm time into period. */ + def apply(in: String): Option[Period] = tryo { fmt.parsePeriod(in) } + def apply(p: Period) = fmt.print(p) + def apply(dt: DateTime) = fmtDt.print(dt) +} + +object Bytes { + implicit def dbl2ns(d: Double): NodeSeq = + Text(String.format(fmt, d.asInstanceOf[AnyRef])) + def fmt = "%.2f" + def kb(v: Long): NodeSeq = v.toDouble / 1024 + def mb(v: Long): NodeSeq = v.toDouble / (1024*1024) +} + +// vim: set ts=2 sw=2 et: