如何在c++中分割日期/时间
how to split date/time in c++?
我想将日期/时间字符串(例如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以来经过的秒数。您绝对不能写您为分配该值所做的操作。
您必须使用函数localtime
或gmtime
在方便的time_t
值和具有天、月、小时等各种信息的struct tm
之间进行转换。
也可以使用strftime
和strptime
函数在字符串和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);
}
相关文章:
- 使用 C++将时间戳转换为格式化的日期时间
- C++代码的 C# 日期时间等效项是什么?
- 如何在提升日期时间中创建日期范围?
- 在 c++ 中将 ISO 日期时间转换为本地日期时间并提取时间
- Rcpp/C++/R:比较日期时间矢量与日期时间时出错(错误:"运算符>"的不明确重载)
- 如何将毫秒的日期时间字符串转换为 UNIX 时间戳
- 扩展中的日期时间对象方法C++问题
- 将DateTime字符串分为C 的日期时间
- C++以微秒为单位解析日期/时间
- 仅将纪元字符串保存到 mysql 日期时间年/月/日,但没有小时分钟秒
- 使用提升解析日期时间字符串:采用个位数小时格式
- C++ Poco SQL 查询不返回具有'between'和'and'日期时间绑定的结果
- 快速将带有时区的日期时间字符串转换为 UNIX 时间戳(C++)
- 从C 的时间戳提取日期时间戳
- 标准::get_time 中的日期时间格式
- 生成包含分数和时区的完整 iso 日期时间表示字符串
- 通过 ODBC C++将带有日期时间的记录插入 SQL Server 2014 的问题
- 在 C++20 中获取当前日期/时间是否线程安全?
- mongocxx:插入日期时间
- Poco 日期时间格式化程序 - 使用当前时区打印时间戳