Thursday, June 16, 2011

Time and Date Functions

9.  <time.h>  Time and Date Functions

The header <time.h> declares types and functions for manipulating date and time. Some functions process local time, which may differ from calendar time, for example because of time zone. clock_t is an arithmetic type representing elapsed processor time, and time_t is an arithmetic type representing calendar time. struct tm holds the components of a calendar time:

<><><><><><><><><><><><><><><><><><>
seconds after the minute (0~61)
int tm_min;
minutes after the hour (0~59)
int tm_hour;
hours since midnight (0~23)
int tm_mday;
day of the month (1~31)
int tm_mon;
months since January (0~11)
int tm_year;
years since 1900 (0~)
int tm_wday;
days since Sunday (0~6)
int tm_yday;
days since January 1 (0~365)
int tm_isdst;
Daylight Saving Time flag

tm_isdst is positive if Daylight Saving Time is in effect, zero if not, and negative if the information is not available.
clock_t clock(void)
clock returns the processor time used by the program since the beginning of execution, or -1 if unavailable. clock()/CLOCKS_PER_SEC is a time in seconds.
time_t time(time_t *tp)
time returns the current calendar time or -1 if the time is not available. If tp is not NULL, the return value is also assigned to *tp.
double difftime(time_t time2, time_t time1)
difftime returns time2-time1 expressed in seconds.
The next four functions return pointers to static objects that may be overwritten by other calls.
struct tm *localtime(const time_t *tp)
localtime converts the calendar time *tp into local time.
struct tm *gmtime(const time_t *tp)
gmtime converts the calendar time *tp into Universal Time Coordinated (UTC; formerly Greenwich Mean Time, GMT). It returns NULL if UTC is not available.
char *asctime(const struct tm *tp)
asctime converts the time in the structure *tp into a time string of the form:
Sun Jan  3 15:14:13 2010\n\0
char *ctime(const time_t *tp)
ctime converts the calendar time *tp to local time and returns the time string; it is equivalent to asctime(localtime(tp)).
time_t mktime(struct tm *tp)
mktime converts the time in the structure *tp into calendar time in the same representation used by time. The components of *tp will have values in the ranges shown above. mktime returns the calendar time or -1 if it cannot be represented.
size_t strftime(char *s, size_t smax, const char *fmt, const struct tm *tp)
strftime formats date and time information from *tp into s according to fmt, which is analogous to a printf format. Ordinary characters (including the terminating '\0') are copied into s. Each %c is replaced as described below, using values appropriate for the local environment. No more than smax characters are placed into s. strftime returns the number of characters, excluding the '\0', or zero if more than smax characters were produced.
%a
abbreviated weekday name; e.g.) Sun.
%A
full weekday name; e.g.) Sunday.
%b
abbreviated month name; e.g.) Dec.
%B
full month name; e.g.) December.
%c
date and time; e.g.) 01/01/99 13:01:01.
%d
day of the month (01~31).
%H
hour (24-hour clock) (00~23).
%I
hour (12-hour clock) (01~12).
%j
day of the year (001~366).
%m
month (01~12).
%M
minute (00~59).
%p
AM/PM indicator; e.g.) AM.
%S
second (00~61).
%U
week number of the year (Sunday as 1st day of week) (00~53).
%w
weekday (0~6, Sunday is 0).
%W
week number of the year (Monday as 1st day of week) (00~53).
%x
date; e.g.) 01/01/99.
%X
time; e.g.) 13:01:01.
%y
year without century (00~99).
%Y
year with century; e.g.) 1999.
%Z
time zone name, if any.
%%
%

EXAMPLE CODES

