limit length of the generated timestamp from ESP32 with DS3231 to 13
For getting millisecond resolution out of an RTC, I think the only
viable solution is to sync with the 1&nbsp;Hz square wave output, as
suggested by Jot in a comment. Note that, since you are only counting
seconds and milliseconds, you probably don't care about hours, minutes,
days, months, etc. So you won't use the RTC for timekeeping: only for
providing the 1&nbsp;Hz reference signal and, maybe, an initial
timestamp at program startup.

Connect the SQW pin of the DS3231 to an interrupt-capable input of your
MCU. Add the following to your setup():



pinMode(SQW_PIN, INPUT_PULLUP);
rtc.writeSqwPinMode(DS3231_SquareWave1Hz);
attachInterrupt(digitalPinToInterrupt(SQW_PIN), tick, FALLING);


Use the interrupt routine to both keep track of the total second count
(seconds elapsed since the Unix epoch) and record the micros() value
of the last tick:

volatile uint32_t seconds_since_epoch;
volatile uint32_t micros_on_tick;

void tick() {
    seconds_since_epoch++;
    micros_on_tick = micros();
}


Now you can combine these two values to get a millisecond-resolved
timestamp as follows:

uint64_t millis_since_epoch() {
    noInterrupts();
    uint32_t seconds = seconds_since_epoch;
    uint32_t microseconds = micros_on_tick;
    interrupts();
    uint32_t extra_micros = micros() - microseconds;
    uint16_t extra_millis = extra_micros / 1000;
    if (extra_millis &gt; 999)
        extra_millis = 999;
    return (uint64_t) seconds * 1000 + extra_millis;
}


The value returned from this function is the 13-digit number you want,
provided seconds_since_epoch has been sensibly initialized.