Java tutorial
/** * Copyright (c) 2011 Wolox <http://www.wolox.com.ar/> * * 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 ar.com.wolox.commons.base.json; import javax.validation.constraints.NotNull; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; /** * The serialized version of {@link DateTime} * * @author Guido Marucci Blas * @since Sep 7, 2011 */ public final class JSONSerializableDateTime { /** * Creates a {@link JSONSerializableDateTime} from a {@link DateTime} * * @param date * @return */ public static JSONSerializableDateTime create(@NotNull final DateTime date) { if (date == null) { throw new IllegalArgumentException("The date to be serialized cannot be null"); } final JSONSerializableDateTime serialized = new JSONSerializableDateTime(); serialized.setIsoDate(ISODateTimeFormat.dateTime().print(date)); serialized.setTimeZone(date.getChronology().getZone().getID()); return serialized; } private String isoDate; private String timeZone; /** * Creates the JSONSerializableDateTime. */ private JSONSerializableDateTime() { } /** * @return The deserialized date time */ public DateTime toDateTime() { return ISODateTimeFormat.dateTime().withZone(DateTimeZone.forID(timeZone)).parseDateTime(isoDate); } /** * Returns the isoDate. * * @return <code>String</code> with the isoDate. */ public String getIsoDate() { return isoDate; } /** * Sets the isoDate. * * @param isoDate <code>String</code> with the isoDate. */ public void setIsoDate(@NotNull final String isoDate) { if (isoDate == null || isoDate.isEmpty()) { throw new IllegalArgumentException("The ISO date cannot be blank"); } this.isoDate = isoDate; } /** * Returns the timeZone. * * @return <code>String</code> with the timeZone. */ public String getTimeZone() { return timeZone; } /** * Sets the timeZone. * * @param timeZone <code>String</code> with the timeZone. */ public void setTimeZone(@NotNull final String timeZone) { if (timeZone == null || timeZone.isEmpty()) { throw new IllegalArgumentException("The time zone cannot be blank"); } this.timeZone = timeZone; } }