473,756 Members | 3,051 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Parse timestamp string

Hi,

I'm looking for advice on how to parse a timestamp string
according to the ISO 8601 specification.

For those unfamiliar with the standard, here's an example:

2003-09-09T23:00:00Z

A compact form of it can as well be without the minuses and
the colons or with timezone information.

The parser should be small and fast and fairly easy to
integrate into C. And if possible, I don't want to link to an
additional library.

I thought so far about doing it in lex/yacc (flex/bison) but
after thinking it through, I don't consider them to be the right
tools for the job.

Regexes would be exactly what I need but I don't want to have
a whole regex engine that calculates the pattern at runtime when
it's not necessary. There must be a cheaper way of doing it.

I've already searched the internet for a kind of regex
compiler/generator that would generate C code for my specific
regex but unfortunately I didn't find anything similar to what I
want.

Of course, I can do it the hard way by messing around with
the string functions in string.h but if I can avoid that I'll do
so.

Any suggestions are appreciated.

Thanks

Reiner
Nov 13 '05 #1
10 14994
Reiner Merz wrote:
Hi,

I'm looking for advice on how to parse a timestamp string
according to the ISO 8601 specification.

For those unfamiliar with the standard, here's an example:

2003-09-09T23:00:00Z

Of course, I can do it the hard way by messing around with
the string functions in string.h but if I can avoid that I'll do
so.

I do not really think this is such a big deal and given your
requirements, that, er, I snipped, I think this is the way to go.

Now, depending on the applications that you have in mind for this piece
of code, I am more than willing to develop that for you for a reasonable
fee. Feel free to contact me directly if you are interested.

--
Bertrand Mollinier Toublet
Currently looking for employment in the San Francisco Bay Area
http://www.bmt.dnsalias.org/employment

Nov 13 '05 #2
On 9 Sep 2003 15:23:52 -0700, lo******@gmx.de (Reiner Merz) wrote:
Hi,

I'm looking for advice on how to parse a timestamp string
according to the ISO 8601 specification.

For those unfamiliar with the standard, here's an example:

2003-09-09T23:00:00Z

A compact form of it can as well be without the minuses and
the colons or with timezone information.

The parser should be small and fast and fairly easy to
integrate into C. And if possible, I don't want to link to an
additional library.


C already includes libraries that include pattern matching. The
example you give can be parsed with:

sscanf( string, "%d-%d-%dT%d:%d:%d%c", /* ... */ );

You need to look at the return code to determine whether the
match was successful or not.

Start with one of the longer patterns first and try each pattern
until you find the one that succeeds.

Nick.

Nov 13 '05 #3


Reiner Merz wrote:
Hi,

I'm looking for advice on how to parse a timestamp string
according to the ISO 8601 specification.

For those unfamiliar with the standard, here's an example:

2003-09-09T23:00:00Z

A compact form of it can as well be without the minuses and
the colons or with timezone information.

The parser should be small and fast and fairly easy to
integrate into C. And if possible, I don't want to link to an
additional library.

I thought so far about doing it in lex/yacc (flex/bison) but
after thinking it through, I don't consider them to be the right
tools for the job.

Regexes would be exactly what I need but I don't want to have
a whole regex engine that calculates the pattern at runtime when
it's not necessary. There must be a cheaper way of doing it.

I've already searched the internet for a kind of regex
compiler/generator that would generate C code for my specific
regex but unfortunately I didn't find anything similar to what I
want.

Of course, I can do it the hard way by messing around with
the string functions in string.h but if I can avoid that I'll do
so.

Any suggestions are appreciated.


You may remove the possible non-digits from the timestamp with
a routine like

char *str = "2003-09-09T23:00:00Z ", buf[32];
int i,j;

for(i = 0,j = 0;str[i] != '\0';i++)
if(str[i] >= '0' && str[i] <= '9')
buf[j++] = str[i];
buf[j] = '\0';

buf would then be "20030909230000 "
Then function sscanf to parse using the format string
"%4u%2u%2u%2u%u %2u"

include <stdio.h>
unsigned yr, mon, day, hr, min, sec

sscanf(buf,"%4u %2u%2u%2u%u%2u" ,&yr,&mon,&day, &hr,&min,&se c);

--
Al Bowers
Tampa, Fl USA
mailto: xa*@abowers.com base.com (remove the x)
http://www.geocities.com/abowers822/

Nov 13 '05 #4
Al Bowers wrote:


You may remove the possible non-digits from the timestamp with a
routine like

char *str = "2003-09-09T23:00:00Z ", buf[32]; int i,j;

for(i = 0,j = 0;str[i] != '\0';i++) if(str[i] >= '0' && str[i] <=
'9') buf[j++] = str[i]; buf[j] = '\0';

