Archive for July, 2005
now()
Friday, July 15th, 2005How to get current date/time using C or C++ in Linux? It’s not as easy as in Delphi or VB..
Well, here is a small code to get current date/time in C. I think it’s quite useable in some cases..
#include <time.h>
#include <stdio.h>
#include <string.h>
/**
function name: now1()
used to format current datetime
parameter:
format : format datetime string for the result
n : length of the result +2 (I dunno why it didn’t work if it’s not +2)
result : pointer of char (must have been allocated) to keep the formatted datetime
*/
void now1(const char *format, int n, char *result)
{
struct tm *tm;
time_t now;
time(&now);
tm=localtime((&now));
strftime(result, n, format, tm);
}/**
function name: now2()
used to retrieve current datetime using format: YYYY-MM-DD, hh:mm:ss
return value : pointer of char contains the formatted current datetime
*/
char* now2()
{
static char result[21];
now1("%Y-%m-%d, %H:%M:%S",22,result);
return result;
}int main()
{
char hasil[21];
now1("%Y-%m-%d, %H:%M:%S",22,hasil);
printf("\n%s\n",hasil);printf("\n%s\n",now2());
return 0;
}
If anyone have a better idea to retrieve current time in C/C++ please let me know. ^o^/
By the way, here is some useful format for strftime (to find more detail, type: man strftime ^^’)
- %a The abbreviated weekday name according to the current locale.
- %A The full weekday name according to the current locale.
- %b The abbreviated month name according to the current locale.
- %B The full month name according to the current locale.
- %c The preferred date and time representation for the current locale.
- %C The century number (year/100) as a 2-digit integer.
- %d The day of the month as a decimal number (range 01 to 31).
- %D Equivalent to %m/%d/%y
- %e Like %d, but a leading zero is replaced by a space.
- %F Equivalent to %Y-%m-%d
- %g Like %G, but without century, i.e., with a 2-digit year (00-99).
- %H The hour as a decimal number using a 24-hour clock (range 00 to 23).
- %I The hour as a decimal number using a 12-hour clock (range 01 to 12).
- %j The day of the year as a decimal number (range 001 to 366).
- %k The hour as a decimal number (range 0 to 23); single digits are preceded by a blank.
- %l The hour as a decimal number (range 1 to 12); single digits are preceded by a blank.
- %m The month as a decimal number (range 01 to 12).
- %M The minute as a decimal number (range 00 to 59).
- %n A newline character.
- %p Either ‘AM’ or ‘PM’ according to the given time value.
- %P Like %p but in lowercase
- %u The day of the week as a decimal, range 1 to 7, Monday being 1.
- %U The week number of the current year, range 00 to 53.
- %w The day of the week as a decimal, range 0 to 6, Sunday being 0.
- %W The week number of the current year as a decimal number, range 00 to 53.
- %y The year as a decimal number without a century (range 00 to 99).
- %Y The year as a decimal number including the century.