Pergunta

I'm trying to avoid reinstalling Eclipse to solve this, so I hope someone can help with this date-parsing problem. Here's what I do.

DateFormat dateFormat; 

That's a variable in my class. I set it to the following.

dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
// Example input: 2010-11-07 16:00:00

When another method is called, I create a new java.sql.Date instance using strings that are passed in. For the sake of clarity, here's a shortened version.

public void aMethod (String activateTime, String expireTime) {
    Date example = new Date(dateFormat.parse(activateTime).getTime());
    Date example2 = new Date(dateFormat.parse(expireTime).getTime());
}

When I look at the strings resulting from these operations (just adding .toString() to instantiations above), I get output like the following

2010-10-30
2010-11-29

... instead of the input strings, which are reported to be...

2010-10-30 17:00:00
2010-11-29 16:00:00

Anyone know why it doesn't give me a date in the pattern I specified?

Foi útil?

Solução

The javadocs for java.sql.Date specify that the toString method returns a string in the format "yyyy-mm-dd", so you are seeeing the correct behaviour. The Date object has no knowledge of the formatter you used to create it. To get output in the same format use the DateFormat.format method rather than toString:

public void aMethod (String activateTime, String expireTime) {
    Date example = new Date(dateFormat.parse(activateTime).getTime());
    Date example2 = new Date(dateFormat.parse(expireTime).getTime());
    System.out.println(example.toString() + " vs " + dateFormat.format(example));
    System.out.println(example2.toString() + " vs " + dateFormat.format(example2));
}

Outras dicas

The java.sql.Date contains only the date part of datetime. You probably want to use java.sql.Timestamp instead.

Timestamp example = new Timestamp(dateFormat.parse(activateTime).getTime());
Timestamp example2 = new Timestamp(dateFormat.parse(expireTime).getTime());

It also works like that in the average SQL database. The DATE data type represents only the date, the TIME data type represents only the time. The TIMESTAMP data type (sometimes called DATETIME) represents the date and time.

Note that your hour pattern is incorrect. With the given examples, you'd rather like to use HH instead of hh. See also the SimpleDateFormat javadoc.

See also:

Did you try to change java.sql.Date to java.util.Date?

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