buf would then be "20030909230000 "
IIRC ISO8601 requires the T and the Z. You can only remove the - and the
:. And they must be all absent or all present, ie "200309-09T23:00:00Z"
is *NOT* acceptable.
Then function sscanf to parse using the format string
"%4u%2u%2u%2u%u %2u"

include <stdio.h> unsigned yr, mon, day, hr, min, sec

sscanf(buf,"%4u %2u%2u%2u%u%2u" ,&yr,&mon,&day, &hr,&min,&se c);

The big problem with a scanf implementation is that it does not tell you
where an illegal string fails.

--
Michel Bardiaux
Peaktime Belgium S.A. Bd. du Souverain, 191 B-1160 Bruxelles
Tel : +32 2 790.29.41

Nov 13 '05 #5
Thank you all for your contributions.

Unfortunately, this is not what I want but I must admit, I
haven't made myself clear enough.

Your parsing methods are all simple and working for complete
timestamp strings. But sscanf() is just too tolerant in my C
compiler (gcc) to be useful to me.

For example:

If I parse the string

03-09-09T23:00:00Z

"%4d" doesn't return an error on the year because it's not 4
digits long, which I really need.

So, I need a precise scanner function with the parser telling
me exacly where an error occured.

Thanks,

Reiner
Nov 13 '05 #6
lo******@gmx.de (Reiner Merz) wrote:
Thank you all for your contributions.

Unfortunatel y, this is not what I want but I must admit, I
haven't made myself clear enough.

Your parsing methods are all simple and working for complete
timestamp strings. But sscanf() is just too tolerant in my C
compiler (gcc) to be useful to me.

<SNIP>

Hmm, well, it seems you are in trouble now.
Let me put it together:

You don't want to:
- link against an external library
- use lex/yacc (which, IMHO, are well suited to produce a
scanner/parser; that's what they're made for)
- use any other third party universal regex driven parsing engine
- "mess around" with C's string functions
- use sscanf (for good reasons, IMO)

IMHO you have to drop at least one of these restrictions to accomplish
your mission. Choose the solution that looks least worse to you.

My two-cent suggestion: use (f)lex/yacc(bison) - this way your
scanner/parser will be easier to maintain than any hand crafted
solution.

Good luck to you!

Regards

Irrwahn

--
The generation of random numbers is too important to be left to chance.
Nov 13 '05 #7
On 19 Sep 2003 03:29:06 -0700, in comp.lang.c , lo******@gmx.de
(Reiner Merz) wrote:
If I parse the string

03-09-09T23:00:00Z

"%4d" doesn't return an error on the year because it's not 4
digits long, which I really need.

So, I need a precise scanner function with the parser telling
me exacly where an error occured.


read the string char by char. Decide what you have as you receive it.

eg
read 2 chars
if next char is not numeric, then add 2000 to first two to form year
etc
--
Mark McIntyre
CLC FAQ <http://www.eskimo.com/~scs/C-faq/top.html>
CLC readme: <http://www.angelfire.c om/ms3/bchambless0/welcome_to_clc. html>
Nov 13 '05 #8
Hi Irrwahn,
You don't want to:
- use lex/yacc (which, IMHO, are well suited to produce a
scanner/parser; that's what they're made for)


You must have got me wrong there.

I did try to use lex/yacc because I thought they were made
for these kind of problems, but I didn't succeed. But my
inability to do it could be due to the fact that I've only
rarely used lex/yacc and when I used it, I used it for simple
configuration files. So, you could say, I'm not really
experienced.

My problem was mainly the scanner. I wanted to define my tokens

YEAR as four digits
MONTH as two digits
DAY as two digits
HOUR as two digits
MINUTE as two digits
SECOND as two digits

So, how can the scanner possibly distinguish between MONTH,
DAY, HOUR, MINUTE and SECOND? The flex manual says it picks the
longest possible match and if there are equally long matches it
picks the first defined token.

Ok, I could define a FOURDIGIT and a TWODIGIT token and then
assign the right values in bison. I guess that would work for

2003-09-09T23:00:00Z

but for

20030909T230000 Z (which is a legal date time according to the
ISO specification)

I would imagine, lex gives me

FOURDIGIT 2003
FOURDIGIT 0909
FOURDIGIT 2300
TWODIGIT 00

and that is not really what I want.

But maybe I didn't understand the way lex/yacc work.

Cheers,

Reiner
Nov 13 '05 #9
lo******@gmx.de (Reiner Merz) wrote:
Hi Irrwahn,
You don't want to:
- use lex/yacc (which, IMHO, are well suited to produce a
scanner/parser; that's what they're made for)
You must have got me wrong there.

Possibly ... :)
I did try to use lex/yacc because I thought they were made
for these kind of problems, but I didn't succeed. But my
inability to do it could be due to the fact that I've only
rarely used lex/yacc and when I used it, I used it for simple
configuratio n files. So, you could say, I'm not really
experienced.

My problem was mainly the scanner. I wanted to define my tokens