9.       time.h
l time-1.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <time.h>
void main() {
    time_t t = (time_t)0;
    printf("KST: %s", ctime(&t));
    printf("KST: %s", asctime(localtime(&t)));
    printf("UTC: %s", asctime(gmtime(&t)));
}
>  time-1
KST: Thu Jan 01 09:00:00 1970
KST: Thu Jan 01 09:00:00 1970
UTC: Thu Jan 01 00:00:00 1970
l time-2.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <time.h>
void main() {
    time_t t = time(NULL);
    struct tm *pt = localtime(&t);

    printf("%s", ctime(&t));
    printf("%04d/%02d/%02d %02d:%02d:%02d\n",
            pt->tm_year + 1900, pt->tm_mon + 1, pt->tm_mday,
            pt->tm_hour, pt->tm_min, pt->tm_sec);

    printf("연중 %d일째, 주중 %d일째\n", pt->tm_yday + 1, pt->tm_wday + 1);

    if (pt->tm_isdst > 0) printf("DST: Yes\n");
    else if (pt->tm_isdst < 0) printf("DST: Unknown\n");
    else printf("DST: No\n");
}
>  time-2
Sun Jan 11 10:01:01 1970
1970/01/11 10:01:01
연중 11일째, 주중 1일째
DST: No
l time-3.c
// Strictly speaking, this program is NOT standard conformant!!!
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <time.h>
void main() {
    time_t t1, t2; struct tm tm;

    time(&t1);
    tm = *localtime(&t1);
    tm.tm_hour += 100;
    t2 = mktime(&tm);

    printf("t1: %ld -- %s", (long)t1, ctime(&t1));
    printf("t2: %ld -- %s", (long)t2, ctime(&t2));

    printf("%g %g\n", difftime(t2, t1), difftime(t1, t2));
    printf("%ld %ld\n", (long)t2 - (long)t1, (long)t1 - (long)t2);
}
>  time-3
t1: 1299661 -- Fri Jan 16 10:01:01 1970
t2: 1659661 -- Tue Jan 20 14:01:01 1970
360000 -360000
360000 -360000
l clock.c
#include <stdio.h>
#include <time.h>

void job() {
    int i, j, n = 0;
    printf("Job started.\n");
    for (i = 0; i < 20000; i++)
        for (j = 0; j < 20000; j++)
            n += i * j;
    printf("Job ended.\n");
}

void main() {
    clock_t start, end;
    printf("CLOCKS_PER_SEC = %d\n", CLOCKS_PER_SEC);

    start = clock(); job(); end = clock();
    printf("Job processing time: %gms\n",
            (end - start) / (double)CLOCKS_PER_SEC * 1000);
}
>  clock
CLOCKS_PER_SEC = 1000
Job started.
Job ended.
Job processing time: 1234ms
l locale.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <locale.h> // setlocale, LC_ALL, LC_TIME
#include <time.h>

#define SIZE 100

void main() {
    time_t t = time(NULL);
    struct tm *pt = localtime(&t);
    char s[SIZE];

    printf("%s\n", setlocale(LC_ALL, NULL));
    printf("%s\n", setlocale(LC_TIME, NULL));
    printf("%s", ctime(&t));
    strftime(s, SIZE, "%c", pt); puts(s);
    putchar('\n');
    printf("%s\n", setlocale(LC_TIME, ""));
    printf("%s", ctime(&t));
    strftime(s, SIZE, "%c", pt); puts(s);
    putchar('\n');
    printf("%s\n", setlocale(LC_TIME, "English"));
    printf("%s", ctime(&t));
    strftime(s, SIZE, "%c", pt); puts(s);
}
>  locale
C
C
Thu Jan 01 00:00:00 1970
01/01/70 00:00:00

Korean_Korea.949
Thu Jan 01 00:00:00 1970
1970-01-01 오전 12:00:00

English_United States.1252
Thu Jan 01 00:00:00 1970
1/1/1970 12:00:00 AM
l strftime.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <locale.h>
#include <time.h>

#define SIZE 100
void strftime_test(const struct tm *pt) {
    char s[SIZE];
    strftime(s, SIZE, "weekday name -- %%a, %%A: %a, %A", pt); puts(s);
    strftime(s, SIZE, "month name -- %%b, %%B: %b, %B", pt); puts(s);
    strftime(s, SIZE, "date and time -- %%c: %c", pt); puts(s);
    strftime(s, SIZE, "date -- %%d: %d", pt); puts(s);
    strftime(s, SIZE, "hour -- %%H, %%I %%p: %H, %I %p", pt); puts(s);
    strftime(s, SIZE, "minute and second -- %%M:%%S: %M:%S", pt); puts(s);
    strftime(s, SIZE, "day of the year -- %%j: %j", pt); puts(s);
    strftime(s, SIZE, "month -- %%m: %m", pt); puts(s);
    strftime(s, SIZE, "week number(00~) -- %%U, %%W: %U, %W", pt); puts(s);
    strftime(s, SIZE, "weekday(0~) -- %%w: %w", pt); puts(s);
    strftime(s, SIZE, "date -- %%x: %x", pt); puts(s);
    strftime(s, SIZE, "time -- %%X: %X", pt); puts(s);
    strftime(s, SIZE, "year -- %%y, %%Y: %y, %Y", pt); puts(s);
    strftime(s, SIZE, "time zone -- %%Z: %Z", pt); puts(s);
}

