解析yyyy-MM-dd HH:mm:ss日期时间字符串? [英] Parsing yyyy-MM-dd HH:mm:ss date time string?

查看:746
本文介绍了解析yyyy-MM-dd HH:mm:ss日期时间字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自mysql的日期时间。我需要提取每个部分:

  int year; 
int month;
int day;
int hour;
int min;
int sec;

例如:

 code> 2014-06-10 20:05:57 

运行它通过stringstream为每个组件? (无需boost或c ++ 11解决方案。)



感谢

解决方案<

sscanf() 可能是最直接的选择。



这里是一个例子:

  int year; 
int month;
int day;
int hour;
int min;
int sec;

const char * str =2014-06-10 20:05:57;

if(sscanf(str,%d-%d-%d%d:%d:%d,& year,& month,& day,& hour,& ; min,& sec)== 6)
{
// sscanf()返回扫描的元素数量,因此6表示包含所有6个元素的字符串。
//否则可能是格式错误。
}

这里是一个现场测试



另一个不错的解决方案是使用 C ++ 11 regex ,这将使字符串的解析更加强大。


I have a date time that comes from mysql. I need to extract each part:

int year;
int month;
int day;
int hour;
int min;
int sec;

example:

2014-06-10 20:05:57

Is there a simpler way than running it through stringstream for each component? (no boost or c++11 solutions please).

Thanks

解决方案

sscanf() is probably the most straightforward option. It is a C library function, so purists might disapprove it.

Here is an example:

int year;
int month;
int day;
int hour;
int min;
int sec;

const char * str = "2014-06-10 20:05:57";

if (sscanf(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &min, &sec) == 6)
{
    // sscanf() returns the number of elements scanned, so 6 means the string had all 6 elements.
    // Else it was probably malformed.
}

And here is a live test.

Another nice solution would also be to use a C++11 regex which would make for a more robust parsing of the string.

这篇关于解析yyyy-MM-dd HH:mm:ss日期时间字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