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

how to split date/time in c++?

本文关键字:日期 时间 分割 c++      更新时间:2023-10-16

我想将日期/时间字符串(例如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++可以接受哪些类型的数据时代格式?

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

例如,如果你有:

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是一个整数,用于统计自UNIX epoch:1970年1月1日00:00:00以来经过的秒数。您绝对不能写您为分配该值所做的操作。

您必须使用函数localtimegmtime在方便的time_t值和具有天、月、小时等各种信息的struct tm之间进行转换。

也可以使用strftimestrptime函数在字符串和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);
}