【问题标题】:How to compare user date with system date in c++? [duplicate]如何在 C++ 中比较用户日期和系统日期? [复制]
【发布时间】:2015-01-22 18:28:41
【问题描述】:

我以 DD/MM/YEAR 格式从用户那里获取日期,但我想将其与系统日期进行比较,并想知道用户输入的日期是将来还是过去!

#include <iostream>
#include <ctime>

int main ()
{      
    char date [10],sysdate[10];
    cout<<"enter Date";           
    cin>>date;                   //for taking date from user
    _strdate(sysdate);      //for getting system date(given in DD/MM/YY    
    cout<< sysdate;        //prints system date    
}

【问题讨论】:

  • 如果你在写 C++,那不是 C。
  • C++ chrono 工具似乎没有为处理年、月和日提供任何支持。您可以使用 C mktime() 函数。
  • 它通常是特定于操作系统的。在 POSIX 系统上考虑 strptime & strftime 等......

标签: c++ date


【解决方案1】:

如果您正在严格处理日期字符串(而不是 datetime_ttimestamps 或 datetmstructures),那么您可以直接比较 "YY/MM/DD" 格式的日期字符串来确定一个在另一个之前还是之后.

您使用的格式 ("DD/MM/YY") 不允许这种直接的字符串比较。

【讨论】:

  • 但是 'sydate' 以 DD/MM/YY 格式给出系统日期,那么我该如何更改呢?
  • 您可以重新排列sysdate 值中的数字以创建一个新字符串,并使用该字符串进行比较。
  • 即使在 YY/DD/MM 中重新排列后,我如何比较它?
  • 使用std::strcmp() 或类似的东西。
【解决方案2】:

观看此示例,那么它不会很难 比较用户日期和系统日期

#include <iostream>
#include <ctime>

using namespace std;

int main( )
{
   // current date/time based on current system
   time_t now = time(0);


   tm *ltm = localtime(&now);

   // print various components of tm structure.
   cout << "Year: "<< 1900 + ltm->tm_year << endl;
   cout << "Month: "<< 1 + ltm->tm_mon<< endl;
   cout << "Day: "<<  ltm->tm_mday << endl;

  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-08
    • 2013-09-21
    相关资源
    最近更新 更多