void main() {
    time_t t = time(NULL);
    struct tm *pt = localtime(&t);

    printf("[locale: %s]\n", setlocale(LC_TIME, "C"));
    strftime_test(pt);
    putchar('\n');
    printf("[locale: %s]\n", setlocale(LC_TIME, "Korean"));
    strftime_test(pt);
    putchar('\n');
    printf("[locale: %s]\n", setlocale(LC_TIME, "English"));
    strftime_test(pt);
}
>  strftime
[locale: C]
weekday name -- %a, %A: Sun, Sunday
month name -- %b, %B: Aug, August
date and time -- %c: 08/08/99 20:08:08
date -- %d: 08
hour -- %H, %I %p: 20, 08 PM
minute and second -- %M:%S: 08:08
day of the year -- %j: 220
month -- %m: 08
week number(00~) -- %U, %W: 32, 31
weekday(0~) -- %w: 0
date -- %x: 08/08/99
time -- %X: 20:08:08
year -- %y, %Y: 99, 1999
time zone -- %Z: 대한민국 표준시

[locale: Korean_Korea.949]
weekday name -- %a, %A: , 일요일
month name -- %b, %B: 8, 8
date and time -- %c: 1999-08-08 오후 8:08:08
date -- %d: 08
hour -- %H, %I %p: 20, 08 오후
minute and second -- %M:%S: 08:08
day of the year -- %j: 220
month -- %m: 08
week number(00~) -- %U, %W: 32, 31
weekday(0~) -- %w: 0
date -- %x: 1999-08-08
time -- %X: 오후 8:08:08
year -- %y, %Y: 99, 1999
time zone -- %Z: 대한민국 표준시

[locale: English_United States.1252]
weekday name -- %a, %A: Sun, Sunday
month name -- %b, %B: Aug, August
date and time -- %c: 8/8/1999 8:08:08 PM
date -- %d: 08
hour -- %H, %I %p: 20, 08 PM
minute and second -- %M:%S: 08:08
day of the year -- %j: 220
month -- %m: 08
week number(00~) -- %U, %W: 32, 31
weekday(0~) -- %w: 0
date -- %x: 8/8/1999
time -- %X: 8:08:08 PM
year -- %y, %Y: 99, 1999
time zone -- %Z: 대한민국 표준시
l calendar.c
#define _CRT_SECURE_NO_DEPRECATE
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define USAGE "usage: calendar year month\n"

void main(int argc, char *argv[]) {
    char days[13] = { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    int year, month, wday, mdays, i, j;
    time_t t = time(NULL);
    struct tm tm = *gmtime(&t);

    if (argc != 3)
        fprintf(stderr, "%s", USAGE), exit(1);
    year = atoi(argv[1]); month = atoi(argv[2]);
    if (year < 1970 || year >= 2038)
        fprintf(stderr, "invalid year: %d\n", year), exit(1);
    if (month < 1 || month > 12)
        fprintf(stderr, "invalid month: %d\n", month), exit(1);

    tm.tm_year = year - 1900;
    tm.tm_mon = month - 1;
    tm.tm_mday = 1;
    if (mktime(&tm) == -1)
        fprintf(stderr, "fail to mktime\n"), exit(1);
    wday = tm.tm_wday;

    mdays = days[month];
    if (month == 2 && (year % 4 == 0 && year % 100 != 0 || year % 400 == 0))
        mdays++;

    printf("    [ %d %d ]\n", year, month);
    printf(" \n");
    for (i = 0; i < wday; i++) printf("   ");
    for (j = 1; j <= mdays; j++) {
        printf("%3d", j);
        if (++i % 7 == 0) putchar('\n');
    }
    if (i % 7 != 0) putchar('\n');
}
>  calendar 1999 2
    [ 1999 2 ]
     1  2  3  4  5  6
  7  8  9 10 11 12 13
 14 15 16 17 18 19 20
 21 22 23 24 25 26 27
 28
>  calendar 2000 2
    [ 2000 2 ]
        1  2  3  4  5
  6  7  8  9 10 11 12
 13 14 15 16 17 18 19
 20 21 22 23 24 25 26
 27 28 29

No comments: