The best method I could come up with, after some input from Guru, is:

date_add('millisecond', duration, TIME '00:00:00.000')
Answer from BeRT2me on Stack Overflow
🌐
GitHub
github.com › prestodb › presto › issues › 21025
FROM_UNIXTIME generate a timestamp that does not fit as int64_t milliseconds · Issue #21025 · prestodb/presto
October 3, 2023 - I need help with something, SELECT TO_UNIXTIME(FROM_UNIXTIME(3.87111e+37)) give me as output 9223372036854800. this number 9223372036854800 will overflow if we try to store it in int64_t as milliseconds. presto shuffles serialize a timestamp as int64_t(millis).
Author   prestodb
Discussions

sql - Trying to get HH:MM:SS from milliseconds in Presto - Stack Overflow
I'm trying to convert milliseconds to format HH:MM:SS or MM:SS, but I keep getting the same error. More on stackoverflow.com
🌐 stackoverflow.com
October 18, 2021
Support extracting milliseconds from a timestamp
presto> select extract(millisecond from (timestamp '2017-10-24 23:00:23.206')); Query 20171208_215149_00048_uhmtc failed: line 1:8: Invalid EXTRACT field: millisecond More on github.com
🌐 github.com
8
December 10, 2017
millis() overflow prone code

I'm not sure what people mean by "jitters", Internally it is just a timer set to interrupt every 1 millisecond, and when it does it then increments a variable by 1. millis() then returns that variable when called. So I don't see a way for it to go anywhere but up.

EDIT: After Googling it, it seems people are referring to variances in how long millis() thinks 1 milliseconds is, due to internal clock differences and the use of an aggressive prescaler. So it may be that if you call millis(), wait 1.1 milliseconds, then call again, it still says the same value. Over time these variances average out to 1 millisecond though.

More on reddit.com
🌐 r/arduino
8
1
September 7, 2023
Millis overflow
I find uint32_t difficult to think in, but uint16_t is easier. So, without overflow, we have something like t1 = 100, millis = 750: millis - t1 = 650, which is greater than 500, so true. OK, so what about overflow? t1 = 65505 (31 milliseconds before overflow), millis = 200, what's 200 - 65505 in integer math? So it turns out that 200 - 65505 = 231, which is... exactly what we want. This works in uint32_t too, so if your code looks like this: if(millis() - t1 > 500) { // ... do something t1 = millis(); } It will work exactly as you intend, even if millis overflows. More on reddit.com
🌐 r/esp32
14
1
May 9, 2023
🌐
Stack Overflow
stackoverflow.com › questions › 69616178 › trying-to-get-hhmmss-from-milliseconds-in-presto
sql - Trying to get HH:MM:SS from milliseconds in Presto - Stack Overflow
October 18, 2021 - Note that this will work only if you have less than 24 hours interval in your milliseconds, otherwise you will need to do math yourself and concat results into desired string.
🌐
GitHub
github.com › prestodb › presto › issues › 9524
Support extracting milliseconds from a timestamp · Issue #9524 · prestodb/presto
December 10, 2017 - presto> select extract(millisecond from (timestamp '2017-10-24 23:00:23.206')); Query 20171208_215149_00048_uhmtc failed: line 1:8: Invalid EXTRACT field: millisecond
Author   prestodb
🌐
Blogger
evafengeva.blogspot.com › 2017 › 09 › how-to-convert-milliseconds-or-seconds.html
How to convert milliseconds or seconds into date format in Presto?
September 26, 2017 - Milliseconds: DATE_FORMAT(FROM_UNIXTIME(column_name /1000),'%Y-%m-%d') Seconds: DATE_FORMAT(FROM_UNIXTIME(column_name),'%Y-%m-%d') Please note that '/1000' should be added when it converts milliseconds to human-readable format.
🌐
Reddit
reddit.com › r/arduino › millis() overflow prone code
millis() overflow prone code : r/arduino
September 7, 2023 - millis() does not jitter as you describe, a second reading is always >= the previous reading. In the overflow case the second reading may be lower than the first, but if you do the math second-first you get the right answer because the math also overflows and the end result is correct.
Find elsewhere
🌐
Norwegian Creations
norwegiancreations.com › 2018 › 10 › arduino-tutorial-avoiding-the-overflow-issue-when-using-millis-and-micros
Arduino Tutorial: Avoiding the Overflow Issue When Using millis() and micros() – Norwegian Creations
October 11, 2018 - Here we will get a buggy behavior after approximately 50 days when millis() will go from returning a very high number (close to (2^32)-1) to a very low number. This is known as overflow or rollover.
🌐
Trino
trino.io › docs › current › release › release-0.153.html
Release 0.153 — Trino 477 Documentation
Add support for the Presto real type, which corresponds to the Hive float type.
Top answer
1 of 4
187

Short answer: do not try to “handle” the millis rollover, write rollover-safe code instead. Your example code from the tutorial is fine. If you try to detect the rollover in order to implement corrective measures, chances are you are doing something wrong. Most Arduino programs only have to manage events that span relatively short durations, like debouncing a button for 50 ms, or turning a heater on for 12 hours... Then, and even if the program is meant to run for years at a time, the millis rollover should not be a concern.

The correct way to manage (or rather, avoid having to manage) the rollover problem is to think of the unsigned long number returned by millis() in terms of modular arithmetics. For the mathematically inclined, some familiarity with this concept is very useful when programming. You can see the math in action in Nick Gammon's article millis() overflow ... a bad thing?. For the problem at hand, what's important to know is that in modular arithmetics the numbers “wrap around” when reaching a certain value – the modulus – so that 1 − modulus is not a negative number but 1 (think of a 12 hour clock where the modulus is 12: here 1 − 12 = 1).

For those who do not want to go through the computational details, I offer here an alternative (hopefully simpler) way of thinking about it. It is based on the simple distinction between instants and durations. As long as your tests only involve comparing durations, you should be fine.

Note on micros(): Everything said here about millis() applies equally to micros(), except for the fact that micros() rolls over every 71.6 minutes, and the setMillis() function provided below does not affect micros().

Instants, timestamps and durations

When dealing with time, we have to make the distinction between at least two different concepts: instants and durations. An instant is a point on the time axis. A duration is the length of a time interval, i.e. the distance in time between the instants that define the start and the end of the interval. The distinction between these concepts is not always very sharp in everyday language. For example, if I say “I will be back in five minutes”, then “five minutes” is the estimated duration of my absence, whereas “in five minutes” is the instant of my predicted coming back. Keeping the distinction in mind is important, because it is the simplest way to entirely avoid the rollover problem.

The return value of millis() could be interpreted as a duration: the time elapsed from the start of the program until now. This interpretation, however, breaks down as soon as millis overflows. It is generally far more useful to think of millis() as returning a timestamp, i.e. a “label” identifying a particular instant. It could be argued that this interpretation suffers from these labels being ambiguous, as they are reused every 49.7 days. This is, however, seldom a problem: in most embedded applications, anything that happened 49.7 days ago is ancient history we do not care about. Thus, recycling the old labels should not be an issue.

Do not compare timestamps

Trying to find out which among two timestamps is greater than the other does not make sense. Example:

unsigned long t1 = millis();
delay(3000);
unsigned long t2 = millis();
if (t2 > t1) { ... }

Naively, one would expect the condition of the if () to be always true. But it will actually be false if millis overflows during delay(3000). Thinking of t1 and t2 as recyclable labels is the simplest way to avoid the error: the label t1 has clearly been assigned to an instant prior to t2, but in 49.7 days it will be reassigned to a future instant. Thus, t1 happens both before and after t2. This should make clear that the expression t2 > t1 makes no sense.

