歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android C/C++代碼中將時間戳轉換為標准時間

Android C/C++代碼中將時間戳轉換為標准時間

日期:2017/3/1 9:44:15   编辑:Linux編程

在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\n", (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\n", (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\n",t);
free(tmp_time);
return 0;
}

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved