作为字符串的当前日期和时间 [英] Current date and time as string

查看:104
本文介绍了作为字符串的当前日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了一个函数来获取当前日期和时间,格式为: DD-MM-YYYY HH:MM:SS 。它的工作,但让我们说,它漂亮的丑陋。

I wrote a function to get a current date and time in format: DD-MM-YYYY HH:MM:SS. It works but let's say, its pretty ugly. How can I do exactly the same thing but simpler?

string currentDateToString()
{
    time_t now = time(0);
    tm *ltm = localtime(&now);

    string dateString = "", tmp = "";
    tmp = numToString(ltm->tm_mday);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += "-";
    tmp = numToString(1 + ltm->tm_mon);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += "-";
    tmp = numToString(1900 + ltm->tm_year);
    dateString += tmp;
    dateString += " ";
    tmp = numToString(ltm->tm_hour);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += ":";
    tmp = numToString(1 + ltm->tm_min);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;
    dateString += ":";
    tmp = numToString(1 + ltm->tm_sec);
    if (tmp.length() == 1)
        tmp.insert(0, "0");
    dateString += tmp;

    return dateString;
}


推荐答案

:使用< ctime> 标头,您可以使用 strftime 。请确保您的缓冲区足够大,您不会想要超过它并稍后造成严重破坏。

Non C++11 solution: With the <ctime> header, you could use strftime. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.

#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;
}

这篇关于作为字符串的当前日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