How to create date object in c++?

Member

by sallie , in category: General Help , 2 months ago

How to create date object in c++?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by aliya.yundt , 2 months ago

@sallie 

In C++, you can create a date object by using the built-in "struct tm" and "time_t" types provided in the standard library. Here's an example of how you can create a date object:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <ctime>

int main() {
    // Get the current time
    std::time_t currentTime = std::time(nullptr);

    // Convert the current time to a struct tm
    struct std::tm* currentDate = std::localtime(&currentTime);

    // Access individual components of the date
    int year = currentDate->tm_year + 1900;   // Year since 1900
    int month = currentDate->tm_mon + 1;       // Month (0-11, so add 1)
    int day = currentDate->tm_mday;            // Day of the month

    // Print the current date
    std::cout << "Current date: " << year << "-" << month << "-" << day << std::endl;

    return 0;
}


In the above example, we use the std::time function to get the current time as the number of seconds since the Unix epoch. Then, we pass this value to std::localtime to convert it to a struct tm object representing the current date and time in the local timezone. Finally, we access individual components of the date using the members of struct tm and print them.


Note that struct tm represents dates and times as local time, so if you need to work with dates and times in UTC or other timezones, you may need to use other functions from the <ctime> library or third-party libraries like Boost.Date_Time.