首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将字符串转换为C++中的日期

将字符串转换为C++中的日期
EN

Stack Overflow用户
提问于 2008-11-21 10:42:00
回答 5查看 75.8K关注 0票数 23

我知道这可能很简单,但作为C++,我对此表示怀疑。如何将格式为01/01/2008的字符串转换为日期,以便对其进行操作?我很高兴将字符串分解为日、月、年的组成部分。如果解决方案是Windows,我也很高兴。

EN

回答 5

Stack Overflow用户

发布于 2008-11-21 10:46:57

代码语言:javascript
复制
#include <time.h>
char *strptime(const char *buf, const char *format, struct tm *tm);
票数 18
EN

Stack Overflow用户

发布于 2008-11-21 14:24:09

我没有使用strptime就解决了这个问题。

将日期分解为其组成部分,即日、月、年,然后:

代码语言:javascript
复制
struct tm  tm;
time_t rawtime;
time ( &rawtime );
tm = *localtime ( &rawtime );
tm.tm_year = year - 1900;
tm.tm_mon = month - 1;
tm.tm_mday = day;
mktime(&tm);

现在可以将tm转换为time_t并对其进行操作。

票数 9
EN

Stack Overflow用户

发布于 2014-11-04 23:45:03

代码语言:javascript
复制
#include <time.h>
#include <iostream>
#include <sstream>
#include <algorithm>

using namespace std;

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  int year, month ,day;
  char str[256];

  cout << "Inter date: " << endl; 
  cin.getline(str,sizeof(str));

  replace( str, str+strlen(str), '/', ' ' );  
  istringstream( str ) >> day >> month >> year;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  timeinfo->tm_year = year - 1900;
  timeinfo->tm_mon = month - 1;
  timeinfo->tm_mday = day;
  mktime ( timeinfo );

  strftime ( str, sizeof(str), "%A", timeinfo );
  cout << str << endl;
  system("pause");
  return 0;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/308390

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档