Friday, December 05, 2014

How to parse any valid date format in Talend?

How to parse any valid date format in Talend? This is a question that comes up every so often and the simple answer is that there is not plain simple way that will work for everybody. Valid dates format depend on locale and if you are in the middle of a project supporting multiple countries and languages YMMV.

You will need to use Talend routines. For example you can create a stringToDate() custom method. In its simpler form (considering you are tackling just one locale) you will pass just a String a parameter (not the locale). You will need to add the formats you will allow like you see in the function below. The class and the main method are just for testing purposes and you can see it in action here. These days is so much easier to share snippets of code that actually run ;-)
/**
*
* See it in action in http://runnable.com/VIHI8AhI-_MpHcsM/multipledatesparser-java
*
* */
class MultipleDatesParser {
public static String stringToDate (String dateToParse) throws java.lang.Exception {
String parsedDate = null;
java.text.SimpleDateFormat sdf = null;
try {
sdf = new java.text.SimpleDateFormat("MM/DD/yy");
parsedDate = sdf.parse(dateToParse).toString();
} catch (Exception e1) {
try {
sdf = new java.text.SimpleDateFormat("MM/DD/yyyy");
parsedDate = sdf.parse(dateToParse).toString();
} catch (Exception e2) {
//Other data formats here following the pattern above or ...
throw e2;
}
}
return parsedDate;
}
public static void main (String[] args) throws java.lang.Exception {
System.out.println(stringToDate("12/20/2014"));
System.out.println(stringToDate("12/20/14"));
}
}

No comments:

Followers