利用boost獲取時間並格式化

2021-05-27 21:55:09 字數 1695 閱讀 5026

利用boost來獲取當前時間又方便快捷,還不用考慮跨平台的問題。

1. 輸出yyyymmdd

#include #define boost_date_time_source

std::string strtime = boost::gregorian::to_iso_string(\

boost::gregorian::day_clock::local_day());

std::cout << strtime.c_str() << std::endl;

2. 輸出yyyymmdd-hh:mm:ss

#include #define boost_date_time_source

std::string strtime = boost::posix_time::to_iso_string(\

boost::posix_time::second_clock::local_time());

// 這時候strtime裡存放時間的格式是yyyymmddthhmmss,日期和時間用大寫字母t隔開了

int pos = strtime.find('t');

strtime.replace(pos,1,std::string("-"));

strtime.replace(pos + 3,0,std::string(":"));

strtime.replace(pos + 6,0,std::string(":"));

std::cout << strtime.c_str() << std::endl;

3. 計算時間間隔。boost裡計算時間間隔的功能很多很強大,我列舉的僅僅是我目前用到的。

#include #include #define boost_date_time_source

boost::posix_time::ptime time_now,time_now1;

boost::posix_time::millisec_posix_time_system_config::time_duration_type time_elapse;

// 這裡為微秒為單位;這裡可以將microsec_clock替換成second_clock以秒為單位;

time_now = boost::posix_time::microsec_clock::universal_time();

// sleep 100毫秒;

boost::this_thread::sleep(boost::posix_time::millisec(100));

time_now1 = boost::posix_time::microsec_clock::universal_time();

time_elapse = time_now1 - time_now;

// 類似gettickcount,只是這邊得到的是2個時間的ticket值的差,以微秒為單位;

int ticks = time_elapse.ticks();

// 得到兩個時間間隔的秒數;

int sec = time_elapse.total_seconds();

利用boost獲取時間並格式化

利用boost來獲取當前時間又方便快捷,還不用考慮跨平台的問題。1.輸出yyyymmdd cpp view plain copy include define boost date time source std string strtime boost gregorian to iso strin...

JS獲取當前時間並格式化

var mydate new date mydate.getyear 獲取當前年份 2位 mydate.getfullyear 獲取完整的年份 4位,1970 mydate.getmonth 獲取當前月份 0 11,0代表1月 mydate.getdate 獲取當前日 1 31 mydate.get...

時間獲取格式化

var mydate new date mydate.getyear 獲取當前年份 2位 mydate.getfullyear 獲取完整的年份 4位,1970 mydate.getmonth 獲取當前月份 0 11,0代表1月 所以獲取當前月份是mydate.getmonth 1 mydate.ge...