Convert string to date Android

只谈情不闲聊 提交于 2019-12-12 02:34:35

问题


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.


回答1:


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);



回答2:


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



回答3:


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);


来源:https://stackoverflow.com/questions/21244760/convert-string-to-date-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!