我希望获得这些值,以便提前10分钟制作一个日期时间。然后以这种格式返回新的日期时间:yyyy / mm / dd / HH / MM
int yyyy = 2010;
int month = 11;
int day = 18;
int hour = 12;
int minute = 10;
Datetime?
答案 0 :(得分:6)
查看Boost :: Date_Time。
http://www.boost.org/doc/libs/1_44_0/doc/html/date_time.html
编辑:以下是http://www.boost.org/doc/libs/1_36_0/doc/html/date_time/examples.html的示例。
/* Some simple examples of constructing and calculating with times
* Output:
* 2002-Feb-01 00:00:00 - 2002-Feb-01 05:04:02.001000000 = -5:04:02.001000000
*/
#include "boost/date_time/posix_time/posix_time.hpp"
#include <iostream>
int
main()
{
using namespace boost::posix_time;
using namespace boost::gregorian;
date d(2002,Feb,1); //an arbitrary date
//construct a time by adding up some durations durations
ptime t1(d, hours(5)+minutes(4)+seconds(2)+millisec(1));
//construct a new time by subtracting some times
ptime t2 = t1 - hours(5)- minutes(4)- seconds(2)- millisec(1);
//construct a duration by taking the difference between times
time_duration td = t2 - t1;
std::cout << to_simple_string(t2) << " - "
<< to_simple_string(t1) << " = "
<< to_simple_string(td) << std::endl;
return 0;
}
答案 1 :(得分:2)
#include <boost/date_time.hpp>
#include <iostream>
#include <sstream>
#include <locale>
int main(int argc, char* argv[])
{
int yyyy = 2010;
int month = 11;
int day = 18;
int hour = 12;
int minute = 10;
boost::gregorian::date date(yyyy, month, day);
boost::posix_time::ptime time(date,
boost::posix_time::hours(hour) +
boost::posix_time::minutes(minute)
);
boost::posix_time::time_facet* facet = new boost::posix_time::time_facet();
facet->format("%Y/%m/%d/%H/%M");
std::ostringstream oss;
oss.imbue(std::locale(oss.getloc(), facet));
oss << time;
std::cout << oss.str() << std::endl;
}
答案 2 :(得分:1)
以下是可能有用的代码段。查看MSDN以获取有关所用函数的更多详细信息。不要忘记用零填充结构。
struct tm now;
memset(&now, 0, sizeof(struct tm));
now.tm_year = 2010 - 1900; // years start from 1900
now.tm_mon = 11 - 1; // Months start from 0
now.tm_mday = 18;
now.tm_hour = 12;
now.tm_min = 10; // you have day here, but I guess it's minutes
time_t afterTime = mktime(&now) + 10 * 60; // time_t is time in seconds
struct tm *after = localtime(&afterTime);
编辑:我犹豫是否写了将日期时间写入字符串的函数,因为它是C而不是C ++,但有时人们只需要一个解决方案而不介意它来自哪个库。所以:
char output[17]; // 4+1+2+1+2+1+2+1+2 format +1 zero terminator
if (strftime(output, sizeof(output), "%Y/%m/%d/%H/%M", after) == 0)
handle_error();