Pergunta

    String DATE_FORMAT = "`";
    Object value = null;
    String date = "2014-02-02";

    try {
        value = new SimpleDateFormat(DATE_FORMAT).parse(date);
        System.out.println(value);
    } catch (ParseException e) {
        System.out.println(e.getMessage());
    }

as i saw in the java docs, this DATE_FORMAT will avoid interpretation, maybe i didn't understand it correctly.

so what am i doing wrong ?

Foi útil?

Solução

I guess you refer to this:

Date and time formats are specified by date and time pattern strings. Within date and time pattern strings, unquoted letters from 'A' to 'Z' and from 'a' to 'z' are interpreted as pattern letters representing the components of a date or time string. Text can be quoted using single quotes (') to avoid interpretation. "''" represents a single quote. All other characters are not interpreted; they're simply copied into the output string during formatting or matched against the input string during parsing.

This means you can avoid interpretation of the text of the pattern adding a single quote to the parts you want to avoid.

For example if I get my String dates with a text I want not to be interpreted as part of the date I can do something like this:

SimpleDateFormat df = new SimpleDateFormat("'mydate' yyyy-MM-dd HH:mm:ss");
try {
    df.parse("mydate 2014-04-01 12:30:00");
} catch (ParseException e) {
    e.printStackTrace();
}

This will not give any exception. On the other hand, this will:

  SimpleDateFormat df = new SimpleDateFormat("'mydate' yyyy-MM-dd HH:mm:ss");
    try {
        df.parse("mydates 2014-04-01 12:30:00"); //check the additional s
    } catch (ParseException e) {
        e.printStackTrace();
    }

In short I think you missinterpreted the specs.

More info: How to escape single quote in java's SimpleDateFormat

Outras dicas

Try,

String DATE_FORMAT = "yyyy-MM-dd";
Date value  = null;
String date = "2014-02-02";

try {
    value = new SimpleDateFormat(DATE_FORMAT).parse(date);
    System.out.println(value);
} catch (ParseException e) {
    System.out.println(e.getMessage());
}

And Read

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top