0
votes

I'm trying to convert a String that represents a date stored in SQLITE.

The date was stored into sqlite as follows:

Date date;

date.toString();

According with Java documentation, toString() method:

Returns a string representation of this Date. The formatting is equivalent to using a SimpleDateFormat with the format string "EEE MMM dd HH:mm:ss zzz yyyy", which looks something like "Tue Jun 22 13:07:00 PDT 1999". The current default time zone and locale are used. If you need control over the time zone or locale, use SimpleDateFormat instead.

Until here, it's fine but, when I try to get the String and convert it to date again, Java throws an exception.

The String comes from sqlite:

Mon Jan 20 18:26:25 BRT 2014

So, I do:

SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy", Locale.US);

Date date= sdf.parse("Mon Jan 20 18:26:25 BRT 2014");

What I'm doing wrong?

Thanks.

3
You haven't told us what you expect and what you actually get.Sotirios Delimanolis
And what is the exception?Alexis C.
Sorry! I need to get the date in this format: "dd/MM/yyyy".vitorvigano
@vitorvigano By the way, that is the absolute wrong way to store date-time data in your database. Never use "toString" on java.util.Date except for quick-and-dirty purposes; it uses default time zone when you should be using UTC/GMT, and it uses 3-letter time zone codes which are neither standardized nor unique. Read the SQLite doc on data types. Use the SQLite date-time functions to store and retrieve in ISO 8601 format adjusting to UTC/GMT (no time zone offset).Basil Bourque

3 Answers

1
votes

try this code

String dateString = "here your date";
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date convertedDate = new Date();
try {
    convertedDate = dateFormat.parse(dateString);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
System.out.println(convertedDate);
1
votes

Try this:

String w = "Mon Jan 20 18:26:25 BRT 2014";
SimpleDateFormat pre = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy");
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
try{
    Date date = pre.parse(w);
    System.out.println(sdf.format(date));
}catch(Exception e){
    e.printStackTrace();
}

Output:

20/01/2014
0
votes

Formatter for storing and restoring data value in format dd/MM/yyyy

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy");

Storing data

String dataAsString = simpleDateFormat.format(date); // 20/01/2014

Restoring data

Date data = simpleDateFormat.parse(dataAsString);