Pergunta

I have the following String.

21-Mar-2014

How can i convert this into a valid Joda DateTime object?

I've tried the following with no joy:

DateTimeFormatter formatter = DateTimeFormat.forPattern("d-MMM/Y");
            DateTime dt = formatter.parseDateTime(date);

Thanks in advance

Matt

Foi útil?

Solução 2

A genuine joda answer with corrected pattern string and explicit Locale:

String input = "21-Mar-2014";
DateTimeFormatter dtf = DateTimeFormat.forPattern("dd-MMM-yyyy").withLocale(Locale.ENGLISH);
DateTime dt = dtf.parseDateTime(input); // using the default time zone
System.out.println(dt); // 2014-03-21T00:00:00.000+01:00 (my zone: Europe/Berlin)

If you don't need time part (regarding your input!) then I recommend to use:

LocalDate date = dtf.parseLocalDate(input);

Outras dicas

There are already so many question in SO related to this. Check this.

    String dateInString = "7-Jun-2013";
try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

} catch (ParseException e) {
    e.printStackTrace();
}

you can try this

Date date1;
String myFormatString = "MMM-dd-yyyy"; // for example
String Your_Date=txtDate.getText().toString();
SimpleDateFormat df = new SimpleDateFormat(myFormatString);
date1 = df.parse(Your_Date);

you just use the following simple date format

SimpleDateFormat sdf=new SimpleDateFormat("d-MMM-yyyy");
Date date1=sdf.parse("21-Mar-2014");

Try this

    DateTimeFormatter formatter = DateTimeFormat.forPattern("d-MMM-yyyy");
                DateTime dt = formatter.parseDateTime(date);
System.out.println(dt.toString());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top