timestamp.c 1.6 KB
Newer Older
M
Marc G. Fournier 已提交
1 2 3 4 5 6
#include <stdio.h>
#include <string.h>
#include <time.h>
#include "postgres.h"
#include "utils/builtins.h"

7 8
time_t
timestamp_in(const char *timestamp_str)
M
Marc G. Fournier 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
{
    struct tm input_time;
    int4 result;

    memset(&input_time, 0, sizeof(input_time));
    if(sscanf(timestamp_str, "%d%*c%d%*c%d%*c%d%*c%d%*c%d",
	      &input_time.tm_year, &input_time.tm_mon, &input_time.tm_mday,
	      &input_time.tm_hour, &input_time.tm_min, &input_time.tm_sec) != 6) {
	elog(WARN, "timestamp_in: timestamp \"%s\" not of the form yyyy-mm-dd hh:mm:ss",
	     timestamp_str);
    }

    /* range checking?  bahahahaha.... */

    input_time.tm_year -= 1900;
    input_time.tm_mon -= 1;

    /* use mktime(), but make this GMT, not local time */
    result = mktime(&input_time);

    return result;
}

char *
33
timestamp_out(time_t timestamp)
M
Marc G. Fournier 已提交
34 35 36 37
{
    char *result;
    struct tm *time;

38
    time = localtime((time_t *)&timestamp);
M
Marc G. Fournier 已提交
39 40 41 42 43 44 45 46
    result = palloc(20);
    sprintf(result, "%04d-%02d-%02d %02d:%02d:%02d",
	    time->tm_year+1900, time->tm_mon+1, time->tm_mday,
	    time->tm_hour, time->tm_min, time->tm_sec);

    return result;
}

47
time_t
M
Marc G. Fournier 已提交
48 49 50 51 52
now(void)
{
    time_t sec;

    time(&sec);
53
    return(sec);
M
Marc G. Fournier 已提交
54 55
}

56 57
bool
timestampeq(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
58
{
59
    return difftime(t1, t2) == 0;
M
Marc G. Fournier 已提交
60 61
}

62 63
bool
timestampne(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
64
{
65
    return difftime(t1, t2) != 0;
M
Marc G. Fournier 已提交
66 67
}

68 69
bool
timestamplt(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
70
{
71
    return difftime(t1, t2) > 0;
M
Marc G. Fournier 已提交
72 73
}

74 75
bool
timestampgt(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
76
{
77
    return difftime(t1, t2) < 0;
M
Marc G. Fournier 已提交
78 79
}

80 81
bool
timestample(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
82
{
83
    return difftime(t1, t2) >= 0;
M
Marc G. Fournier 已提交
84 85
}

86 87
bool
timestampge(time_t t1, time_t t2)
M
Marc G. Fournier 已提交
88
{
89
    return difftime(t1, t2) <= 0;
M
Marc G. Fournier 已提交
90
}