首页 / 操作系统 / Linux / Android C/C++代码中将时间戳转换为标准时间
在Android 底层C/C++代码中如何将时间戳转换为标准时间?这个问题实质上可以理解为C/C++中如何将Linux的时间戳转换为标准时间,那么接下来就这个问题进行分析和处理。首先,要在C/C++代码中要获取Linux系统的系统时间。在Android的Java层中可以直接导入时间工具包import java.util.Date; 然后new Date()出来一个时间对象。同样在C/C++中也有现成的时间函数供使用,我们可以使用bionoc/libc库中与time相关的方法来实现。步骤如下:在需要获取系统时间的C/C++文件中#include <libc/include/time.h>具体转换方法可参考:时间戳转换为标准时间int timeFormat(void)
{
time_t tick;
struct tm tm;
char s[100];//格式化后的时间,2014-02-26 19:45:50 tick = time(NULL);
tm = *localtime(&tick);
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", &tm);
printf("%d: %s
", (int)tick, s); return 0;
}------------------------补充:1. 时间戳转格式化日期,比如:1384936600 → 2013-11-20 08:36:40 输入一个long,输出一个nsstring具体实现如下://时间戳转格式化#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[])
{
time_t t;
struct tm *p;
t=1384936600;
p=gmtime(&t);
char s[100];
strftime(s, sizeof(s), "%Y-%m-%d %H:%M:%S", p);
printf("%d: %s
", (int)t, s);
return 0;
} 2. 反过来,格式化的时间转换时间戳:2013-11-2008:36:40 → 1384936600 输入nsstring,输出一个long
具体实现如下://格式化转时间戳#include <stdio.h>
#include <time.h>
int main(int argc, const char * argv[])
{
struct tm* tmp_time = (struct tm*)malloc(sizeof(struct tm));
strptime("20131120","%Y%m%d",tmp_time);
time_t t = mktime(tmp_time);
printf("%ld
",t);
free(tmp_time);
return 0;
} 更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-05/101938.htm