给定时间_t或struct timeval,我如何在那一天获取午夜EST / EDT(本地时区)的TimeVal或Time_T? 与假设本地时区是EST / EDT一样,给定一个时间_teation of maying 2010-11-30 08:00:00 EST / EDT,预期答案是一个达到的时间,对应于2010-11-30 00:00:00/ EDT

尝试1(不正确:由于它不处理DST,并且假定EST / EDT始终为UTC的5小时):

time_t RewindToMidnight ( const time_t temp_time_t_ )
{
  return ( (5*3600) + ((( temp_time_t_ - 5*3600 )/86400 ) * 86400) );
}
.

尝试2(不正确:由于它返回对应于午夜UTC而不是EST / EDT,本地时区)时的句号(何时):

time_t RewindToMidnight ( const time_t temp_time_t_ )
{
   boost::posix_time::ptime temp_ptime_ = boost::posix_time::from_time_t ( temp_time_t_ );
   boost::gregorian::date temp_date_ = temp_ptime_.date();
   boost::posix_time::ptime temp_ptime_midnight_ ( temp_date_,
                                                   boost::posix_time::time_duration ( 0, 0, 0 ) );
   return to_time_t ( temp_ptime_midnight_ );
}

time_t to_time_t ( const boost::posix_time::ptime & temp_ptime_ )
{
   boost::posix_time::ptime temp_epoch_ptime_(boost::gregorian::date(1970,1,1));
   boost::posix_time::time_duration::sec_type temp_sec_type_ = ( temp_ptime_ - temp_epoch_ptime_ ).total_seconds();
   return time_t ( temp_sec_type_ );
}
.

我觉得应该有一个涉及的解决方案 (i)struct tm,mktime或 (ii)Boost :: local_date_time或许?

有帮助吗?

解决方案 3

电流解决方案:

time_t RewindToMidnight ( const time_t & temp_time_t_ )
{
    int temp_yyyymmdd_ = iso_date_from_time_t ( temp_time_t_ );
    return time_t_from_iso_date ( temp_yyyymmdd_ );
}

int iso_date_from_time_t ( const time_t & in_time_t_ ) 
{
     tm temp_this_tm_;

     { // the following to set local dst fields of struct tm ?
         time_t tvsec_ = time(NULL);
         localtime_r ( & tvsec_, & temp_this_tm_ ) ;
     }
     localtime_r ( & in_time_t, & temp_this_tm_ ) ;

     return ( ( ( ( 1900 + temp_this_tm_.tm_year ) * 100 + ( 1 + temp_this_tm_.tm_mon ) ) * 100 ) + temp_this_tm_.tm_mday ) ;
}

time_t time_t_from_iso_date ( const int & temp_yyyymmdd_ ) 
{ 

     boost::gregorian::date d1 ( (int)( temp_yyyymmdd_/10000), 
                                 (int)( ( temp_yyyymmdd_/100) % 100), 
                                 (int)( temp_yyyymmdd_ % 100) );

     std::tm this_tm_ = to_tm ( d1 );
     return ( mktime ( & this_tm_ ) ) ;
}
.

请告知。

其他提示

时间_t是以来的时间以来的时间:自纪元(00:00:00 UTC,1970年1月1日),你只需要摆脱一天的秒。一天中有86400秒(闰秒通常被忽略),因此结果应为86400的倍数。因此:

time_t now = time();
time_t midnight = now / 86400 * 86400
.

time_t local_midnight(time_t x) {
  struct tm t;
  localtime_r(&x, &t);
  t.tm_sec = t.tm_min = t.tm_hour = 0;
  return mktime(&t);
}
.

我使用了localtime_r,因为它必须在您的答案中使用它。

示例:

int main() {
  time_t now = time(0);
  cout << "local: " << asctime(localtime(&now));
  cout << "UTC:   " << asctime(gmtime(&now));
  time_t midnight = local_midnight(now);
  cout << "\n       " << asctime(localtime(&midnight));
  return 0;
}
.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top