加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何在C中获取当前日期?

发布时间:2020-12-16 10:04:18 所属栏目:百科 来源:网络整理
导读:我一直试图在C中获取当前日期一段时间,我无法弄清楚我做错了什么.我查看了几个站点和我实现的所有解决方案我得到一个错误,上面写着“这个函数或变量可能不安全.请考虑使用localtime_s.“我尝试了几个找到的解决方案 here(包括下面的解决方案),但我无法让它们
我一直试图在C中获取当前日期一段时间,我无法弄清楚我做错了什么.我查看了几个站点和我实现的所有解决方案我得到一个错误,上面写着“这个函数或变量可能不安全.请考虑使用localtime_s.“我尝试了几个找到的解决方案 here(包括下面的解决方案),但我无法让它们中的任何一个工作.我究竟做错了什么?

#include <iostream>
#include <iomanip>
#include <string>
#include <ctime>

using namespace std;

int main()
{

    const int SALARY = 18;
    const int COMMISSION = .08;
    const int BONUS = .03;

    int monthlySales;
    int appointmentNumber;

    time_t t = time(0);   // get time now
    struct tm * now = localtime(&t);

    string name;


//this is where the user adds their name and date
    cout << "Please enter the sales representative's name: ";
    cin >> name;
    cout << "Please enter the number of appointments: ";
    cin >> appointmentNumber;
    cout << "Please enter the amount of sales for the month: $";
    cin >> monthlySales;

//clear screen and execute code
    system("cls");

    cout << setfill(' ');
    cout << "Sales Representative:" << name << endl;
    cout << "Pay Date:" << (now->tm_mon + 1) << " " << now->tm_mday << " " << (now->tm_year + 1900) << endl;
    cout << "Work Count:" << appointmentNumber << "Sale Amount" 
        << monthlySales << endl;

        system("pause");

    return 0;
}

解决方法

您可以尝试下面的代码和说明.

#include <iostream>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,80,"%d-%m-%Y %I:%M:%S",timeinfo);
  std::string str(buffer);

  std::cout << str;

  return 0;
}

功能

time_t time(time_t * timer);

函数返回此值,如果参数不是空指针,它还将此值设置为timer指向的对象.

参数

>计时器
指向time_t类型的对象的指针,其中存储了时间值.如果不需要,您也可以传递空指针

回报价值

当前日历时间作为time_t对象.如果函数无法检索日历时间,则返回值-1.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读