I have an Arduino program that connects to a java web server, and I need to synchronize time. But there is a one hour sync problem.
The output of this Java program:
public class Test { public static void main(String[] args) { java.util.Date d = new java.util.Date(2018-1900, 11-1, 22, 05, 48, 10); // 22th Nov 2018, 05:48:10 System.out.println(d); long t = d.getTime() / 1000; System.out.println(t); } } is
Thu Nov 22 05:48:10 CET 2018 1542862090 Then, I check on https://www.unixtimestamp.com/
Enter a Timestamp: 1542862090 -> Convert -> Timestamp Converter: 1542862090 Is equivalent to: 11/22/2018 @ 4:48am (UTC) Why do I have this one hour difference (05:48 - 4:48)?
In contrast, running an equivalent program in Arduino using this library:
#include <RtcDS3231.h> void setup() { Serial.begin(115200); RtcDateTime date = RtcDateTime(2018, 11, 22, 05, 48, 10); // 22th Nov 2018, 05:48:10 uint32_t t = date.Epoch32Time(); Serial.println(t); } the output is: 1542865690
Then, I check on https://www.unixtimestamp.com/ Enter a Timestamp: 1542865690 -> Convert ->
Timestamp Converter: 1542865690 Is equivalent to: 11/22/2018 @ 5:48am (UTC) This looks correct.
The problem is that the java web server sends the epoch time (a long number) to arduino, arduino rebuilds the data as follows, and I get one hour difference:
RtcDateTime date = RtcDateTime(0); date2.InitWithEpoch32Time(t); Serial.println(date.Hour()); // 4 How I get the correct epoch time in Java, independently of time zone? Or, is the Java result correct, and that arduino library is buggy? What am I missing?
05:48:10 CETvs4:48am (UTC)CET != UTCDate.getTime(andSystem.currentTimeMillis)return the epoch time using the default system time zone (this was Zurich in my case). That arduino library does not have the concept of time zone (so, it uses the equivalent ofZoneOffset.UTC). So we need to explicitly return the time using theZoneOffset.UTC.long t = java.time.LocalDateTime.now.atZone(java.time.ZoneOffset.UTC).toInstant.toEpochMilli / 1000ZoneId.systemDefault, while the arduino library was parsing the epoch time using the equivalent ofZoneOffset.UTC. As that arduino library does not handle timezones, my solution is to tell the java program to use alsoZoneOffset.UTC.long t = java.time.LocalDateTime.now.atZone(java.time.ZoneOffset.UTC).toInstant.toEpochMilli / 1000LocalDateTimefor handling moments. Precisely the wrong class to use here.