Removing Timezone from XMLGregorianCalendar

1 year ago codedestine 0

If you had worked on a project which consume or publish web services, then you would have faced a problem with date (XMLGregorianCalendar) object, where you would like to send only date string as yyyy-MM-dd but complete yyyy-MM-dd’T’HH:mm:ss’Z’ has been sent. This date string contains date, time and timezone information, if you like to send only date string as yyyy-MM-dd then you have to remove time and timezone information from date object. Let’s see how to remove these information  :- 

To remove time zone or “Z” from date string, call following method :-


xmlDate.setTimezone( DatatypeConstants.FIELD_UNDEFINED )

To remove time information from date string, call following method :-


xmlDate.setTimezone( DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED, 
                     DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED )

Example :- 


import java.util.Date;
import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;

public class Main {

 public static void main(String[] args) {
 
   XMLGregorianCalendar xmlDate = null;
   GregorianCalendar gc = new GregorianCalendar();
   gc.setTime(new Date()); 
   try {
       xmlDate = DatatypeFactory.newInstance().newXMLGregorianCalendar(gc);
       System.out.println("Complete Date :- " + xmlDate.toString());
 
       // To remove Timezone or "Z"
       xmlDate.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
       System.out.println("Without Time Zone :- " + xmlDate.toString());
 
       // To remove Time information
       xmlDate.setTime(DatatypeConstants.FIELD_UNDEFINED,
       DatatypeConstants.FIELD_UNDEFINED,
       DatatypeConstants.FIELD_UNDEFINED,
       DatatypeConstants.FIELD_UNDEFINED);
       System.out.println("Without Time Zone & Time :- " + xmlDate.toString());
 
   } catch (Exception e) {
       e.printStackTrace();
   } 
 }

}

Result :-

Removing Timezone from XMLGregorianCalendar

You can also check :- 

Convert XMLGregorianCalendar to Date Object

Convert Date to XMLGregorianCalendar Object

That’s all for this post, If you liked it, please share your thoughts in comments section and share it with others too.