Skip to content Skip to sidebar Skip to footer

Date Formatting In Android

I have a problem that I want to parse a String to Date in 'November 15, 2013' format but I unable to do that using MMMM D, YYYY in SimpleDateFormat Class. Please suggest any soluti

Solution 1:

Take a look at the example from Android at SimpleDateFormat.

String[] formats = newString[] {
   "yyyy-MM-dd",
   "yyyy-MM-dd HH:mm",
   "yyyy-MM-dd HH:mmZ",
   "yyyy-MM-dd HH:mm:ss.SSSZ",
   "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
 };
 for (String format : formats) {
   SimpleDateFormat sdf = newSimpleDateFormat(format, Locale.US);
   System.out.format("%30s %s\n", format, sdf.format(newDate(0)));
   sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
   System.out.format("%30s %s\n", format, sdf.format(newDate(0)));
 }

Output:

yyyy-MM-dd1969-12-31yyyy-MM-dd1970-01-01yyyy-MM-ddHH:mm1969-12-31 16:00yyyy-MM-ddHH:mm1970-01-01 00:00yyyy-MM-ddHH:mmZ1969-12-31 16:00-0800yyyy-MM-ddHH:mmZ1970-01-01 00:00+0000yyyy-MM-ddHH:mm:ss.SSSZ1969-12-31 16:00:00.000-0800yyyy-MM-ddHH:mm:ss.SSSZ1970-01-01 00:00:00.000+0000yyyy-MM-dd'T'HH:mm:ss.SSSZ1969-12-31T16:00:00.000-0800yyyy-MM-dd'T'HH:mm:ss.SSSZ1970-01-01T00:00:00.000+0000

Solution 2:

you could do something like this

SimpleDateFormat orignalFormat= newSimpleDateFormat("MMMMMMMMM dd, yyyy"); //November 15, 2013Datedate=null;
            try {
                    date = origFormat.parse(apkgalaxy.getPosted_on());              
            } catch (ParseException e) {
                e.printStackTrace();
            }

and set the day in desired format by below code

SimpleDateFormat newFormat_date= newSimpleDateFormat("yyyy-MM-dd"); //any format you wantif (date!=null) {
                    StringdesiredDateFormat= newFormat_date.format(date);
                    holder.posted_on_date.setText(desiredDateFormat);
                }else{
                    holder.posted_on_date.setText("N/A");
                }

Solution 3:

I don't think you should be using a mutable object such as Date as a key to a HashMap. Consider converting the date to a String. This is how I would format a date.

DateFormat formatter1 = new SimpleDateFormat("MMMMM DD, yyyy");
System.out.println(formatter1.parse("15/02/2013"));

Solution 4:

Since SimpleDateFormat is Depreciated

I would suggest you to use this way

android.text.format.DateFormat dateFormat= new android.text.format.DateFormat();
dateFormat.format("MMMM DD, yyyy", new java.util.Date());

Post a Comment for "Date Formatting In Android"