String to Date conversion for UNIX?
I have string 2010-07-26 18:37:12 and I want to convert it to date format so that I can compare it with other strings and check whether date (2010-07-2开发者_运维问答6 18:37:12) is earlier or not.
Could anyone suggest way to convert this string to date?
The strptime function is what you want
man strptime
For your example
struct tm stm;
strptime(string, "%Y-%m-%d %H:%M:%s", &stm);
The beauty of the ISO 8601 notation you show is that a string comparison between two dates tells you the relative orders. As long as all the dates you need to compare are AD (or CE) rather than BC (or BCE) and expressed in the same time zone, then it is trivial:
2010-07-26 18:37:12 > 2001-10-31 15:36:21
2010-07-26 18:37:12 < 2010-12-25 00:00:00
If you need to deal with other date formats, then strptime()
is your friend.
I have a program (imaginatively named strptime) that will do the job (see my profile to contact me); there are probably other tools to do so. However, even strptime()
has some issues with time zones - especially named time zones rather than pure numeric offsets.
精彩评论