001 /* 002 * Copyright 2008-2009 the original author or authors. 003 * The contents of this file are subject to the Mozilla Public License 004 * Version 1.1 (the "License"); you may not use this file except in 005 * compliance with the License. You may obtain a copy of the License at 006 * http://www.mozilla.org/MPL/ 007 * 008 * Software distributed under the License is distributed on an "AS IS" 009 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 010 * License for the specific language governing rights and limitations 011 * under the License. 012 */ 013 014 package com.mtgi.xml; 015 016 import java.text.FieldPosition; 017 import java.text.SimpleDateFormat; 018 import java.util.Calendar; 019 import java.util.Date; 020 021 /** SimpleDateFormat doesn't give us a time zone option that meets W3C standards, so we provide our own */ 022 public class XmlDateFormat extends SimpleDateFormat { 023 024 private static final long serialVersionUID = -5310271700921914349L; 025 026 public XmlDateFormat() { 027 this("yyyy-MM-dd'T'HH:mm:ss.SSS"); 028 } 029 030 public XmlDateFormat(String format) { 031 super(format); 032 } 033 034 @Override 035 public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition pos) { 036 StringBuffer ret = super.format(date, toAppendTo, pos); 037 038 //append timezone as (+|-)hh:mm to meet xsd standard. 039 int value = (calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET)) / 60000; 040 041 //append sign indicator and convert to absolute value. 042 if (value < 0) { 043 ret.append('-'); 044 value *= -1; 045 } else { 046 ret.append('+'); 047 } 048 049 appendTwoDigit(toAppendTo, value / 60); 050 toAppendTo.append(':'); 051 appendTwoDigit(toAppendTo, value % 60); 052 053 return ret; 054 } 055 056 private static final void appendTwoDigit(StringBuffer buf, int value) { 057 buf.append(value / 10).append(value % 10); 058 } 059 }