开发者

how to split date/time in c++?

I would like to spit a date/time string (for example 1/08/1957/11:20:01, or any type of time format) into month, hour, second, minute. The problem is that firstly I don't know how to define a type of time tha开发者_开发百科t can be split.

Should I write:

time_t now=1081987112001 s; //it is not correct. why? what's the c++ time data format?
struct tm* tm = localtime(&now);

cout << "Today is "
     << tm->tm_mon+1 // month
     << "/" << tm->tm_mday // day
     << "/" << tm->tm_year + 1900 // year with century
     << " " << tm->tm_hour // hour
     << ":" << tm->tm_min // minute
     << ":" << tm->tm_sec; // second

But it's not correct. Can someone give me an example with a method that takes a time value given from the keyboard and splits it?

What are the types of data times formats that c++ can accept?


If you looking to take the time from a user-input (which is what it seems like you're wanting), and convert that into a valid struct tm, you can use strptime() found in time.h.

So for instance, if you had:

char user_input_time[] = "25 May 2011 10:15:45";

struct tm;
strptime(user_input_time, "%d %b %Y %H:%M:%S", &tm);

printf("year: %d; month: %d; day: %d;\n", tm.tm_year, tm.tm_mon, tm.tm_mday);


time_t is an integer number and counts the number of seconds elapsed since the UNIX epoch: 1st Jan 1970, 00:00:00. You definitively cannot write what you did to assign this value.

You have to use the functions localtime or gmtime to convert between a convenient time_t value and a struct tm that have the various info of day, month, hour, etc.

You can also use the strftime and strptime functions to convert between a character string and struct tm.


#include <cstdio>
#include <iostream>
#include <string>
...
{
  std::string date_time;
  std::getline(std::cin, date_time);
  sscanf(date_time.c_str(), "%d/%d/%d/%d:%d:%d", &month, &date, &year, &hour, &minute, &second);
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