给定time_t或struct timeval,如何在当天获得EST / EDT午夜(当地时区)的timeval或time_t? 假设当地时区是EST / EDT,给定time_t对应于美国东部时间/美国东部时间2010-11-30 08:00:00,预期答案是对应于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(错误:因为它返回的time_t对应于午夜时间而不是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?
答案 0 :(得分:5)
由于time_t是自Epoch(1970年1月1日00:00:00 UTC)以来的秒数,您只需要摆脱一天中的秒数。一天有86400秒(通常忽略闰秒),因此结果应该是86400的倍数。因此:
time_t now = time();
time_t midnight = now / 86400 * 86400
答案 1 :(得分: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;
}
答案 2 :(得分: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_ ) ) ;
}
请告知。