Rachael M
Rachael M

Reputation: 92

android getDate from milliseconds stored in String field

I have a date stored in a String field in SQLITE with the String value

"/Date(1411472160000+0100)/"

how can I convert this back into a date format , the code below doesn't work. I think I need to convert from the milliseconds first but I cant see how to even get the above text into a long format first ?

any suggestions ?

Date convertedDate = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm",         
java.util.Locale.getDefault());
convertedDate = dateFormat.parse(dateString);       
return dateFormat.format(convertedDate);

Upvotes: 0

Views: 543

Answers (2)

AxelH
AxelH

Reputation: 14572

Well, a substring from the indexOf("(") to the indexOf("+") and you should find the date in milli.

From there, I believe you can find the date ;)

   String s = "/Date(1411472160000+0100)/";
   s = s.substring(s.indexOf("(") + 1, s.indexOf("+"));
   Date d = new Date(Long.parseLong(s));

With the same structure, you can find the timezone (+0100) (from "+" to ")") and work with a Calendar to find the right time for the right time area.

Upvotes: 3

Amit K. Saha
Amit K. Saha

Reputation: 5951

First you have to parse out the time value from String i.e. "1411472160000+0100" part.

Here in "1411472160000+0100" , "+0100" is the timezone info. If you don't want to consider the timezone, then you can take following approach.

Approach-1

long timestamp = 1245613885;
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getDefault());
calendar.setTimeInMillis(timestamp * 1000);

int year = calendar.get(Calendar.YEAR);
int day = calendar.get(Calendar.DATE);
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);

then to get the date in your specified format you can use-

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateString = sdf.format(calendar.getTime());
System.out.println(dateString); // 2009-06-21 15:51:25

Besides this approach, there is an excellent Java Date library called JodaTime. If you want to incorporate the timezone info , you can refer to this constructor from JodaTime.

http://www.joda.org/joda-time/apidocs/org/joda/time/DateTime.html#DateTime-long-org.joda.time.DateTimeZone-

Upvotes: 3

Related Questions