Re: Date parsing question...
Re: Date parsing question...
- Subject: Re: Date parsing question...
- From: "Alastair J.Houghton" <email@hidden>
- Date: Tue, 28 Oct 2003 21:02:02 +0000
On Tuesday, October 28, 2003, at 06:09 pm, Daniele M. wrote:
hello, I have a string like this 20031028180309 (it's a date:
2003/10/28 18:03:09). I have tried to parse it using dateWithString and
dateWithNaturalLanguage...but with null/wrong result. Is there a method
to parse it?
One possibility is to use the C run-time, for example
int year, month, day, hours, minutes, seconds;
sscanf ([myString UTF8String], "M-----", &year, &month,
&day,
&hours, &minutes, &seconds);
or, if you want to use Cocoa a bit more, a somewhat less efficient
solution might be
int year = [[myString substringToIndex:4] intValue];
int month = [[myString substringWithRange:NSMakeRange(4, 2)]
intValue];
int day = [[myString substringWithRange:NSMakeRange(6, 2)] intValue];
int hours = [[myString substringWithRange:NSMakeRange(8, 2)]
intValue];
int minutes = [[myString substringWithRange:NSMakeRange(10, 2)]
intValue];
int seconds = [[myString substringWithRange:NSMakeRange(12, 2)]
intValue];
Alternatively, you can do it by hand... for example:
/* A function to scan an integer value, stopping if it hits a
non-digit character,
the end of the string, or the (specified) maximum length */
int scanint (unichar *ptr, int maxlen)
{
int ret = 0;
while (maxlen--) {
/* Stop if we hit a character that isn't a digit */
if (*ptr < '0' || *ptr > '9')
return ret;
ret = 10 * ret + *ptr - '0';
}
return ret;
}
unichar buffer[14];
int year, month, day, hours, minutes, seconds;
if ([myString length] < 14) {
/* Not a valid input */
}
/* Get the string's characters */
[myString getCharacters:buffer range:NSMakeRange(0, 14)];
/* Scan all of the values */
year = scanint (&buffer[0], 4);
month = scanint (&buffer[4], 2);
day = scanint (&buffer[6], 2);
hours = scanint (&buffer[8], 2);
minutes = scanint (&buffer[10], 2);
seconds = scanint (&buffer[12], 2);
It's worth realising that the first two solutions will actually allow
negative values(!), so you might want to check that your string only
contains numbers if you're going to use one of them. The latter
solution is probably the most efficient, and will allow you to
customise its behaviour when it sees input that isn't in the format you
expect.
(Of course, the usual caveat about code typed in Mail applies.)
Kind regards,
Alastair.
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.