Reputation: 39
I am using SimpleDateFormat to convert the date from dd-MM-yyyy to yyyy-MM-dd but I does not display the year properly.I am trying to convert 18-5-2014 to 2014-05-18 but I am getting 3914-05-18.
public void onDateSet(DatePicker view, int year,int monthOfYear, int dayOfMonth)
{
Date selectedDate = new Date(year,monthOfYear, dayOfMonth);
String strDate = null;
SimpleDateFormat dateFormatter = new SimpleDateFormat("yyyy-MM-dd");
strDate = dateFormatter.format(selectedDate);
txtdeliverydate.setText(strDate);
}
Upvotes: 0
Views: 799
Reputation: 1503859
I suspect you didn't read the documentation for the (deprecated) Date
constructor you're using:
Parameters:
year - the year minus 1900.
month - the month between 0-11.
date - the day of the month between 1-31.
Avoid using Date
here. Either use a good date/time library like Joda Time, or use Calendar
to set year/month/day values - even then, the month will be 0-based.
Also, your method is currently accepting year/month/day values... if you're actually just trying to do a conversion, you should be accepting a string and returning a string, e.g.
public static String convertDateFormat(String text) {
TimeZone utc = TimeZone.getTimeZone("Etc/UTC");
SimpleDateFormat parser = new SimpleDateFormat("dd-MM-yyyy", Locale.US);
parser.setTimeZone(utc);
Date date = parser.parse(text);
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);
formatter.setTimeZone(utc);
return formatter.format(date);
}
Upvotes: 2