我正在尝试将时间结构转换为FAT时间戳。我的代码看起来像这样:
unsigned long Fat(tm_struct pTime)
{
unsigned long FatTime = 0;
FatTime |= (pTime.seconds / 2) >> 1;
FatTime |= (pTime.minutes) << 5;
FatTime |= (pTime.hours) << 11;
FatTime |= (pTime.days) << 16;
FatTime |= (pTime.months) << 21;
FatTime |= (pTime.years + 20) << 25;
return FatTime;
}有人有正确的代码吗?
发布于 2013-04-02 19:57:56
The DOS date/time format is a bitmask:
24 16 8 0
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
|Y|Y|Y|Y|Y|Y|Y|M| |M|M|M|D|D|D|D|D| |h|h|h|h|h|m|m|m| |m|m|m|s|s|s|s|s|
+-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+ +-+-+-+-+-+-+-+-+
\___________/\________/\_________/ \________/\____________/\_________/
year month day hour minute second
The year is stored as an offset from 1980.
Seconds are stored in two-second increments.
(So if the "second" value is 15, it actually represents 30 seconds.)我不知道您正在使用的tm_struct,但如果是http://www.cplusplus.com/reference/ctime/tm/,那么
unsigned long FatTime = ((pTime.tm_year - 80) << 25) |
((pTime.tm_mon + 1) << 21) |
(pTime.tm_mday << 16) |
(pTime.tm_hour << 11) |
(pTime.tm_min << 5) |
(pTime.tm_sec >> 1);编辑:我添加了评论中提到的+1月份
发布于 2017-08-08 23:52:45
Lefteris E给出了几乎正确的答案,但这里有一个小错误
您应该将1加到tm_mon中,因为tm struct将月份作为数字,从0到11 (struct tm),而DOS日期/时间从1到12 (FileTimeToDosDateTime。所以正确的说就是
unsigned long FatTime = ((pTime.tm_year - 80) << 25) |
((pTime.tm_mon+1) << 21) |
(pTime.tm_mday << 16) |
(pTime.tm_hour << 11) |
(pTime.tm_min << 5) |
(pTime.tm_sec >> 1);发布于 2019-09-09 23:15:01
你也可以使用位域和库time.h。在我的项目中,我将UNIX时间戳转换为FatFs时间。
#include <time.h>
#pragma pack (push,1)
typedef struct{
unsigned Sec :5;
unsigned Min :6;
unsigned Hour :5;
unsigned Day :5;
unsigned Month :4;
unsigned Year :7;
}FatDate_t;
#pragma pack (pop)
DWORD get_fattime(void){
time_t ts=GetDateTimeNow();
struct tm * tmInfo = gmtime( &ts );
uint32_t Result=0;
FatDate_t *fatDate;
fatDate=(FatDate_t *)&Result;
fatDate->Year=tmInfo->tm_year-80;
fatDate->Month=tmInfo->tm_mon+1;
fatDate->Day=tmInfo->tm_mday;
fatDate->Hour=tmInfo->tm_hour;
fatDate->Min=tmInfo->tm_min;
fatDate->Sec=tmInfo->tm_sec>>1;
return Result;
}https://stackoverflow.com/questions/15763259
复制相似问题