如何在c ++中分割日期/时间?

时间:2011-05-25 14:53:07

标签: c++ datetime

我想将日期/时间字符串(例如1/08/1957/11:20:01或任何类型的时间格式)吐出到月,小时,秒,分钟。问题是,首先我不知道如何定义可以拆分的时间类型。

我应该写:

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

但这不正确。有人可以给我一个示例,其中一个方法需要从键盘获取时间值并将其拆分吗?

c ++可以接受的数据时代格式有哪些?

3 个答案:

答案 0 :(得分:3)

如果您希望从用户输入中获取时间(这似乎是您想要的),并将其转换为有效的struct tm,则可以使用strptime() time.h

例如,如果你有:

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);

答案 1 :(得分:1)

time_t是一个整数,它计算自UNIX纪元以来经过的秒数:1970年1月1日,00:00:00。你明确地无法写下你为分配这个值所做的事情。

您必须使用localtimegmtime函数在方便的time_t值和struct tm之间进行转换,这些值包含日,月,小时的各种信息,等

您还可以使用strftimestrptime函数在字符串和struct tm之间进行转换。

答案 2 :(得分:0)

#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);
}
相关问题