M
M
Mimocodil2021-06-13 15:46:24
Java
Mimocodil, 2021-06-13 15:46:24

What is the error of the algorithm (calculating time from currentTimeMillis)?

You need to output the format string:

[HH:MM:SS] LEVEL: text

The problem is that the time is 3 hours behind the real time. Yes, you can just add 3 hours, but I would like to understand the reason.
void log(String level, String text) {
  int h, m, s;

  s = (int) ((System.currentTimeMillis() % (1000 * 60 * 60 * 24)) / 1000);
  s -= (h = s / 3600) * 3600;
  s -= (m = s / 60) * 60;

  System.out.printf("[%02d:%02d:%02d] %s: %s\n", h, m, s, level, text);
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
O
Orkhan, 2021-06-13
@Ezekiel4

Good afternoon.
As a colleague pointed out, the issue is with the timezone.
https://www.tutorialspoint.com/java/lang/system_cu...
System.currentTimeMillis()

This method returns the difference, measured in milliseconds, between the current time and midnight, January 1, 1970 UTC(coordinated universal time).

Date date = new Date(System.currentTimeMillis());
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss", Locale.US);
format.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
String result = format.format(date);
System.out.println(result);

This is how you can convert UTC.
Conclusion:
2021-06-13T19:35:35

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question