Breadcrumbs
Home / Programming / Objective-C / Change a file's Creation and Modification Dates on OS XChange a file's Creation and Modification Dates on OS X
A question came up on one of the forums the other day about how to change a file's creation and modification dates. They were using the /Developer/Tools/SetFile tool but were getting some odd results.
I searched all over the internet but everything I found would not do exactly what was needed.
For example. The command line utility touch using the '-tm' will change both the creation and modification dates to the same day but only if it is a date older than the current creation date.
I looked for a solution with Ruby, Python, Shell and Java but was unable to locate one. BTW, if you know of a solution using any scripting lanuguage, please post it in the comments.
Objective-C has a fairly simple way to accomplish this so that is where I turned next. The code below could use some more error checking and if you have LOTS of files to change you should modify the code to let it handle the entire job. This is created to be called from another script or code and it effects one file at a time.
@param creationDate = You can use dates like '12/01/10' or 'Last Tuesday at 12:00'
@param modDate = You can use dates like '12/01/10' or 'Last Tuesday at 12:00'
Example usage based on saving this code as a Foundation Tool in a location in your $PATH:
ChangeFileDates '/users/user_name/desktop/file_name.txt' '07/01/2009' '07/25/2009'
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *args = [[NSProcessInfo processInfo] arguments];
if ( argc != 4 ) {
printf(
"\nUsage: \n\tChangeFileDates filePath creationDate modDate\n"
"\tYou can use dates like '12/01/10' or 'Last Tuesday at 12:00'\n\n"
);
return 1;
}
// Arguments
NSString *path = [args objectAtIndex:1];
NSString *cDate = [args objectAtIndex:2];
NSString *mDate = [args objectAtIndex:3];
NSError *error;
NSFileManager *NSFm = [NSFileManager defaultManager];
NSDate *createDate = [NSDate dateWithNaturalLanguageString:cDate];
NSDate *modDate = [NSDate dateWithNaturalLanguageString:mDate];
NSDictionary *d = [NSDictionary dictionaryWithObjectsAndKeys:
createDate, NSFileCreationDate,
modDate, NSFileModificationDate,
nil ];
[NSFm setAttributes:d ofItemAtPath:path error:&error];
if ( error != NULL ) printf("\nThere was an error");
[pool drain];
return 0;
}

