/*
 *  StringToDate.java
 *
 *  Copyright 1997 Massachusetts Institute of Technology.
 *  All Rights Reserved.
 *
 *  Author: Ora Lassila
 *
 *  $Id: StringToDate.java,v 1.1 1997/05/30 13:24:00 bmahe Exp $
 */

package w3c.www.pics;

import java.util.Date;

public class StringToDate implements Mapper {

  public Object map(Object value) throws PICSParserException
  {
    try {
      return transformISODateToDate((String)value);
    }
    catch (NumberFormatException e) {
      throw new PICSParserException("Unable to parse ISO date", e);
    }
  }

  public static Date transformISODateToDate(String isoDate)
    throws NumberFormatException
  {
    if (isoDate.length() != 21 ||
	      isoDate.charAt(4) != '.' ||
	      isoDate.charAt(7) != '.' ||
	      isoDate.charAt(10) != 'T' ||
	      isoDate.charAt(13) != ':')
      throw new NumberFormatException();
    int year       = Integer.parseInt(isoDate.substring(0, 4));
    int month      = Integer.parseInt(isoDate.substring(5, 7));
    int day        = Integer.parseInt(isoDate.substring(8, 10));
    int hour       = Integer.parseInt(isoDate.substring(11, 13));
    int minute     = Integer.parseInt(isoDate.substring(14, 16));
    char zoneSign  = isoDate.charAt(16);
    int zoneHour   = Integer.parseInt(isoDate.substring(17, 19));
    int zoneMinute = Integer.parseInt(isoDate.substring(19));
    if (month < 1 || month > 12 || day < 1 || day > 31 ||
	      hour < 0 || hour > 23 || minute < 0 || minute > 60 || // leap-second!!
	      (zoneSign != '+' && zoneSign != '-') ||
	      zoneHour < 0 || zoneHour > 23 || zoneMinute < 0 || zoneMinute > 59)
      throw new NumberFormatException();
    long utc = Date.UTC(year-1900, month-1, day, hour, minute, 0);
    int offset = 60 * (60 * zoneHour + zoneMinute);
    if (zoneSign == '-')
      utc -= offset;
    else
      utc += offset;
    return new Date(utc);
  }

}
