zoukankan      html  css  js  c++  java
  • c++ 日期时间工具

    简易的日期时间工具:

    #include <iostream>
    #include <sstream>
    #include <time.h>
    #include<chrono>
    #include<iomanip>
    #include<glog/logging.h>
    
    namespace DateTimeUtils {
        //获取当前时间日期
        inline std::string GetCurrentDateTimeStr(const char* format = "%Y-%m-%d %H-%M-%S")
        {
            auto now = std::time(nullptr);
            struct tm tm = { 0 };
            localtime_s(&tm, &now);
            std::ostringstream oss;
            oss << std::put_time(&tm, format);
            return  oss.str();
        }
        //格式化时间戳到utc日期时间字符串
        inline std::string FormatDateTimeUTC(const time_t& time, const char* format = "%Y-%m-%d %H-%M-%S") {
            struct tm tm = { 0 };
            //检查入参是否合法
            localtime_s(&tm, &time);
            if (mktime(&tm) != time) {
                DLOG(ERROR) << "FormatDateTimeUTC Error invalidate input time:" << time;
                return "";
            }
            gmtime_s(&tm, &time);
            std::ostringstream oss;
            oss << std::put_time(&tm, format);
            return oss.str();
        }
        //格式化时间戳到本地日期时间字符串
        inline std::string FormatDateTimeLocal(const time_t& time, const char* format = "%Y-%m-%d %H-%M-%S") {
            struct tm tm = { 0 };
            localtime_s(&tm, &time);
            if (mktime(&tm) != time) {
                DLOG(ERROR) << "FormatDateTimeLocal Error invalidate input time:" << time;
                return "";
            }
            std::ostringstream oss;
            oss << std::put_time(&tm, format);
            return oss.str();
        }
        //根据日期字符串获得时间戳(秒)
        inline time_t GetTimeStampByDate(const char* date, const char* format = "%Y-%m-%d %H-%M-%S") {
            struct std::tm tm = { 0 };
            std::istringstream ss(date);
            ss >> std::get_time(&tm, format);
            if (ss.fail()) {
                DLOG(ERROR) << "Error GetTimeStamp date:  " << date << " format:" << format;
                return 0;
            }
            return mktime(&tm);
        }
    
        //获取毫秒时间戳
        inline time_t GetTimeStamp()
        {
            auto now = std::chrono::system_clock::now();
            return std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch()).count();
        }
    
    }
  • 相关阅读:
    Linq聚合操作之Aggregate,Count,Sum,Distinct源码分析
    Linq分区操作之Skip,SkipWhile,Take,TakeWhile源码分析
    Linq生成操作之DefautIfEmpty,Empty,Range,Repeat源码分析
    Linq基础操作之Select,Where,OrderBy,ThenBy源码分析
    PAT 1152 Google Recruitment
    PAT 1092 To Buy or Not to Buy
    PAT 1081 Rational Sum
    PAT 1084 Broken Keyboard
    PAT 1077 Kuchiguse
    PAT 1073 Scientific Notation
  • 原文地址:https://www.cnblogs.com/wolbo/p/14171762.html
Copyright © 2011-2022 走看看