Reputation: 6393
A simple question which I can't find an answer to. I have a String which is a timestamp, I want to make it into a calendar object so I then can display it in my Android application.
The code I have so far displays everything makes everything in the 1970:s.
String timestamp = parameter.fieldParameterStringValue;
timestampLong = Long.parseLong(timestamp);
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
dateTextView.setText(year + "-" + month + 1 + "-" + date);
UPDATE: Just FYI, the timestamp is from the server is: 1369148661, Could that be wrong?
Upvotes: 9
Views: 32557
Reputation: 93892
If you get the time in seconds, you have to multiply it by 1000 :
String time = "1369148661";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);
System.out.println(year +"-"+month+"-"+date);
Output :
2013-4-21
Care because the constant for the Calendar.MONTH
is starting from 0. So you should display it like this for the user :
System.out.println(year +"-"+(month+1)+"-"+date);
Upvotes: 22
Reputation: 1372
You can use setTimeMillis :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestampLong);
Upvotes: 28