Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleDateFormat always returns 1970.01.17 with wrong timezone

I have been using Processing 3.0, and I am trying to print a simple timestamp when my Arduino outputs certain values, but it is not working. I tried to use SimpleDateFormat, but it always returns 1970.01.17 17:48:35 GMT, rather than the actual time. Below is the MVCE:

void setup ()
{      
  SimpleDateFormat format = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss z");
  format.setTimeZone (TimeZone.getDefault());

  long timestamp = getTimeNow();
  println(format.format(new Date(timestamp)));
  println(timestamp);
}

long getTimeNow ()
{
   Date d = new Date ();
   Calendar cal = new GregorianCalendar();

   long current = d.getTime()/1000;
   long timezone = cal.get(Calendar.ZONE_OFFSET)/1000;
   long daylight = cal.get(Calendar.DST_OFFSET)/1000;
   return current + timezone + daylight;
}

Output example:

1970.01.17 17:48:35 GMT 
1442915733

I doubt the issue is with getTimeNow(), since, if I plug the values into an online epoch converter I get the correct time. What is the issue in the above code?

like image 372
MKII Avatar asked Sep 22 '15 08:09

MKII


2 Answers

The Date object parameter accepts the time as long in milliseconds, not seconds. You need to multiply it by 1000. and make sure that you supply it as long.

Date dateObj = new Date(1442915733L * 1000);
System.out.println(dateObj);
like image 132
M S Parmar Avatar answered Oct 05 '22 23:10

M S Parmar


Decided to post this as an answer, since it's different from Mitesh's solution.

I dropped the getTimeNow() function and instead I simply created a new date and used that:

void setup ()
{      
  SimpleDateFormat format = new SimpleDateFormat ("yyyy.MM.dd HH:mm:ss z");
  format.setTimeZone (TimeZone.getDefault());

  Date timestamp = new Date ();
  println(format.format(timestamp));
}

The reason is two fold. I had another issue with the code, after applying Matesh's answer, where the TimeZone would disregard the DST settings, so the hour in the timestamp was wrong. Furthermore, this solution removed the need for several lines of code, which is always helpful.

like image 27
MKII Avatar answered Oct 05 '22 23:10

MKII