JavaStudent JavaStudent - 5 months ago 40
Java Question

String date to xmlgregoriancalendar conversion

I have written this function :

public static XMLGregorianCalendar getXMLGregorianCalendar(String date) throws OmniException{
XMLGregorianCalendar xmlCalender=null;
GregorianCalendar calender = new GregorianCalendar();
calender.setTime(Util.stringToJavaDate(date));
xmlCalender = DatatypeFactory.newInstance().newXMLGregorianCalendar(calender);
return xmlCalender;
}

public static Date stringToJavaDate(String sDate) throws OmniException{
Date date=null;
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ENGLISH).parse(sDate);
return date;
}


When i am passing date as
"2014-01-07"
am getting output date as
2014-01-06T18:30:00:000Z

where i am going wrong ?
also what to do if I want to get only
2014-01-06T18:30:00
and
2014-01-06T18:30:00Z


Any help is appreciated

Answer

Found the solution as below.... posting it as it could help somebody else too :)

Date dob=null;
DateFormat df=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
dob=df.parse( "2014-02-10 11:15:00" );
GregorianCalendar cal = new GregorianCalendar();

cal.setTime(dob);
XMLGregorianCalendar xmlDate2 = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH), dob.getHours(),dob.getMinutes(),dob.getSeconds(),DatatypeConstants.FIELD_UNDEFINED, cal.getTimeZone().LONG).normalize();
XMLGregorianCalendar xmlDate3 = DatatypeFactory.newInstance().newXMLGregorianCalendar(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH)+1, cal.get(Calendar.DAY_OF_MONTH),dob.getHours(),dob.getMinutes(),dob.getSeconds(),DatatypeConstants.FIELD_UNDEFINED, DatatypeConstants.FIELD_UNDEFINED);
System.out.println(xmlDate2);
System.out.println(xmlDate3);

Output:> 2014-02-10T11:14:00Z

2014-02-10T11:15:00