1

Im having difficulty converting the following date string "2014-07-10T11:31:35" to a java Date object in android.

so Date date = new Date("2014-07-10T11:31:35"); returns null, which causes a null reference exception

public class DateUtil {

    public static String FromIsoString(String datestring)
    {
        String formattedDateString = "";
        try {
            if (!datestring.isEmpty()) {

                Date date = new Date(date string);//-->>>> returns null 
                String format = "dd/MM/yyyy";
                Locale locale = Locale.ENGLISH;
                formattedDateString = FromIsoString(date, format, locale);
            }
        }
        catch(Exception ex)
        {
            Log.e(ex.getLocalizedMessage(),"FromUtcString");
        }
        return formattedDateString;
    }


    public static  String FromIsoString(Date date, String format, Locale locale){
        String dateString = null;
        try
        {

            dateString = new SimpleDateFormat(format, locale).format(date);

        }catch (Exception ex)
        {
            Log.e(ex.getLocalizedMessage(),"FromString");
        }
        return dateString;
    }
}
6
  • 1
    Please give the specific error you are receiving. See this guide on How to Ask a Good Question. Commented Jul 14, 2014 at 11:28
  • 1
    It would help if you'd post the right code. This code uses a dd/MM/yyyy format, and doesn't even compile. Also, don't use the String constructor for dates, it's deprecated. Commented Jul 14, 2014 at 11:29
  • its right there in the code, it returns null, which causes a null reference exception. Commented Jul 14, 2014 at 11:29
  • Xerxes, That is really obscure. Put it in the text surrounding as well. Commented Jul 14, 2014 at 11:30
  • 1
    Then how do you expect 2014-07-10T11:31:35 to match dd/MM/yyyy? Commented Jul 14, 2014 at 11:30

1 Answer 1

7
/**
 * Format date with specified Date format
 * @param dateString
 * @param inFormat format of input date
 * @param outFormat format of result date
 * @return dateString
 */
public static String formatDate(String dateString, String inFormat, String outFormat){
    DateFormat inFormatter = new SimpleDateFormat(inFormat);
    inFormatter.setLenient(false);
    DateFormat outFormatter = new SimpleDateFormat(outFormat);

    Date date = null;
    try {
        date = inFormatter.parse(dateString);
    } catch (ParseException e) {
        e.printStackTrace();
        return "";
    }

    return outFormatter.format(date);
}

and call it like formatDate("2014-07-10T11:31:35"", inFormat, outFormat)

where inFormat = "yyyy-MM-dd'T'HH:mm:ss" and outFormat = "dd/MM/yyyy"

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.