Request: Time::fromString()

Hi, Jules.

Could you add this method in class Time?

// The parameter 'timeString' should be created by the Time::toString() method...
Time fromString (const String& timeString);

Cheers!

Sorry - converting a time to a string is easy enough, but going the other way would be insanely difficult! How could it possibly know what format the string is in, or what language? If you have a string where you actually know the format, then you should write your own parser for it, but I think it'd be practically impossible to write a general-purpose date parser.


// The parameter 'timeString' should be created by the Time::toString() method...

Time fromString (const String& timeString);

 

And yes, I have a lot of time-string but I actually don't know the format, because these string were created by Time::toString()...smiley
 

Yes, but the format that Time::toString uses will be locale-dependent. And if the string doesn't include a time-zone name, how could it possibly know which time-zone to use.. Honestly, you could spend a lifetime trying to write a time parser and still not get it right in all cases!

A small devised to put you on the path may eters even after 1 year smiley


 Time DatefromString(String value, String format = "%d/%d/%d")
 {
         int year, month, day;
         sscanf(value.toRawUTF8(), format.toRawUTF8(), &day, &month, &year);
         return Time( year, month-1, day, 0, 0);
 }

so the developer can specify the format ...
 

Not sure you've thought that idea through very deeply! e.g. how would you specify a USA-style date format with a reversed day/month?

I really think it's better to leave this up to developers to write appropriately for their own app.

Oops it's true that I have not thought ... mea culpa Juleswink

Take a look at ICU if you really need this...Or if you are targetting Mac only CFDateFormatterRef (which uses ICU under the hood).  It takes locale into consideration and you throw it the string with a format code(ie... "EEE, dd MMM yyyy HH:mm:ss z") and it figures things out

 

If the date is in something like ISO8601 then writing your own parser is pretty easy