當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ String轉Date用法及代碼示例

在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)




相關用法


注:本文由純淨天空篩選整理自mguru4c05q大神的英文原創作品 How to Convert String to Date in C++?。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。