String timestamp to Calendar in Java?
25,635
Solution 1
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);
Solution 2
You can use setTimeMillis :
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestampLong);
Author by
Joakim Engstrom
Gadget geek, Android and iOS developer, mobile enthusiast and an unhealthy love for film!
Updated on July 09, 2022Comments
-
Joakim Engstrom almost 2 years
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?
-
Joakim Engstrom almost 11 yearsI ended up skipping the Date conversion, but otherwise it's the same code I ended up using. Especially with with the (month +1) which threw me of at the beginning.