0

To get year and month from given timestamp I used this code. But giving a wrong answer for that.

    long timestamp = Long.parseLong("1459239223");
    Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(timestamp);
    System.out.println(cal.get(Calendar.YEAR)); 

But when using this it will give the connect answer as it should be. Any idea why this is happening.

Note: Java 7 OpenJDK is being used and a similar question is asked about Getting “unixtime” in Java.

Community
  • 1
  • 1
GPrathap
  • 7,336
  • 7
  • 65
  • 83

2 Answers2

4

The site you have referred for online conversion is correct. You have set to time in seconds for the calendar instance i.e multiply by 1000 to convert time in milli seconds to seconds.

long timestamp = Long.parseLong("1459239223000");
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(timestamp);
System.out.println(cal.get(Calendar.YEAR)); 

Therefore to answer your question: Unix time is defined as the number of seconds elapsed since UTC Jan 1, 1970 midnight.

riteshtch
  • 8,629
  • 4
  • 25
  • 38
0

You can do like that way also -

SimpleDateFormat sdf = new SimpleDateFormat("yyyy");    
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));    
System.out.println(calendar.getWeekYear());
Sudip
  • 92
  • 7