Set xsd style dates with zulu time zone in java

I need to set some XML Schema Date/Time Datatypes (also called ) values for Created (being now) and Expired (one month from now) so that the result might look something like a dateTime in UTC (also known as GMT, but also being a 24 hour clock format) time by adding a “Z” (for Zulu?) behind the time

1
<startdate>2002-05-30T09:30:10Z</startdate>

with much chin pulling and Google cursing (suffering so you don’t have to) I came up with this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import java.util.*;
import java.text.SimpleDateFormat;
public class xsdDate {
 private static final SimpleDateFormat SDF =    
     new SimpleDateFormat( "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" );

 public String getCreatedxsdDate () {
  GregorianCalendar cal = new GregorianCalendar();
  final TimeZone utc = TimeZone.getTimeZone( "UTC" );
  SDF.setTimeZone( utc );
  final String milliformat = SDF.format( new Date() );
  final String zulu = milliformat.substring( 0, 22 ) + 'Z';
 return zulu ;
 }

 public String getExpiresxsdDate () {
  GregorianCalendar cal = new GregorianCalendar();
  cal.setTime(new Date());
  cal.add(Calendar.MONTH, 1); // adjust date by one month
  final TimeZone utc = TimeZone.getTimeZone( "UTC" );
  SDF.setTimeZone( utc );
  final String milliformat = SDF.format( cal.getTime() );
  final String zulu = milliformat.substring( 0, 22 ) + 'Z';
  return zulu ;
 }
}

as an example of how to use it :

1
2
3
xsdDate d = new xsdDate();    
System.out.println("CreatedxsdDate Date: " + d.getCreatedxsdDate ());
System.out.println("ExpiresxsdDate Date: " + d.getExpiresxsdDate ());

joy!

Leave a Reply