以下的两个函数是实现年月日时分秒到秒数的相互转换。实际应用中发现问题,这种解bug的感觉不忍独享,特定分享出来给大家,哈哈哈哈
typedef uint32 UTCTime;
// To be used with
typedef struct
{
uint8 seconds; // 0-59
uint8 minutes; // 0-59
uint8 hour; // 0-23
uint8 day; // 0-30
uint8 month; // 0-11
uint16 year; // 2000+
} UTCTimeStruct;
/*********************************************************************
* @fn osal_ConvertUTCTime
*
* @brief Converts UTCTime to UTCTimeStruct
*
* @param tm – pointer to breakdown struct
*
* @param secTime – number of seconds since 0 hrs, 0 minutes,
* 0 seconds, on the 1st of January 2000 UTC
*
* @return none
*/
void osal_ConvertUTCTime( UTCTimeStruct *tm, UTCTime secTime )
{
// calculate the time less than a day – hours, minutes, seconds
{
uint32 day = secTime % DAY;
tm->seconds = day % 60UL;
tm->minutes = (day % 3600UL) / 60UL;
tm->hour = day / 3600UL;
}
// Fill in the calendar – day, month, year
{
uint16 numDays = secTime / DAY;
tm->year = BEGYEAR;
while ( numDays >= YearLength( tm->year ) )
{
numDays -= YearLength( tm->year );
tm->year++;
}
tm->month = 0;
while ( numDays >= monthLength( IsLeapYear( tm->year ), tm->month ) )
{
numDays -= monthLength( IsLeapYear( tm->year ), tm->month );
tm->month++;
}
tm->day = numDays;
}
}
/*********************************************************************
* @fn osal_ConvertUTCSecs
*
* @brief Converts a UTCTimeStruct to UTCTime
*
* @param tm – pointer to provided struct
*
* @return number of seconds since 00:00:00 on 01/01/2000 (UTC)
*/
UTCTime osal_ConvertUTCSecs( UTCTimeStruct *tm )
{
uint32 seconds;
/* Seconds for the partial day */
seconds = (((tm->hour * 60UL) + tm->minutes) * 60UL) + tm->seconds;
/* Account for previous complete days */
{
/* Start with complete days in current month */
uint16 days = tm->day;
/* Next, complete months in current year */
{
int8 month = tm->month;
while ( –month >= 0 )
{
days += monthLength( IsLeapYear( tm->year ), month );
}
}
/* Next, complete years before current year */
{
uint16 year = tm->year;
while ( –year >= BEGYEAR )
{
days += YearLength( year );
}
}
/* Add total seconds before partial day */
seconds += (days * DAY);
}
return ( seconds );
}
Albin Zhang:
最佳会员,谢谢分享
BR. AZ
Susan Yang:
谢谢分享!