//需要超级用户权限才能设置linux系统时间
/*
<div style="font-family: 微软雅黑; font-size: 14px; line-height: 21px;">1、date -s "2014-06-11 16:13:00" 修改系统时间</div><div style="font-family: 微软雅黑; font-size: 14px; line-height: 21px;">2、hwclock -w 系统时间写入硬件时间</div><div style="font-family: 微软雅黑; font-size: 14px; line-height: 21px;"> hwclock -s 硬件时间写入系统时间</div>
*/
#include<stdio.h>
#include<unistd.h>
#include<time.h>
#include<sys/time.h>
/************************************
* 函数功能:设置系统时间
* 参数类型:y_m_d=设置年月日,格式:"2013-8-6",NULL表示不设置
h_m_s=设置时分秒,格式:"12-30-40"
* 返回类型:成功返回0,失败返回-1
************************************/
int set_sys_time(char *y_m_d, char *h_m_s)
{
if(y_m_d==NULL && h_m_s==NULL)
{
return -1;
}
struct timeval tv;
struct timezone tz;
time_t timep;
struct tm *lt;
int year = 0;
int mon = 0;
int mday = 0;
int hour = 0;
int min = 0;
int sec = 0;
time(&timep);
lt = localtime(&timep);/*获取当前系统时间,存放在结构体中*/
printf("lt===%p\n", lt);
if(y_m_d!=NULL) /*设置年月日*/
{
if(sscanf(y_m_d, "%d-%d-%d", &year, &mon, &mday)==3)
{
//printf("year=%d\n", year);
lt->tm_year = year-1900;
lt->tm_mon = mon-1;
lt->tm_mday = mday;
}
else
{
printf("year_mon_day format is error\n");
return -1;
}
}
if(h_m_s!=NULL) /*设置时分秒*/
{
if(sscanf(h_m_s, "%d-%d-%d", &hour, &min, &sec)==3)
{
lt->tm_hour = hour;
lt->tm_min = min;
lt->tm_sec = sec;
}
else
{
printf("hour_min_sec format is error\n");
return -1;
}
}
gettimeofday(&tv, &tz);/*得到相关的属性,才能够去设置,否则设置会失败*/
tv.tv_sec = mktime(lt);/*将结构体转换为秒数*/
return settimeofday(&tv, &tz);
}