Tuesday 1 October 2013

Program to Format Date

// input - 20 jul 2013 (or) 20,jul,2013 (or) 20 ,jul ,2013 (or) 20, jul, 2013

// output - 2013-07-20

import java.util.*;
class DateFormatConversion
{
public static void main(String[] args) {
if(args.length != 1)
{
System.out.println("Enter only one argument ");
return;
}
System.out.println(getDate(args[0]));
}

static String getDate(String s)
{
s = s.replace(","," ");
String[] temp = splitString(s);
String result="";
temp[1] = getMonthNumber(temp[1]);
for(int i = temp.length - 1 ; i >= 0 ; i--)
{
if(i==0)
result += temp[i];
else
result += temp[i] + "-";
}
return result;
}

static String[] splitString(String s)
{
return s.split("[ ]+");
}

static String getMonthNumber(String s)
{
String months = "JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC";
int num = (months.indexOf(s.toUpperCase())/3)+1;
if(num < 10)
return "0" + num;
return "" + num;
}
}

No comments:

Post a Comment