Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ISO 8601 to time_t conversion in C or vice versa

Tags:

c

iso8601

time-t

According to ISO 8601, time can be specified in different formats.

My program does not know which exact ISO 8601 format will be specified.

In this case, how can I convert it to time_t?

strptime requires you to specify format (which I do not know before hand in my case).

Ultimate goal: is to compare 2 time_t timestamps.

Edit 0: Because my goal is to compare 2 time stamps, time_t to ISO 8601 conversion will also work.

like image 435
hari Avatar asked Jul 07 '11 22:07

hari


2 Answers

If you are on a UNIX like machine, try getdate. The interface is funky but works pretty good.

Which formats are recognized is controlled by the file named by the environment variable DATEMSK. This file should contain lines of valid format strings which could be passed to strptime.

like image 93
Byron Whitlock Avatar answered Nov 14 '22 21:11

Byron Whitlock


You say you need to compare two time_t values, ultimately. But how are you obtaining those values? If they are sent as strings, then Byron Whitlock's answer is plausible if your machine supports getdate(). If they are already time_t, then you can compare the time values. If you need to compare a time_t generated locally with a string generated remotely, then you are caught between a rock and a hard place; you have to know somehow which ISO 8601 style is used when the data is sent.

Note that ISO 8601 expects that the two systems exchanging information will agree on the notation they are going to use, and in particular that they will agree on which fields can be left out (if any) and whether punctuation will separate the fields. If you know the (single) format, or can configure your system so that for each data source, you now the ISO 8601 format that will be used, then the POSIX strptime() function can handle pretty much everything - though you need to know how your code is going to handle any undefined fields.

The title of the standard is, in full: "ISO 8601:2004 Data elements and interchange formats — Information interchange — Representation of dates and times". Its section §3.7 Mutual agreement says:

Some of the representations identified in this International Standard are only allowed by mutual agreement of the partners in information interchange. Such agreement should ensure that fields in which the representation may occur are not allowed to hold other representations that cannot be unambiguously distinguished from the agreed representation.

like image 40
Jonathan Leffler Avatar answered Nov 14 '22 21:11

Jonathan Leffler