But, if these are mere labels, the obvious question is: how can we do any useful time calculations with them? The answer is: by restricting ourselves to the only two calculations that make sense for timestamps:

  1. later_timestamp - earlier_timestamp yields a duration, namely the amount of time elapsed between the earlier instant and the later instant. This is the most useful arithmetic operation involving timestamps.
  2. timestamp ± duration yields a timestamp which is some time after (if using +) or before (if −) the initial timestamp. Not as useful as it sounds, since the resulting timestamp can be used in only two kinds of calculations...

Thanks to modular arithmetics, both of these are guaranteed to work fine across the millis rollover, at least as long as the delays involved are shorter than 49.7 days.

Comparing durations is fine

A duration is just the amount of milliseconds elapsed during some time interval. As long as we do not need to handle durations longer than 49.7 days, any operation that physically makes sense should also make sense computationally. We can, for example, multiply a duration by a frequency to get a number of periods. Or we can compare two durations to know which one is longer. For example, here are two alternative implementations of delay(). First, the buggy one:

void myDelay(unsigned long ms) {          // ms: duration
    unsigned long start = millis();       // start: timestamp
    unsigned long finished = start + ms;  // finished: timestamp
    for (;;) {
        unsigned long now = millis();     // now: timestamp
        if (now >= finished)              // comparing timestamps: BUG!
            return;
    }
}

And here is the correct one:

void myDelay(unsigned long ms) {              // ms: duration
    unsigned long start = millis();           // start: timestamp
    for (;;) {
        unsigned long now = millis();         // now: timestamp
        unsigned long elapsed = now - start;  // elapsed: duration
        if (elapsed >= ms)                    // comparing durations: OK
            return;
    }
}

Most C programmers would write the above loops in a terser form, like

while (millis() < start + ms) ;  // BUGGY version

and

while (millis() - start < ms) ;  // CORRECT version

Although they look deceptively similar, the timestamp/duration distinction should make clear which one is buggy and which one is correct.

What if I really need to compare timestamps?

Better try to avoid the situation. If it is unavoidable, there is still hope if it is known that the respective instants are close enough: closer than 24.85 days. Yes, our maximum manageable delay of 49.7 days just got cut in half.

The obvious solution is to convert our timestamp comparison problem into a duration comparison problem. Say we need to know whether instant t1 is before or after t2. We choose some reference instant in their common past, and compare the durations from this reference until both t1 and t2. The reference instant is obtained by subtracting a long enough duration from either t1 or t2:

unsigned long reference_instant = t2 - LONG_ENOUGH_DURATION;
unsigned long from_reference_until_t1 = t1 - reference_instant;
unsigned long from_reference_until_t2 = t2 - reference_instant;
if (from_reference_until_t1 < from_reference_until_t2)
    // t1 is before t2

This can be simplified as:

if (t1 - t2 + LONG_ENOUGH_DURATION < LONG_ENOUGH_DURATION)
    // t1 is before t2

It is tempting to simplify further into if (t1 - t2 < 0). Obviously, this does not work, because t1 - t2, being computed as an unsigned number, cannot be negative. This, however, although not portable, does work:

if ((signed long)(t1 - t2) < 0)  // works with gcc
    // t1 is before t2

The keyword signed above is redundant (a plain long is always signed), but it helps make the intent clear. Converting to a signed long is equivalent to setting LONG_ENOUGH_DURATION equal to 24.85 days. The trick is not portable because, according to the C standard, the result is implementation defined. But since the gcc compiler promises to do the right thing, it works reliably on Arduino. If we wish to avoid implementation defined behavior, the above signed comparison is mathematically equivalent to this:

#include <limits.h>

if (t1 - t2 > LONG_MAX)  // too big to be believed
    // t1 is before t2

with the only problem that the comparison looks backwards. It is also equivalent, as long as longs are 32-bits, to this single-bit test:

if ((t1 - t2) & 0x80000000)  // test the "sign" bit
    // t1 is before t2

The last three tests are actually compiled by gcc into the exact same machine code.

How do I test my sketch against the millis rollover

If you follow the precepts above, you should be all good. If you nevertheless want to test, add this function to your sketch:

