Locale and parsing of time

Hi! ESP32 project on the Arduino framework: I'm trying to parse a time string "8:00AM" like this:

strptime(timestr, "%I:%M%p", &tmobject);

...it works, but it does not parse the AM/PM correctly: it is always PM in the resulting tm struct.

I have read that %p depends on the locale, which may not have am/pm values set, so I tried looking into how to set that and came up empty. I tried all of these:

setlocale(LC_TIME, "en_US")
setlocale(LC_TIME, "en_US.utf8")
setlocale(LC_ALL, "en_US")
setlocale(LC_ALL, "en_US.utf8")

...but those calls all return NULL, which indicates that they did not work.

I can parse the AM/PM myself manually, but I'd love to just have strptime do it. Is there a secret to making this work? Is there documentation anywhere about how locales are handled in this context? I didn't google anything up.

Here's a full demo program. This prints "hour is 20" on the ESP32. The analgous program on my desktop prints "hour is 8" as expected.

#include <Arduino.h>
#include <stdio.h>
#include <stdlib.h>
#include <locale.h>
#include <time.h>

void setup()
{
  Serial.begin(115200);
  while (!Serial) delay(10);

  char timestr[7] = "8:00AM";
  static struct tm temptm;
  static time_t temptime;
  temptime = time(NULL);
  temptm = *localtime(&temptime);
  strptime(timestr, "%I:%M%p", &temptm);
  Serial.printf("hour is %d\n", temptm.tm_hour);
}

void loop()
{
    delay(100);
}

seems you found a bug

IIRC at some point they was a bug in IDF and they were not linking strptime() because it was missing from the libc library. I think they fixed this since you can compile but it looks like their implementation is bogus then.

See also: strptime - what am I doing wrong? - ESP32 Forum

Thanks for the replies. I think this marks the first time it wasn't actually my fault. Must be learning. :slight_smile:

Filed a bug here: strptime doesn't parse AM/PM (%p) · Issue #9184 · espressif/arduino-esp32 · GitHub

Edit2: a fix was submitted; "Looks like there is a bug in newlib library. ... Next IDF's toolchain release will have the fix"

Edit3: "this was fixed in esp-4.3.0 of newlib, closing as solved"

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.