0

I'm trying to use the ICU library to convert a time stamp from a string to a time_t value.

To do so, I though all I had to do is create a time instance and call its parse() function. Unfortunately, all I get is a U_ILLEGAL_ARGUMENT_ERROR from the parser.

There is a simplified version of the code that shows the unexpected behavior:

#include <iostream>
#include <unicode/datefmt.h>
#include <unicode/errorcode.h>
#include <unicode/locid.h>
#include <unicode/smpdtfmt.h>
#include <unicode/timezone.h>

int main(int argc, char *argv[])
{
    LocalPointer<DateFormat> dt(DateFormat::createTimeInstance());

    UErrorCode err(U_ZERO_ERROR);
    UDate const result(dt->parse("12:05:33", err));

    std::cerr << "*** err = " << u_errorName(err)
              << " and result = " << result << "\n";

    return 0;
}

When I run this, the output is

*** err = U_ILLEGAL_ARGUMENT_ERROR and result = 0

I was expecting something more like a representation of the time such as 12 x 3600 + 5 * 60 + 33 = 43533.

Am I doing something wrong? From the documentation, it looks like the library is capable of converting various types of time stamps.

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156

1 Answers1

0

Most likely, the format of your time string does not match the default style/locale of the DateFormat object that createTimeInstance() returns. Use the style and aLocale parameters of createTimeInstance() to specify the particular style/locale that parse() should expect.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • Yeah, I tried that with "en_US". The default locale is "English". I really don't see why the time I have would fail in English. I also tried with other times like "05:33" and "11:20 AM". – Alexis Wilke May 24 '15 at 06:48
  • I also have a timezone setup like this: `LocalPointer tz(TimeZone::createTimeZone("Pacific Time"));` and `dt->setTimeZone(*tz);`. It doesn't help either. – Alexis Wilke May 24 '15 at 06:52
  • You are focusing on the `locale` and ignoring the `style`. The default `style` for `createTimeInstance()` is `kDefault`, which is an alias for `kMedium`. Try specifying `kShort` instead: `DateFormat::createTimeInstance(kShort, Locale::getUS())` – Remy Lebeau May 24 '15 at 08:25
  • I tried them all, short, full, medium... Plus it feels like these represent the length of the date rather than the time. Not too sure though. – Alexis Wilke May 24 '15 at 11:49