#include <util/atomic.h>

void setMillis(unsigned long ms)
{
    extern unsigned long timer0_millis;
    ATOMIC_BLOCK (ATOMIC_RESTORESTATE) {
        timer0_millis = ms;
    }
}

and you can now time-travel your program by calling setMillis(destination). If you want it to go through the millis overflow over and over again, like Phil Connors reliving Groundhog Day, you can put this inside loop():

// 6-second time loop starting at rollover - 3 seconds
if (millis() - (-3000) >= 6000)
    setMillis(-3000);

The negative timestamp above (-3000) is implicitly converted by the compiler to an unsigned long corresponding to 3000 milliseconds before the rollover (it is converted to 4294964296).

What if I really need to track very long durations?

If you need to turn a relay on and turn it off three months later, then you really need to track the millis overflows. There are many ways to do so. The most straightforward solution may be to simply extend millis() to 64 bits:

uint64_t millis64() {
    static uint32_t low32, high32;
    uint32_t new_low32 = millis();
    if (new_low32 < low32) high32++;
    low32 = new_low32;
    return (uint64_t) high32 << 32 | low32;
}

This is essentially counting the rollover events, and using this count as the 32 most significant bits of a 64 bit millisecond count. For this counting to work properly, the function needs to be called at least once every 49.7 days. However, if it is only called once per 49.7 days, for some cases it is possible that the check (new_low32 < low32) fails and the code misses a count of high32. Using millis() to decide when to make the only call to this code in a single "wrap" of millis (a specific 49.7 day window) could be very hazardous, depending on how the time frames line up. For safety, if using millis() to determine when to make the only calls to millis64(), there should be at least two calls in every 49.7 day window.

Keep in mind, though, that 64 bit arithmetic is expensive on the Arduino. It may be worth to reduce the time resolution in order to stay at 32 bits.

2 of 4
39

TL;DR Short version:

An unsigned long is 0 to 4,294,967,295 (2^32 - 1).

So lets say previousMillis is 4,294,967,290 (5 ms before rollover), and currentMillis is 10 (10ms after rollover). Then currentMillis - previousMillis is actual 16 (not -4,294,967,280) since the result will be calculated as an unsigned long (which can't be negative, so itself will roll around). You can check this simply by:

Serial.println( ( unsigned long ) ( 10 - 4294967290 ) ); // 16

So the above code will work perfectly fine. The trick is to always calculate the time difference, and not compare the two time values.

🌐
Bald Engineer
baldengineer.com › home › arduino: how do you reset millis() ?
Arduino: How do you reset millis() ? - Bald Engineer
March 31, 2022 - I tried to rewrite your proof code with unsigned long variables and I set to “counter” variable near the overflow variable and it works correct even without retyping in IF statement. ... People who understand the compiler’s rules much better than I have told me it is a good idea. I haven’t proven to myself yet if it is required. ... Ok I asked about this on arduino forum and looks like your retyping of variable in IF statement is not need, it will work just with simple millis() – previousMillis.
🌐
GitHub
github.com › prestodb › presto › issues › 27934
Parameterized Timestamp for Presto · Issue #27934 · prestodb/presto
June 5, 2026 - Prerequisite: org.apache.iceberg:iceberg-core at 1.10.1 (already present in prestodb/presto — Types.TimestampNanoType and Types.TimestamptzNanoType are available, no dependency change needed). ... Breaking behavioral change: The mapping of Iceberg timestamp (µs) from TIMESTAMP(3) to TIMESTAMP(6) is a correctness fix — the prior mapping silently discarded sub-millisecond data.
Author   prestodb
🌐
Arduino Forum
forum.arduino.cc › projects › programming
Millis overflow - Programming - Arduino Forum
September 11, 2012 - Please i would like to know does millis overflow (go back to zero), after approximately 50 days as i found here or it resets after 9 hours and 32 minutes. as i found here http://www.faludi.com/2007/12/18/arduino-milli…