[文件时间]_[Windows-macOS]_[修改文件的创建时间-修改时间]

场景

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;
}

参考

修改文件的创建时间-修改时间-访问时间

NSDateFormatter

NSFileManager

NSDate

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Peter(阿斯拉达)

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值