YEAR as four digits
MONTH as two digits
DAY as two digits
HOUR as two digits
MINUTE as two digits
SECOND as two digits

So, how can the scanner possibly distinguish between MONTH,
DAY, HOUR, MINUTE and SECOND? The flex manual says it picks the
longest possible match and if there are equally long matches it
picks the first defined token.

Ok, I could define a FOURDIGIT and a TWODIGIT token and then
assign the right values in bison. I guess that would work for

2003-09-09T23:00:00Z

but for

20030909T230000 Z (which is a legal date time according to the
ISO specification)
Blame me, I was only thinking about the hyphen-separated format.
(And, besides, IMO the latter format is sheer braindead.)

I would imagine, lex gives me

FOURDIGIT 2003
FOURDIGIT 0909
FOURDIGIT 2300
TWODIGIT 00

and that is not really what I want.
Well, obviously not, and furthermore, I cannot imagine a way to tell lex
how to disambiguate this and tokenize appropriately; but I am far from
being a lex expert.

But maybe I didn't understand the way lex/yacc work.


Possibly better than I do.

However, to get back to your original problem, maybe the easiest
solution is to handcraft a scanner, traversing the string and use the
is*() functions from ctype.h, a la:

- read four consecutive digits, interprete as year
- gulp an optional hyphen
- read two consecutive digits, interprete as month
- gulp an optional hyphen
- read two consecutive digits, interprete as day
- gulp the mandatory 'T'
- read two consecutive digits, interprete as hour
- gulp an optional colon
- ... etc.

Not really a nice thing to do I admit, and you have to provide a lot of
error checking; but, after all, you know exactly the way your code
works.

Sorry, I'm unable to provide a better solution, maybe someone else can.
Good luck to you!

Regards

Irrwahn
--
My other computer is a abacus.
Nov 13 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
22044
by: N | last post by:
Hi, I would like to parse out each value that is seperated by a comma in a field and use that value to join to another table. What would be the easiest way to do so without having to write a function or routine ? EX. Table AAA COL1 COL2
15
3211
by: Jeannie | last post by:
Hello group! I'm in Europe, traveling with my laptop, and I don't any compilers other than Borland C++ 5.5. available. I also don't have any manuals or help files available. Sadly, more crippling problems! I never used C++ much, so, I don't remember commands or fuctions well. My questions are simple. I posted the DOS window output so you can see the Borland C++ version I am using: E:\TZ>bcc32 file2
9
5712
by: Danny | last post by:
HI again Is there a nifty function in access that will: 1. return the amount of occurances of a small string within a larger string? this<br>is<br>a<br>test would return 3 for <br>
19
20584
by: linzhenhua1205 | last post by:
I want to parse a string like C program parse the command line into argc & argv. I hope don't use the array the allocate a fix memory first, and don't use the memory allocate function like malloc. who can give me some ideas? The following is my program, but it has some problem. I hope someone would correct it. //////////////////////////// //Test_ConvertArg.c ////////////////////////////
16
5883
by: Charles Law | last post by:
I have a string similar to the following: " MyString 40 "Hello world" all " It contains white space that may be spaces or tabs, or a combination, and I want to produce an array with the following elements arr(0) = "MyString" arr(1) = 40 arr(2) = "Hello world"
2
4768
by: David Garamond | last post by:
When a timestamp string input contains a timezone abbreviation (CDT, PST, etc), which timezone offset is used? The input date's or today date's? The result on my computer suggests the latter. # create table ts (ts timestamptz); # insert into ts values ('2004-10-17 00:00:00 CDT'); -- UTC-5 # insert into ts values ('2004-11-17 00:00:00 CDT'); -- UTC-6 # select ts at time zone 'utc' from ts; timezone ---------------------
4
9492
by: Phil Mc | last post by:
OK this should be bread and butter, easy to do, but I seem to be going around in circles and not getting any answer to achieving this simple task. I have numbers in string format (they are coming in from an excel sheet): Examples. 45,666.0041 5664456.12 -5465.25568 ETC
1
2712
by: Dan Somdahl | last post by:
Hi, I am new to ASP but have what should be a fairly simple task that I can't figure out. I need to parse a string from a single, semi-colon delimited, 60 character field (el_text) in a recordset and display the results in a table on a webpage (ASP) I can retrieve the recordset from the database and display the field data results in rows of a table but have the entire 60 character string in one cell. I need to break that string apart...
2
3646
by: tekt9t9 | last post by:
Hello I want to parse a string which holds a integer value to an int. The Interger.parseint() throws an exception. e.g If i try to execute the following code: i = Integer.parseInt("14141414141414"); it throws the following exception: Exception in thread "main" java.lang.NumberFormatException: For input string: "14141414141414"
0
10032
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9872
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9841
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9711
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8712
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7244
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6534
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5303
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3358
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.