Standard conformant way of converting std::time_t to System::DateTime?

前端 未结 2 1881
感情败类
感情败类 2020-12-10 08:45

I have already found several answers related to converting a std::time_t value to System::DateTime and back. However, almost all answers seem to ne

2条回答
  •  暖寄归人
    2020-12-10 08:52

    It just isn't very productive to insist on a "standard conformant" way to make this conversion. The only place where an std::time_t and a System::DateTime are ever going to meet is covered by the Ecma-372 standard. Of which there is right now, and surely will ever be, only one implementation. The Mono project could be assumed to be the most likely source of another one, but right now they appear entirely uninterested in providing a mixed-mode implementation, the only reason you'd ever consider using C++/CLI.

    std::time_t is steadily marching towards the Y2K38 disaster. With Microsoft pre-emptively having done something about it, and really having to do so because they went for LLP64, but everybody else counting on their LP64 data model keeping them out of trouble. In other words, no remaining 32-bit processors still running in 2038. This could well be a self-fulfilling prophesy.

    Regardless, the conversion is going to have to work with elapsed seconds since 1/1/1970. And that can be a 32-bit or a 64-bit integral value, depending on implementation. The only warranty I can give is that this code is at least good until 2038:

    #include 
    
    using namespace System;
    
    public ref class Conversions {
    public:
        static DateTime time_t2DateTime(std::time_t date) {
            double sec = static_cast(date);
            return DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind::Utc).AddSeconds(sec);
        }
        static std::time_t DateTime2time_t(DateTime date) {
            TimeSpan diff = date.ToUniversalTime() - DateTime(1970, 1, 1);
            return static_cast(diff.TotalSeconds);
        }
    };
    

提交回复
热议问题