Convert String To Date Format In Android
I'm trying to convert string to date format.I trying lot of ways to do that.But not successful. my string is 'Jan 17, 2012'. I want to convert this as ' 2011-10-17'. Could someone
Solution 1:
try {
StringstrDate="Jan 17, 2012";
//current date formatSimpleDateFormatdateFormat=newSimpleDateFormat("MMM dd, yyyy");
DateobjDate= dateFormat.parse(strDate);
//Expected date formatSimpleDateFormatdateFormat2=newSimpleDateFormat("yyyy-MM-dd");
StringfinalDate= dateFormat2.format(objDate);
Log.d("Date Format:", "Final Date:"+finalDate)
} catch (Exception e) {
e.printStackTrace();
}
Solution 2:
String format = "yyyy-MM-dd";
SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
Which produces this output when run in the PDT time zone:
yyyy-MM-dd1969-12-31
yyyy-MM-dd1970-01-01
For more info look at here
Solution 3:
I suggest using Joda Time, it's the best and simplest library for date / dateTime manipulations in Java, and it's ThreadSafe (as opposed to the default formatting classes in Java).
You use it this way:
// Define formatters:DateTimeFormatterinputFormat= DateTimeFormat.forPattern("MMM dd, yyyy");
DateTimeFormatteroutputFormat= DateTimeFormat.forPattern("yyyy-MM-dd");
// Do your conversion:StringinputDate="Jan 17, 2012";
DateTimedate= inputFormat.parseDateTime(inputDate);
StringoutputDate= outputFormat.print(date);
// or:StringoutputDate= date.toString(outputFormat);
// or:StringoutputDate= date.toString("yyyy-MM-dd");
// Result: 2012-01-17
It also provides plenty of useful methods for operations on dates (add day, time difference, etc.). And it provides interfaces to most of the classes for easy testability and dependency injection.
Solution 4:
Why do you want to convert string to string try to convert current time in milisecond to formated String, this method will convert your milisconds to a data formate.
publicstaticStringgetTime(long milliseconds)
{
returnDateFormat.format("MMM dd, yyyy", milliseconds).toString();
}
you can also try DATE FORMATE class for better understanding.
Solution 5:
You can't convert date from one format to other. while you are taking the date take you have take the date which ever format the you want. If you want the date in yyyy-mm-dd. You can get this by using following way.
java.util.Calendar calc = java.util.Calendar.getInstance();
int day = calc.get(java.util.Calendar.DATE);
int month = calc.get(java.util.Calendar.MONTH)+1;
int year = calc.get(java.util.Calendar.YEAR);
String currentdate = year +"/"+month +"/"+day ;
Post a Comment for "Convert String To Date Format In Android"