开发者

ISO 8601 to time_t conversion in C or vice versa

开发者 https://www.devze.com 2023-03-18 07:58 出处:网络
According to ISO 8601, time can be specified in different formats. My program does not know which exact ISO 8601 format wil开发者_高级运维l be specified.

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

My program does not know which exact ISO 8601 format wil开发者_高级运维l 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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消