【发布时间】:2019-11-01 01:57:07
【问题描述】:
我可以使用 C++ 的 strftime 来做 Java 的 Simpledateformat。我的格式输入与 SimpleDateFormat 的语法相同,但我认为我应该使用 strftime,因为这是我能找到的唯一可以格式化日期时间的库。
tz_offset 是我计算时区的函数
long tz_offset(time_t when)
{
if (when == NULL_TIME)
when = std::time(nullptr);
auto const tm = *std::localtime(&when);
std::ostringstream os;
os << std::put_time(&tm, "%z");
std::string s = os.str();
// s is in ISO 8601 format: "±HHMM"
int h = std::stoi(s.substr(0, 3), nullptr, 10);
int m = std::stoi(s[0] + s.substr(3), nullptr, 10);
return h * 3600 + m * 60;
}
这是我的格式化日期函数
std::string FormatDate(double timestamp, std::string format) {
std::ostringstream os;
tm* curr_tm;
time_t timenum = timestamp / 1000;
char date_string[100];
if (format.empty()) {
int millisecond = timestamp - (long long)((long long)(timestamp / 1000) * 1000);
curr_tm = localtime(&timenum);
strftime(date_string, 50, "%Y-%m-%dT%H:%M:%S.", curr_tm);
os << date_string << std::to_string(millisecond) << "+0" << std::to_string(tz_offset() / 3600) << "00";
//My output : 2019-11-01T08:44:39.152+0700
}
else {
//what I must do here??
}
return os.str();
}
我的主要课程
int main()
{
std::string format = "h 'o''cloch' a, zzzz";
FormatDate(1572492011438, format);
return 0;
}
我所做的是如果格式字符串为空,那么我将直接使用我的默认格式。但是用户输入的格式字符串呢?我想到了字符串替换功能。
08 o'clock AM, Indochina Time
【问题讨论】:
标签: c++14 simpledateformat strftime