Monday, 3 February 2014

Routine example in Talend ETL - Convert strings to dates

Hello every one..

In this example you will input different formats of strings and convert them to standard date format...
What ever the format you provide in the form of strings the below code converts into a single date format...
For example if your date is dd-MM-yyyy or dd/MM-yyyy which are strings in your meta data such as .csv or .xls or .xlsx ... by using this code the format of the string is changed to Date with a single formatted output. 

 Coding credit goes to Vaibhav ji(Data warehouse architect - one of my colleagues)...

 From the Repository, right click on Code -> Create routine and give the name of it..
Write below code in your routine. Routine name and class name should be equal.

package routines;

import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;


public class DateLogics{
    private static Date get_date = null;

    /**
     * @param get_date the get_date to set
     */
    public static void setGet_date(String get_dates) {
        if ((StringHandling.INDEX(get_dates,"-")==2))
        {
            try {
                get_date =(Date) new SimpleDateFormat("dd-MM-yyyy").parse(get_dates);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if ((StringHandling.INDEX(get_dates,".")==2))
        {
            try {
                get_date =(Date) new SimpleDateFormat("dd.MM.yyyy").parse(get_dates);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if ((StringHandling.INDEX(get_dates,"/")==2))
        {
            try {
                get_date =(Date) new SimpleDateFormat("dd/MM/yyyy").parse(get_dates);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
      
    }

    /**
     * @return the get_date
     */
    public static Date getGet_date() {
        return get_date;
    }
   
}

Now, create a job and drag and drop a tJava component and write below code..
String date_input = "10.10.2014";
System.out.println(StringHandling.LEN(date_input));
DateLogics.setGet_date(date_input);
System.out.println(DateLogics.getGet_date());


NOTE:
You need to provide as many if conditions for the different kinds of date formats as strings so that you can generalize the code ..

version tested: TOS : 5.1.3

Thank you.