场景
1.修改文件时间一般用在下载远程文件到本地时, 修改其创建时间为远程文件的原时间, 这样对文件排序查找时也方便归类. 这类文件有很多, 视频, 音频, 图片.
说明
1.Windows 和 macOS都有这种API, Windows以简单的C Win32 api 方式; macOS则使用NSFileManager来修改.
例子
Windows
#include <Windows.h>
//2014-09-13 10:52:36
static bool DateTextConvertToTM(SYSTEMTIME* st,const wchar_t* date){
static const int kLen = 19;
if(!date || wcslen(date)<19)
return false;
memset(st,0,sizeof(SYSTEMTIME));
st->wYear = _wtoi(date);
st->wMonth = _wtoi(date+5);
st->wDay = _wtoi(date+8);
st->wHour = _wtoi(date+11);
st->wMinute = _wtoi(date+14);
st->wSecond = _wtoi(date+17);
return true;
}
static bool ModifyFileDateTime(const wchar_t* date,const wchar_t* path)
{
HANDLE file = CreateFile(path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if(file){
SYSTEMTIME st,stUTC;
bool res = DateTextConvertToTM(&st,date);
if(!res) return false;
FILETIME ft;
BOOL f;
//hour: 0-23
TzSpecificLocalTimeToSystemTime(NULL,&st,&stUTC);
SystemTimeToFileTime(&stUTC, &ft); // Converts the current system time to file time format
f = SetFileTime(file, // Sets last-write time of the file
&ft,NULL, // to the converted current system time
&ft);
CloseHandle(file);
return true;
}
return false;
}
macOS
#import <Foundation/Foundation.h>
//2014-09-13 10:52:36
BOOL ModifyFileDateTime(const char* date,const char* path)
{
NSString *dateComponents = @"yyyy-MM-dd HH:mm:ss";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateComponents];
NSDate *nsdate = [dateFormatter dateFromString:[NSString stringWithUTF8String:date]];
NSFileManager* fm = [NSFileManager defaultManager];
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:nsdate,NSFileCreationDate,nsdate,NSFileModificationDate, nil];
BOOL res = [fm setAttributes:dict ofItemAtPath:[NSString stringWithUTF8String:path] error:nil];
return res;
}