Java examples for java.util:Date Parse
Parse input date string as XMLGregorianCalendar .
//package com.java2s; import javax.xml.datatype.DatatypeConfigurationException; import javax.xml.datatype.DatatypeConstants; import javax.xml.datatype.DatatypeFactory; import javax.xml.datatype.XMLGregorianCalendar; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class Main { public static void main(String[] argv) throws Exception { String dateStr = "java2s.com"; String format = "java2s.com"; System.out.println(parseAsXmlDateWithoutTimezone(dateStr, format)); }/*from w w w . ja v a 2 s. c o m*/ /** * Parse input date string as {@link XMLGregorianCalendar}. We want, that * method {@link XMLGregorianCalendar#toXMLFormat} produce date format * 'yyyy-MM-dd'. * * @param dateStr * string representing date * @param format * format of the input string * @return representation of the date (no time set) * @throws ParseException * if not possible to parse the input string wwith the given * format * @see #convert2XmlDateWithoutTimezone */ public static XMLGregorianCalendar parseAsXmlDateWithoutTimezone( String dateStr, String format) throws ParseException { if (dateStr == null || dateStr.length() < 1) { throw new IllegalArgumentException( "Argument 'String dateStr' is null or empty string!"); } if (format == null || format.length() < 1) { throw new IllegalArgumentException( "Argument 'String format' is null or empty string!"); } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format); simpleDateFormat.setLenient(false); Date date = simpleDateFormat.parse(dateStr); return convert2XmlDateWithoutTimezone(date); } /** * Convert Date into XMLGregorianCalendar. We want, that method * {@link XMLGregorianCalendar#toXMLFormat} produce date format * 'yyyy-MM-dd'. To accomplish this, it is necessery to set TimeZone value * of the {@link XMLGregorianCalendar} to * {@link DatatypeConstants#FIELD_UNDEFINED} If TimeZone would be set to 0, * output would be yyyy-MM-ddZ, which is also correct but more applications * outside will be able process the first format. * * @param date * the date * @return representation of the date (no time set) */ public static XMLGregorianCalendar convert2XmlDateWithoutTimezone( Date date) { if (date == null) { throw new IllegalArgumentException( "Argument 'Date date' is null!"); } GregorianCalendar utilGregorianCalendar = new GregorianCalendar(); utilGregorianCalendar.setTimeInMillis(date.getTime()); try { return DatatypeFactory.newInstance() .newXMLGregorianCalendarDate( utilGregorianCalendar.get(Calendar.YEAR), utilGregorianCalendar.get(Calendar.MONTH) + 1, utilGregorianCalendar .get(Calendar.DAY_OF_MONTH), DatatypeConstants.FIELD_UNDEFINED); } catch (DatatypeConfigurationException e) { throw new RuntimeException(e); } } }