简体   繁体   English

C++ 将日、月、年转换为毫秒

[英]C++ convert day, month and year to milliseconds

I need to convert M:D:Y:H:M:S into milliseconds.我需要将 M:D:Y:H:M:S 转换为毫秒。

This is the function for Arduino but can't get the same in c++ for Raspberry Pi 3.这是 Arduino 的 function 但在 Raspberry Pi 3 的 c++ 中无法获得相同的结果。

time_t tmConvert_t(int YYYY, byte MM, byte DD, byte hh, byte mm, byte ss)
{
  tmElements_t tmSet;
  tmSet.Year = YYYY - 1970;
  tmSet.Month = MM;
  tmSet.Day = DD;
  tmSet.Hour = hh;
  tmSet.Minute = mm;
  tmSet.Second = ss;
  return makeTime(tmSet); 
}

Any time I need a date converted to milliseconds I run this line.每当我需要将日期转换为毫秒时,我都会运行此行。

unsigned long midnight = tmConvert_t(currentYear, currentMonth, currentDay, 0,0,0);  // get current start of day time stamp

Thanks谢谢

You could just do what you are doing right now if you know time_t to be an arithmetic type holding the number of seconds passed since the epoch.如果你知道time_t是一个算术类型,保存自纪元以来经过的秒数,你就可以做你现在正在做的事情。 A portable way could be to instead let std::chrono do the calculation for you.一种可移植的方式可能是让std::chrono为您进行计算。

#include <chrono>
#include <ctime>
#include <iostream>

std::chrono::milliseconds::rep
tmConvert_t(int YYYY, int MM, int DD, int hh, int mm, int ss) {
    std::tm t{};             // initialize

    t.tm_year = YYYY - 1900;
    t.tm_mon = MM - 1;
    t.tm_mday = DD;
    t.tm_hour = hh;
    t.tm_min = mm;
    t.tm_sec = ss;
    time_t orig = std::mktime(&t);
    
    // ask for the duration since the epoch
    auto dur = std::chrono::system_clock::from_time_t(orig).time_since_epoch();

    // cast to whole milliseconds
    auto dur_in_ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur);

    // return the tick count in milliseconds
    return dur_in_ms.count();
}

int main() {
    std::cout << tmConvert_t(1970,01,01,0,0,0) << '\n'; // possible epoch
    std::cout << tmConvert_t(2021,02,15,0,0,0) << '\n'; // Today
}

Demo演示

This is the same as above but works with only c++.这与上述相同,但仅适用于 c++。

unsigned long long tmConvert_t(short YY, short MM, short DD, short hh, short mm, short ss)
{
    std::tm example;
    example.tm_sec = ss;
    example.tm_min = mm;
    example.tm_hour = hh;
    example.tm_year = YY - 1900;
    example.tm_mon = MM;
    example.tm_mday = DD;
    unsigned long long milli = std::mktime(&example);
    milli = milli * 1000;
    return milli; 
}

Then call this to get milliseconds since epoch.然后调用它以获取自纪元以来的毫秒数。

unsigned long long midnightMillis = tmConvert_t(2021,01,13,0,0,00);

Thanks for all the help.感谢所有的帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM