Time difference in C++ // not dependent on local time, system time // neutral // UTC 0

Markus Freitag 3,791 Reputation points
2024-01-08T18:05:11.7+00:00

Hello,

I get a time from a database. I have to compare this with my time. Is smaller than 30 seconds -> Error message, is greather than all fine:-) Output the difference in seconds. How can I best implement this?

string strHour = "19";
string strMinute = "05";
string strSecond = "44";
string strYear = "2024";
string strMonth = "01";
string strDay = "8";

What is the best?

 time_t currentTime;
 struct tm *localTime;

 time( &currentTime );                   // Get the current time
 localTime = localtime( &currentTime );  // Convert the current time to the local time

 int Hour   = localTime->tm_hour;
 int Min    = localTime->tm_min;
 int Sec    = localTime->tm_sec;
//*******      OR
// To get the time expressed as UTC   GetSystemTime  ?
SYSTEMTIME st;
GetSystemTime(&st);

C++, what do I need to know about the UTC time. What formatting?

Developer technologies | C++
Developer technologies | C++
A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.
0 comments No comments
{count} votes

Answer accepted by question author
  1. Minxin Yu 13,506 Reputation points Microsoft External Staff
    2024-01-11T09:24:29.9666667+00:00

    Hi, @Markus Freitag Refer to the document: Local Time To convert a local time to a UTC-based time, use the TzSpecificLocalTimeToSystemTime function.

    //convert loacl tm to UTC 
    
    	SYSTEMTIME UtcTm;
    
    	tm temptm;
    
    	localtime_s(&temptm, &currentTm);
    
    	SYSTEMTIME localTm = { 1900 + temptm.tm_year,
    
    		1 + temptm.tm_mon,
    		temptm.tm_wday,
    		temptm.tm_mday,
    		temptm.tm_hour,
    		temptm.tm_min,
    		temptm.tm_sec,
    		0 };
    
    
    	TzSpecificLocalTimeToSystemTime(&tmInfo, &localTm, &UtcTm);
    	struct tm tempUTC = { UtcTm.wSecond, UtcTm.wMinute, UtcTm.wHour, UtcTm.wDay, UtcTm.wMonth - 1, UtcTm.wYear - 1900, UtcTm.wDayOfWeek, 0, 0 };
    	time_t utctm_t = mktime(&tempUTC);
    
    	// Calculate the time difference in seconds
    	auto difference = std::difftime(utctm_t, std::mktime(&dbTime));
    

    Console sample:

    
    #include <iostream>
    #include <chrono>
    #include <ctime>
    #include<string>
    #include<Windows.h>
    
    int main() {
    
    	// Database time
    
    	TIME_ZONE_INFORMATION tmInfo;
    	GetTimeZoneInformation(&tmInfo);
    
    	std::tm dbTime = {};
    
    	dbTime.tm_year = std::stoi("2024") - 1900;
    	dbTime.tm_mon = std::stoi("01") - 1;
    	dbTime.tm_mday = std::stoi("11");
    	dbTime.tm_hour = std::stoi("9");
    	dbTime.tm_min = std::stoi("03");
    	dbTime.tm_sec = std::stoi("00");
    
    
    	// Current time
    
    	auto currentTime = std::chrono::system_clock::now();
    	auto currentTm = std::chrono::system_clock::to_time_t(currentTime);
    
    
    
    	//convert loacl tm to UTC 
    
    	SYSTEMTIME UtcTm;
    
    	tm temptm;
    
    	localtime_s(&temptm, &currentTm);
    
    	SYSTEMTIME localTm = { 1900 + temptm.tm_year,
    
    		1 + temptm.tm_mon,
    		temptm.tm_wday,
    		temptm.tm_mday,
    		temptm.tm_hour,
    		temptm.tm_min,
    		temptm.tm_sec,
    		0 };
    
    
    	TzSpecificLocalTimeToSystemTime(&tmInfo, &localTm, &UtcTm);
    	struct tm tempUTC = { UtcTm.wSecond, UtcTm.wMinute, UtcTm.wHour, UtcTm.wDay, UtcTm.wMonth - 1, UtcTm.wYear - 1900, UtcTm.wDayOfWeek, 0, 0 };
    	time_t utctm_t = mktime(&tempUTC);
    
    	// Calculate the time difference in seconds
    	auto difference = std::difftime(utctm_t, std::mktime(&dbTime));
    
    
    	// Check if the difference is greater than 30 seconds
    	if (difference > 30.0) {
    		std::cout << "All fine. Time difference: " << difference << " seconds.\n";
    	}
    
    	else {
    		std::cout << "Error message. Time difference: " << difference << " seconds.\n";
    	}
    	return 0;
    }
    

    Best regards,

    Minxin Yu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


1 additional answer

Sort by: Most helpful
  1. Azar 31,610 Reputation points MVP Volunteer Moderator
    2024-01-08T18:37:07.53+00:00

    Hi
    Markus Freitag,

    I think you can use chrono to compare the time obtained from the database with the current time in C++, you can use the <chrono> library for a more modern approach and avoid dealing directly with time_t and struct tm. Here's an example using C++11 or later:

    #include <iostream>
    #include <chrono>
    #include <ctime>
    
    int main() {
        // Database time
        std::tm dbTime = {};
        dbTime.tm_year = std::stoi("2024") - 1900;
        dbTime.tm_mon = std::stoi("01") - 1;
        dbTime.tm_mday = std::stoi("8");
        dbTime.tm_hour = std::stoi("19");
        dbTime.tm_min = std::stoi("05");
        dbTime.tm_sec = std::stoi("44");
    
        // Current time
        auto currentTime = std::chrono::system_clock::now();
        auto currentTm = std::chrono::system_clock::to_time_t(currentTime);
    
        // Calculate the time difference in seconds
        auto difference = std::difftime(currentTm, std::mktime(&dbTime));
    
        // Check if the difference is greater than 30 seconds
        if (difference > 30.0) {
            std::cout << "All fine. Time difference: " << difference << " seconds.\n";
        } else {
            std::cout << "Error message. Time difference: " << difference << " seconds.\n";
        }
    
        return 0;
    }
    
    
    

    If this helps kindly accept the answer thanks much.


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.