Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String timestamp to Calendar in Java?

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?

like image 227
Joakim Engstrom Avatar asked May 22 '13 07:05

Joakim Engstrom


People also ask

How do I convert a string to a calendar instance?

You can use following code to convert string date to calender format. String stringDate="23-Aug-10"; SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy"); Date date = formatter. parse(stringDate); Calendar calender = Calendar. getInstance(); calender.

How do I get timestamp from date and time?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.


2 Answers

You can use setTimeMillis :

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(timestampLong);
like image 156
Gomoku7 Avatar answered Oct 08 '22 11:10

Gomoku7


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);
like image 31
Alexis C. Avatar answered Oct 08 '22 09:10

Alexis C.