将秒数转换成年月日时分秒

来源:互联网 发布:安知玉如意txt书包网 编辑:程序博客网 时间:2024/04/27 21:49

// 仅供学习参考,转载请通知作者!

typedef struct 

uint16_t year;
uint16_t month;
uint16_t date;
uint16_t hour;
uint16_t min;
uint16_t sec;
uint16_t week;
}drive_time,*pdrive_time; 


drive_time UTC;


drive_time struct_time = // 初始化时间
{
.year = 1970,
.month = 1,
.date = 1,
.hour = 0,
.min = 0,
.sec = 0,
.week = 0,
};


// second: 秒数,UTC:结构体

int get_UTC(unsigned long second,pdrive_time UTC)// 获取世界标准时间,转换成北京时间需要加上8小时

{

const char Leap_Year_day[2][12] = { {31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31} };
int Leap_Year = 0;
// 判断是否闰年
int month_day = 0;//
判断当前 月 天数


//------------------
初始化检测----------------------------------------------------------------
if( ((struct_time.year) > 9999) || ((struct_time.year) < 1) )
struct_time.year = 1;
Leap_Year = isLeapYear(struct_time.year);
if( ((struct_time.month) > 12) || ((struct_time.month) < 1) )
struct_time.month = 1;
month_day = Leap_Year_day[Leap_Year][struct_time.month-1];
if( ((struct_time.date) > month_day) || ((struct_time.date) < 1) )
struct_time.date = 1;
if( ((struct_time.week) > 7) || ((struct_time.week) < 1) )
struct_time.week = 1;
if( (struct_time.hour) > 23 )
struct_time.hour = 1;
if( (struct_time.min) > 59 )
struct_time.min = 1;
if( (struct_time.sec) > 59 )
struct_time.sec = 1;


//-----------------
赋值-------------------------------------------------------------------
UTC->year = struct_time.year;
UTC->month = struct_time.month;
UTC->date = struct_time.date;
UTC->hour = struct_time.hour +(second / 3600 % 24);
UTC->min = struct_time.min+(second / 60 % 60);
UTC->sec = struct_time.sec +(second % 60);

//--------------
算出天数----------------------------------------------------------------
uint16_t count_days = second /86400;


if(UTC->sec >=60)
{
UTC->sec = UTC->sec%60;
(UTC->min) ++;
}
if(UTC->min >=60)
{
UTC->min = UTC->min%60;
(UTC->hour) ++;
}
if(UTC->hour >=24)
{
UTC->hour = UTC->hour%24;
(count_days) ++;
// 增加天数
}


//---------------
计算年月日------------------------------------------------
for(int i = 0 ; i < count_days; i++ )
{
Leap_Year = isLeapYear(UTC->year);
month_day = Leap_Year_day[Leap_Year][(UTC->month)-1];


(UTC->date) ++;
if((UTC->date) > month_day)
{
(UTC->date) = 1;
(UTC->month) ++;
if((UTC->month) > 12)
{
(UTC->month) = 1;
(UTC->year) ++;
if( ( (UTC->year) - (struct_time.year) ) >100)//
 设置最大计数100年
return -1;
}
}
}


return 0
 ;

}

0 0