简体   繁体   English

解析yyyy-MM-dd HH:mm:ss日期时间字符串?

[英]Parsing yyyy-MM-dd HH:mm:ss date time string?

I have a date time that comes from mysql. 我有一个来自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? 有没有比通过stringstream为每个组件运行它更简单的方法? (no boost or c++11 solutions please). (请不要使用boost或c ++ 11解决方案)。

Thanks 谢谢

sscanf() is probably the most straightforward option. sscanf()可能是最直接的选择。 It is a C library function, so purists might disapprove it. 它是一个C库函数,所以纯粹主义者可能不赞成它。

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. 另一个不错的解决方案也是使用C ++ 11正则表达式 ,这将使字符串更健壮的解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在C ++中将日期格式Www Mmm dd hh:mm:ss yyyy转换为dd hh:mm:ss字符串 - convert date format Www Mmm dd hh:mm:ss yyyy to dd hh:mm:ss string in c++ 将当前时间作为YYYY-MM-DD-HH-MM-SS字符串 - Getting the current time as a YYYY-MM-DD-HH-MM-SS string 如何将CFAbsoluteTime转换为YYYY-MM-DD HH:MM:SS格式? - How do I convert CFAbsoluteTime to YYYY-MM-DD HH:MM:SS format? 格式化时间 c++ dd/mm/yyyy hh:ss - Formatting time c++ dd/mm/yyyy hh:ss 使用 std::chrono::from_stream() 解析时间格式“DD/MM/YYYY at hh:mm:ss”和其他格式 - Parse time format "DD/MM/YYYY at hh:mm:ss" & others using std::chrono::from_stream() 测试字符串是否代表“yyyy-mm-dd” - Test if string represents “yyyy-mm-dd” 如何将YYYY / MM / DD HH:MM:SS转换为std :: chrono :: system_clock :: time_point? - How do I convert YYYY/MM/DD HH:MM:SS to std::chrono::system_clock::time_point? 在 C++ 中将 ddhhmm 转换为 YYYY-MM-DD hh:mm 格式 - Converting ddhhmm to YYYY-MM-DD hh:mm format in C++ C ++字符串DD:HH:MM:SS到整数数据类型 - C++ String DD:HH:MM:SS to integer data types 从用户以“yyyy / mm / dd,hh:mm”的形式输入日期输入并用C ++验证日期? - Taking Date input in the form of “yyyy/mm/dd, hh:mm” from user and validate the date in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM