time_t rawtime;
	struct tm * timeinfo;
	char sec [80];
	char min [80];
	char hour [80];
	char year[80];
	char month[80];
	char day[80];
	time ( &rawtime );
	timeinfo = localtime ( &rawtime );
	string timetest;
	timetest= strftime (sec,80,"%S",timeinfo);
	timetest= strftime (min,80,"%M",timeinfo);
	timetest= strftime (hour,80,"%H",timeinfo);
	timetest= strftime (year,80,"%Y",timeinfo);
	timetest= strftime (month,80,"%m",timeinfo);
	timetest= strftime (day,80,"%d",timeinfo);

is there away to put it into a func or class or is there a better way to get the date and time?

Dani AI

Generated

As pointed out, the time retrieval can and should be wrapped in a function or class. For returning individual pieces like seconds, year, etc., return a small value object (struct/class) or provide getters instead of trying to convert C-style char buffers. That keeps the interface simple and avoids parsing strings.

Example (compact, portable, returns integers):

struct DateTime {
    int year, month, day, hour, minute, second;
};

inline DateTime current_local_time() {
    std::time_t t = std::time(nullptr);
    std::tm tm;
#if defined(_WIN32)
    localtime_s(&tm, &t);
#else
    localtime_r(&t, &tm);
#endif
    return DateTime{ tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday,
                     tm.tm_hour, tm.tm_min, tm.tm_sec };
}

Access components with DateTime dt = current_local_time(); int Seconds = dt.second;.

Notes and troubleshooting:

  • Use the thread-safe variants (localtime_r on POSIX, localtime_s on Windows) rather than the global localtime to avoid races in multithreaded programs. See the cppreference page on localtime for details: localtime documentation.
  • For formatted output instead of separate integers, prefer std::put_time with a std::tm (see put_time). For higher-resolution timing, use std::chrono::system_clock and related facilities: system_clock.
  • Returning a small struct by value is efficient and avoids lifetime issues with pointers to internal buffers.

Recommended Answers

All 3 Replies

Yes. The same way you put anything into a function.

Yes. The same way you put anything into a function.

but i dont know how to get the seconds,year etc out side the function
i tried to convert the char to int then return it back but i still cant figure out how for e.g to set the value of sec to a new variable called Seconds ....

anyclue??

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.