3

time_t または struct timeval が与えられた場合、その日の真夜中の EST/EDT (ローカル タイムゾーン) の timeval または time_t を取得するにはどうすればよいですか? ローカル タイムゾーンが EST/EDT であると仮定すると、たとえば 2010-11-30 08:00:00 EST/EDT に対応する time_t が与えられると、予想される答えは 2010-11-30 00:00:00 EST に対応する time_t になります。 /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 (不正解: EST/EDT ではなく UTC の午前 0 時、ローカル タイムゾーンに対応する time_t を返すため):

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 を含む解決策があるはずだと思います。

4

3 に答える 3

5

time_t はエポック (00:00:00 UTC、1970 年 1 月 1 日) からの秒数であるため、その日の秒数を取り除く必要があります。1 日は 86400 秒なので (うるう秒は通常無視されます)、結果は 86400 の倍数になるはずです。

time_t now = time();
time_t midnight = now / 86400 * 86400
于 2011-02-05T23:19:41.050 に答える
4
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;
}
于 2011-02-08T02:35:32.463 に答える
0

現在の解決策:

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_ ) ) ;
}

お知らせ下さい。

于 2011-02-06T15:58:53.093 に答える