001/* Copyright (C) 2014 konik.io
002 *
003 * This file is part of the Konik library.
004 *
005 * The Konik library is free software: you can redistribute it and/or modify
006 * it under the terms of the GNU Affero General Public License as
007 * published by the Free Software Foundation, either version 3 of the
008 * License, or (at your option) any later version.
009 *
010 * The Konik library is distributed in the hope that it will be useful,
011 * but WITHOUT ANY WARRANTY; without even the implied warranty of
012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
013 * GNU Affero General Public License for more details.
014 *
015 * You should have received a copy of the GNU Affero General Public License
016 * along with the Konik library. If not, see <http://www.gnu.org/licenses/>.
017 */
018package io.konik.zugferd.unqualified;
019
020import java.text.ParseException;
021import java.text.SimpleDateFormat;
022import java.util.Date;
023
024/**
025 * ZUGFeRD Specific Date with a format code.
026 */
027public abstract class ZfDate extends Date {
028
029   private static final long serialVersionUID = -6394296382630804411L;
030
031   /**
032    * Instantiates a new zf date.
033    *
034    * @param date the date
035    */
036   public ZfDate(Date date) {
037      this(date.getTime());
038   }
039
040   /**
041    * Instantiates a new zf date.
042    */
043   public ZfDate() {
044      super();
045   }
046
047   /**
048    * Instantiates a new zf date.
049    *
050    * @param date the date
051    */
052   public ZfDate(long date) {
053      super(date);
054   }
055
056   /**
057    * Instantiates a new zf date with the formatted date string
058    *
059    * @param formattedDate the formatted date
060    */
061   public ZfDate(String formattedDate) {
062      setDate(formattedDate);
063   }
064
065   /**
066    * The format code for the String representation of the Date.
067    *
068    * @return the format code
069    */
070   public abstract String getFormatCode();
071
072   /**
073    * Gets the formatter.
074    *
075    * @return the formatter
076    */
077   abstract SimpleDateFormat getFormatter();
078
079   /**
080    * the String representation of the date applying the format given by the code.
081    *
082    * @return the date as formated string
083    */
084   @Override
085   public String toString() {
086      return getFormatter().format(this);
087   }
088
089   /**
090    * Sets the date based on the provided formatted date string.
091    *
092    * @param formattedDate the new date
093    */
094   public void setDate(String formattedDate) {
095      try {
096         Date date = getFormatter().parse(formattedDate);
097         setTime(date.getTime());
098      } catch (ParseException e) {
099         throw new IllegalArgumentException("New date can not be set", e);
100      }
101   }
102}