String timestamp to Calendar in Java?

A simple question that I can not find the answer to. I have a String, which is a timestamp, I want to turn it into a calendar object in order to then display it in my Android app.

The code that I'm showing so far, everything does everything in 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: Only FYI, timestamp from server: 1369148661, Could this be wrong?

+7
source share
2 answers

If you get the time in seconds, you should 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); 

Exit:

2013-4-21

Leaving, because the constant for Calendar.MONTH starts with 0. Therefore, you should display it like this for the user:

 System.out.println(year +"-"+(month+1)+"-"+date); 
+15
source

You can use setTimeMillis:

 Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(timestampLong); 
+18
source

All Articles