Dear all,
I have textbox (txtTransDate) that I set text to '2008-04-17' because mySQL accepts that format date.
I want to change the format to "MM/dd/yyyy" 04-17-2008 to retrieve month and year.

But the error is like this :
java.text.ParseException: Unparseable date: "2008-04-17"

int tahun =0, bln=0 ;
String sBln="";
SimpleDateFormat dtChange = new SimpleDateFormat("MM/dd/yyyy");
try
{
Date date = dtChange.parse(txtTransDate.getText().trim());
tahun = date.getYear() + 1900;
bln = date.getMonth() + 1;
sBln = Integer.toString(bln);
if(sBln.length()==1)
{
sBln = "0" + sBln;
}
}
catch(Exception e)
{
System.out.println(e.toString());
}

Hi,

First of all, if you are referring to java.sql.Date or java.util.Date, then the methods getYear() and getMonth() are deprecated. Use Calendar.get(Calendar.DAY_OF_MONTH) and Calendar.get(Calendar.MONTH) instead.

SimpleDateFormat dtChange = new SimpleDateFormat("MM/dd/yyyy");	
java.util.Date date = new SimpleDateFormat("yyyy-mm-dd").parse(txtTransDate);	
String dt = dtChange.format(date);

Now, date holds the original date, dt has the date string formatted as you wanted. Play!

commented: Thanks for your help +1
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.