Linux c 獲取和設置本地時間的方法

time 函數說明請自己在終端 man time.

直接上代碼

適合跟我一樣的菜鳥

#include <stdio.h>
#include <stdlib.h>
#include <linux/rtc.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include "app.h"


extern unsigned char recvMAC[6];
extern unsigned char localTime[7];
extern unsigned char localMAC[6];
extern unsigned char fw_version[12];
extern unsigned char sensorlist_version[12];
/*   struct tm
   {
      int tm_sec;   //秒值
      int tm_min;   //分鐘值
      int tm_hour;  //小時值
      int tm_mday;  //本月第幾日
      int tm_mon;   //本年第幾月
      int tm_year;  //tm_year+1900=哪一年
      int tm_wday;  //本週第幾日
      int tm_yday;  //本年第幾日
      int tm_isdst; //日光節約時間
   }
 */  
int getLocalTime(void)
{
	int i;
	unsigned short year;
	//unsigned short yearH;
	//unsigned short yearL;
	struct tm *local;
	time_t t;
	t = time(0);   //獲取日曆時間
	local = localtime(&t);  //將日曆時間轉化爲本地時間,並保存在struct tm結構中
	printf("local time is %d:%d:%d:%d:%d:%d\n",1900+local->tm_year,
										 1+local->tm_mon,
										 local->tm_mday,
										 local->tm_hour,
										 local->tm_min,
										 local->tm_sec);
	year=1900+local->tm_year;
	
	
	localTime[0]=year>>8;
	localTime[1]=year&0x00ff;
	localTime[2]=1+local->tm_mon;
	localTime[3]=local->tm_mday;
	localTime[4]=local->tm_hour;
	localTime[5]= local->tm_min;
	localTime[6]= local->tm_sec;
	for(i=0;i<7;i++)
		printf("0x%02x\n",localTime[i]);
	printf("\n");
	return 0;
}
/************************************************
設置操作系統時間
參數:*dt數據格式爲"2015-9-20 20:30:30"
調用方法:
    char *pt="2015-9-20 20:30:30";
    setLocalTime(dt);
**************************************************/
int setLocalTime(char *dt)
{
    struct rtc_time tm;  
    struct tm _tm;
    struct timeval tv;
    time_t timep;
    sscanf(dt, "%d-%d-%d %d:%d:%d", &tm.tm_year,  
        &tm.tm_mon, &tm.tm_mday,&tm.tm_hour,  
        &tm.tm_min, &tm.tm_sec);  
    _tm.tm_sec = tm.tm_sec;
    _tm.tm_min = tm.tm_min;
    _tm.tm_hour = tm.tm_hour;
    _tm.tm_mday = tm.tm_mday;
    _tm.tm_mon = tm.tm_mon - 1;
    _tm.tm_year = tm.tm_year - 1900;

    timep = mktime(&_tm);
    tv.tv_sec = timep;
    tv.tv_usec = 0;
    if(settimeofday (&tv, (struct timezone *) 0) < 0)
    {
    	printf("Set system datatime error!/n");
    	return -1;
    }
    return 0;

}
希望對你有幫助

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章