在C++中,我們一般以std::tm類型的對象的形式存儲日期和時間數據。有時,這些數據存儲在字符串對象內,我們需要將其轉換為 tm 類型以進行進一步處理。在本文中,我們將學習如何在 C++ 中將字符串轉換為日期。
例子:
Input: dateString = "2024-03-14"; Output: Date: Thu Mar 14 00:00:00 2024
在 C++ 中將字符串轉換為日期
要轉換一個標準::字符串到日期在C++中,我們可以使用std::stringstream
類與std::get_time()
中提供的函數<iomanip>
一個解析字符串流的庫,將其內容解釋為日期和時間規範以填充tm
結構。
get_time() 的語法
ss >> get_time(&tm, "%Y-%m-%d");
這裏,
ss
是要轉換為日期的字符串流。"%Y-%m-%d"
是字符串中日期的格式。tm
是個tm
結構來存儲日期。
將字符串轉換為日期的 C++ 程序
下麵的程序演示了如何使用將字符串轉換為日期std::get_time()
C++ 中的函數。
// C++ program to illustrate how to convert string to date
#include <ctime>
#include <iomanip>
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
// Define a string representing a date
string dateString = "2024-03-14";
// Initialize a tm structure to hold the parsed date
tm tm = {};
// Create a string stream to parse the date string
istringstream ss(dateString);
// Parse the date string using std::get_time
ss >> get_time(&tm, "%Y-%m-%d");
// Check if parsing was successful
if (ss.fail()) {
cout << "Date parsing failed!" << endl;
return 1;
}
// Convert the parsed date to a time_t value
time_t date = mktime(&tm);
// Output the parsed date using std::asctime
cout << "Date: " << asctime(localtime(&date));
return 0;
}
輸出
Date: Thu Mar 14 00:00:00 2024
時間複雜度:O(N),這裏N是日期字符串的長度。
輔助空間:複雜度(1)
相關用法
- C++ String轉Integer用法及代碼示例
- C++ String轉int用法及代碼示例
- C++ String轉Integer Vector用法及代碼示例
- C++ String轉size_t用法及代碼示例
- C++ String轉Char Array用法及代碼示例
- C++ String Assign()用法及代碼示例
- C++ String Data()用法及代碼示例
- C++ String Find()用法及代碼示例
- C++ String append()用法及代碼示例
- C++ String at()用法及代碼示例
- C++ String back()用法及代碼示例
- C++ String begin()用法及代碼示例
- C++ String c_str()用法及代碼示例
- C++ String capacity()用法及代碼示例
- C++ String cbegin()用法及代碼示例
- C++ String cend()用法及代碼示例
- C++ String clear()用法及代碼示例
- C++ String compare()用法及代碼示例
- C++ String copy()用法及代碼示例
- C++ String crbegin()用法及代碼示例
- C++ String crend()用法及代碼示例
- C++ String empty()用法及代碼示例
- C++ String end()用法及代碼示例
- C++ String erase()用法及代碼示例
- C++ String find_first_not_of()用法及代碼示例
注:本文由純淨天空篩選整理自mguru4c05q大神的英文原創作品 How to Convert String to Date in C++?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。