一般在做数据库方面,大家都会遇到日期型转整形数的需求,在C语言中可以用下面这个函数得到日期所对应的数据型。
/*-------------------------------------------------------------
*功能:字符串转换时间
*参数:strTime 字符串时间 2009-06-25 12:56:00
*返回值 void
-------------------------------------------------------------*/
long long StrToTime(char* strTime)
{
char str[64], left[64];
strcpy(str, strTime);
int y,m,d,h,mm,s;
char *p, *pstart=str;
p = strstr(pstart, "-");
if(p == NULL)
{
return 0;
}
memset(left, 0, 64);
memcpy(left, pstart, p-pstart);
y = atoi(left);
pstart = p+1;
p = strstr(pstart, "-");
if(p == NULL)
{
return 0;
}
memset(left, 0, 64);
memcpy(left, pstart, p-pstart);
m = atoi(left);
pstart = p+1;
p = strstr(pstart, " ");
if(p == NULL)
{
return 0;
}
memset(left, 0, 64);
memcpy(left, pstart, p-pstart);
d = atoi(left);
pstart = p+1;
p = strstr(pstart, ":");
if(p == NULL)
{
return 0;
}
memset(left, 0, 64);
memcpy(left, pstart, p-pstart);
h = atoi(left);
pstart = p+1;
p = strstr(pstart, ":");
if(p == NULL)
{
return 0;
}
memset(left, 0, 64);
memcpy(left, pstart, p-pstart);
mm = atoi(left);
pstart = p+1;
s = atoi(pstart);
time_t tt = 0;
struct tm st_tm;
if(y < 1000)
{
y += 2000;
}
y -= 1900;
m -= 1;
st_tm.tm_year = y;
st_tm.tm_mon = m;
st_tm.tm_mday = d;
st_tm.tm_hour = h;
st_tm.tm_min = mm;
st_tm.tm_sec = s;
st_tm.tm_isdst = 0;
tt = mktime(&st_tm);
return (long long)tt;
}
而mysql中已经做好这样的函数供大家使用,如下::
mysql> select unix_timestamp('1973-11-30 06:02:57');
+---------------------------------------+
| unix_timestamp('1973-11-30 06:02:57') |
+---------------------------------------+
| 123456777 |
+---------------------------------------+
1 row in set (0.00 sec)
mysql> select from_unixtime(123456777);
+--------------------------+
| from_unixtime(123456777) |
+--------------------------+
| 1973-11-30 06:02:57 |
+--------------------------+
1 row in set (0.00 sec)