public static final String[] date_format_list = {
"yyyy-MM-dd'T'HH:mm:ss'Z'",
"yyyy-MM-dd'T'HH:mm:ss",
"yyyy-MM-dd",
"yyyy-MM-dd hh:mm:ss",
"yyyy-MM-dd HH:mm:ss",
"EEE MMM d hh:mm:ss z yyyy"
/// add your own format here
};
public static Date parseDate(String d) throws ParseException {
return parseInputWithFormats(d, date_format_list);
}
public static Date parseInputWithFormats(
String dateValue,
String[] formatList
) throws ParseException {
if (dateValue == null || formatList == null || formatList.length == 0) {
throw new IllegalArgumentException("dateValue is null");
}
if (dateValue.length() > 1
&& dateValue.startsWith("'")
&& dateValue.endsWith("'")
) {
dateValue = dateValue.substring(1, dateValue.length() - 1);
}
SimpleDateFormat dateParser = null;
for(int i=0;i < formatList.length;i++){
String format = (String) formatList[i];
if (dateParser == null) {
dateParser = new SimpleDateFormat(format, Locale.US);
} else {
dateParser.applyPattern(format);
}
try {
return dateParser.parse(dateValue);
} catch (ParseException pe) {
//pe.printStackTrace();
}
}
throw new ParseException("Unable to parse the input date " + dateValue, 0);
}
public static void main(String[] args) {
String fromDt="";
String nPattern = "yyyy-MM-dd'T'HH:mm:ss'Z'";
SimpleDateFormat sdf = new SimpleDateFormat(nPattern);
String currentValue="Fri Jul 22 04:22:14 CEST 2011";
try{
fromDt = sdf.format(parseDate(currentValue.toString() ) );
} catch (Exception e) {
System.out.print("\n Case1: date format exception"+e.getMessage()+ " SOLR currentValue:"+currentValue);
fromDt="";
}
System.out.println("Case1. date as str---"+fromDt);
currentValue="2011-07-21 21:22:14";
try{
fromDt = sdf.format(parseDate(currentValue.toString() ) );
} catch (Exception e) {
System.out.print("\n Case2: date format exception"+e.getMessage()+ " SOLR currentValue:"+currentValue);
fromDt="";
}
System.out.println("\n Cse2. date as str---"+fromDt);
}
Daily I help teams with solution engineering aspect of connected vehicle data projects. (massive datasets & always some new datasets with new car models aka new technologies.) Lately in the spare time, applying some of the ML/Deep learning techniques on datasets (many are create based on observations of real datasets)To Share some thoughts on my work (main half of this blog) and the other half will be about my family and friends.
Wednesday, March 28, 2012
Data format conversion in java
Basic need is we used to get xml date data type in different formats for data sources. However our federated search engine we are storing in a neutral format. (For simplicity sake.) After analyzing couple of formats, added this code in year 2005. Nowadays Team is using some apache package utils. But I don’t think they will something different. I am not seeing many options.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment