File modification time
You are encouraged to solve this task according to the task description, using any language you may know.
This task will attempt to get and set the modification time of a file.
Ada
Ada does not allow you to change the date of a file but you can definitely read it: <lang ada>with Ada.Directories; use Ada.Directories; with Ada.Text_IO; use Ada.Text_IO; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
procedure File_Time_Test is begin
Put_Line (Image (Modification_Time ("file_time_test.adb")));
end File_Time_Test;</lang>
AutoHotkey
<lang AutoHotkey>FileGetTime, OutputVar, output.txt MsgBox % OutputVar FileSetTime, 20080101, output.txt FileGetTime, OutputVar, output.txt MsgBox % OutputVar</lang>
Batch File
<lang dos>for %%f in (file.txt) do echo.%%~tf</lang>
The date/time format is dependent on the user's locale, like the contents of the %DATE%
and %TIME%
built-ins. There is no built-in way of setting a file's modification time.
BBC BASIC
<lang bbcbasic> DIM ft{dwLowDateTime%, dwHighDateTime%}
DIM st{wYear{l&,h&}, wMonth{l&,h&}, wDayOfWeek{l&,h&}, \ \ wDay{l&,h&}, wHour{l&,h&}, wMinute{l&,h&}, \ \ wSecond{l&,h&}, wMilliseconds{l&,h&} } REM File is assumed to exist: file$ = @tmp$ + "rosetta.tmp" REM Get and display the modification time: file% = OPENIN(file$) SYS "GetFileTime", @hfile%(file%), 0, 0, ft{} CLOSE #file% SYS "FileTimeToSystemTime", ft{}, st{} date$ = STRING$(16, CHR$0) time$ = STRING$(16, CHR$0) SYS "GetDateFormat", 0, 0, st{}, 0, date$, LEN(date$) TO N% date$ = LEFT$(date$, N%-1) SYS "GetTimeFormat", 0, 0, st{}, 0, time$, LEN(time$) TO N% time$ = LEFT$(time$, N%-1) PRINT date$ " " time$ REM Set the modification time to the current time: SYS "GetSystemTime", st{} SYS "SystemTimeToFileTime", st{}, ft{} file% = OPENUP(file$) SYS "SetFileTime", @hfile%(file%), 0, 0, ft{} CLOSE #file%
</lang>
C
POSIX utime()
utime() has a precision of one second. This program would truncate the time to the last second, losing precision if the filesystem is more precise.
<lang c>#include <sys/stat.h>
- include <stdio.h>
- include <time.h>
- include <utime.h>
const char *filename = "input.txt";
int main() {
struct stat foo; time_t mtime; struct utimbuf new_times;
if (stat(filename, &foo) < 0) { perror(filename); return 1; } mtime = foo.st_mtime; /* seconds since the epoch */
new_times.actime = foo.st_atime; /* keep atime unchanged */ new_times.modtime = time(NULL); /* set mtime to current time */ if (utime(filename, &new_times) < 0) { perror(filename); return 1; }
return 0;
}</lang>
BSD utimes()
With BSD, utime() is obsolete. utimes() has a precision of 1 microsecond (where 1 second = 1000000 microseconds).
<lang c>#include <sys/stat.h>
- include <sys/time.h>
- include <err.h>
const char *filename = "input.txt";
int main() {
struct stat foo; struct timeval new_times[2];
if (stat(filename, &foo) < 0) err(1, "%s", filename);
/* keep atime unchanged */ TIMESPEC_TO_TIMEVAL(&new_times[0], &foo.st_atim);
/* set mtime to current time */ gettimeofday(&new_times[1], NULL);
if (utimes(filename, new_times) < 0) err(1, "%s", filename);
return 0;
}</lang>
POSIX utimensat()
utimensat(2) has a precision of 1 nanosecond (where 1 second = 10**9 nanoseconds). Program needs to be linked with -lrt
.
<lang c>#include <sys/stat.h>
- include <sys/time.h>
- include <time.h>
- include <fcntl.h>
- include <stdio.h>
const char *filename = "input.txt";
int main() {
struct stat foo; struct timespec new_times[2]; if (stat(filename, &foo) < 0) { perror(filename); return 1; } /* keep atime unchanged */ new_times[0] = foo.st_atim; /* set mtime to current time */ clock_gettime(CLOCK_REALTIME, &new_times[1]); if (utimensat(AT_FDCWD, filename, new_times, 0) < 0) { perror(filename); return 1; } return 0;
}</lang>
Windows
Declare FILETIME modtime;
and then use GetFileTime(fh, NULL, NULL, &modtime);
to get the file modification time, or SetFileTime(fh, NULL, NULL, &modtime);
to set it.
<lang c>#include <windows.h>
- include <stdio.h>
- include <stdlib.h>
- include <wchar.h>
/* Print "message: last Win32 error" to stderr. */ void oops(const wchar_t *message) { wchar_t *buf; DWORD error;
buf = NULL; error = GetLastError(); FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, error, 0, (wchar_t *)&buf, 0, NULL);
if (buf) { fwprintf(stderr, L"%ls: %ls", message, buf); LocalFree(buf); } else { /* FormatMessageW failed. */ fwprintf(stderr, L"%ls: unknown error 0x%x\n", message, error); } }
int setmodtime(const wchar_t *path) { FILETIME modtime; SYSTEMTIME st; HANDLE fh; wchar_t date[80], time[80];
fh = CreateFileW(path, GENERIC_READ | FILE_WRITE_ATTRIBUTES, 0, NULL, OPEN_EXISTING, 0, NULL); if (fh == INVALID_HANDLE_VALUE) { oops(path); return 1; }
/* * Use GetFileTime() to get the file modification time. */ if (GetFileTime(fh, NULL, NULL, &modtime) == 0) goto fail; FileTimeToSystemTime(&modtime, &st); if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 || GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0) goto fail; wprintf(L"%ls: Last modified at %s at %s (UTC).\n", path, date, time);
/* * Use SetFileTime() to change the file modification time * to the current time. */ GetSystemTime(&st); if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 || GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0) goto fail; SystemTimeToFileTime(&st, &modtime); if (SetFileTime(fh, NULL, NULL, &modtime) == 0) goto fail; wprintf(L"%ls: Changed to %s at %s (UTC).\n", path, date, time);
CloseHandle(fh); return 0;
fail: oops(path); CloseHandle(fh); return 1; }
/*
* Show the file modification time, and change it to the current time. */
int main() { int argc, i, r; wchar_t **argv;
/* MinGW never provides wmain(argc, argv). */ argv = CommandLineToArgvW(GetCommandLineW(), &argc); if (argv == NULL) { oops(L"CommandLineToArgvW"); exit(1); }
if (argc < 2) { fwprintf(stderr, L"usage: %ls file...\n", argv[0]); exit(1); }
r = 0; for (i = 1; argv[i] != NULL; i++) if (setmodtime(argv[i])) r = 1; return r; }</lang>
C++
compiled with g++ -lboost_filesystem <sourcefile> -o <destination file> <lang cpp>#include <boost/filesystem/operations.hpp>
- include <ctime>
- include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 2 ) { std::cerr << "Error! Syntax: moditime <filename>!\n" ; return 1 ; } boost::filesystem::path p( argv[ 1 ] ) ; if ( boost::filesystem::exists( p ) ) { std::time_t t = boost::filesystem::last_write_time( p ) ; std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ]
<< " was modified the last time!\n" ;
std::cout << "Setting the modification time to now:\n" ; std::time_t n = std::time( 0 ) ; boost::filesystem::last_write_time( p , n ) ; t = boost::filesystem::last_write_time( p ) ; std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ; return 0 ; } else { std::cout << "Could not find file " << argv[ 1 ] << '\n' ; return 2 ; }
}</lang>
C#
<lang csharp>using System; using System.IO;
Console.WriteLine(File.GetLastWriteTime("file.txt")); File.SetLastWriteTime("file.txt", DateTime.Now);</lang>
Clojure
<lang lisp>(import '(java.io File)
'(java.util Date))
(Date. (.lastModified (File. "output.txt"))) (Date. (.lastModified (File. "docs")))
(.setLastModified (File. "output.txt")
(.lastModified (File. "docs")))</lang>
Common Lisp
Common Lisp doesn't provide a way to set the modification time. The write date can be accessed, however, using file-write-date:
<lang lisp>(file-write-date "input.txt")</lang>
Implementations may, in addition, provide other ways of accessing these file attributes, e.g., POSIX bindings:
(1.0.30, OS X, Intel),
(sb-posix:utime
takes an access time and a modification time rather than an array of two times.)
<lang lisp>(let* ((filename "input.txt")
(stat (sb-posix:stat filename)) (mtime (sb-posix:stat-mtime stat))) (sb-posix:utime filename
(sb-posix:stat-atime stat) (sb-posix:time)))</lang>
D
<lang d>import std.stdio; import std.file: getTimes, setTimes, SysTime;
void main() {
auto fname = "unixdict.txt"; SysTime fileAccessTime, fileModificationTime; getTimes(fname, fileAccessTime, fileModificationTime); writeln(fileAccessTime, "\n", fileModificationTime); setTimes(fname, fileAccessTime, fileModificationTime);
}</lang> For Windows systems there is also getTimesWin(), that gives the file creation time too.
Delphi
<lang Delphi>procedure GetModifiedDate(const aFilename: string): TDateTime; var
hFile: Integer; iDosTime: Integer;
begin
hFile := FileOpen(aFilename, fmOpenRead); iDosTime := FileGetDate(hFile); FileClose(hFile); if (hFile = -1) or (iDosTime = -1) then raise Exception.Create('Cannot read file: ' + sFilename); Result := FileDateToDateTime(iDosTime);
end;
procedure ChangeModifiedDate(const aFilename: string; aDateTime: TDateTime); begin
FileSetDate(aFileName, DateTimeToFileDate(aDateTime));
end;</lang>
E
E follows the Java File interface, except that it replaces boolean success/failure returns with an ejector parameter, so that the default behavior if the client does not handle the case is not to continue ignoring the failure.
<lang e>def strdate(date) {
return E.toString(<unsafe:java.util.makeDate>(date))
}
def test(type, file) {
def t := file.lastModified() println(`The following $type called ${file.getPath()} ${ if (t == 0) { "does not exist." } else { `was modified at ${strdate(t)}` }}`) println(`The following $type called ${file.getPath()} ${ escape ne { file.setLastModified(timer.now(), ne); "was modified to current time." } catch _ { "does not exist." }}`) println(`The following $type called ${file.getPath()} ${ escape ne { file.setLastModified(t, ne); "was modified to previous time." } catch _ { "does not exist." }}`)
}
test("file", <file:output.txt>) test("directory", <file:docs>)</lang>
Erlang
<lang Erlang> -module( file_modification_time ).
-include_lib("kernel/include/file.hrl").
-export( [task/0] ).
task() ->
File = "input.txt", {ok, File_info} = file:read_file_info( File ), io:fwrite( "Modification time ~p~n", [File_info#file_info.mtime] ), ok = file:write_file_info( File, File_info#file_info{mtime=calendar:local_time()} ).
</lang>
F#
<lang fsharp>open System open System.IO
[<EntryPoint>] let main args =
Console.WriteLine(File.GetLastWriteTime(args.[0])) File.SetLastWriteTime(args.[0], DateTime.Now) 0</lang>
Factor
<lang factor>"foo.txt" file-info modified>> .</lang> Setting the modified time is not cross-platform, so here's a Unix version. <lang factor>USE: io.files.info.unix
"foo.txt" now 2 hours time+ set-file-modified-time</lang>
Go
<lang go>package main
import (
"fmt" "os" "syscall" "time"
)
var filename = "input.txt"
func main() {
foo, err := os.Stat(filename) if err != nil { fmt.Println(err) return } fmt.Println("mod time was:", foo.ModTime()) mtime := time.Now() atime := mtime // a default, because os.Chtimes has an atime parameter. // but see if there's a real atime that we can preserve. if ss, ok := foo.Sys().(*syscall.Stat_t); ok { atime = time.Unix(ss.Atim.Sec, ss.Atim.Nsec) } os.Chtimes(filename, atime, mtime) fmt.Println("mod time now:", mtime)
}</lang>
GUISS
In Graphical User Interface Support Script, we can can only use facilities that the underlying user interface provides, so we can display file timestamps, but cannot alter them. In this example, we get the date and timestamp for the file Foobar.txt.
<lang guiss>Start,My Documents,Rightclick:Icon:Foobar.txt,Properties</lang>
Haskell
<lang haskell>import System.Posix.Files import System.Posix.Time
do status <- getFileStatus filename
let atime = accessTime status mtime = modificationTime status -- seconds since the epoch curTime <- epochTime setFileTimes filename atime curTime -- keep atime unchanged -- set mtime to current time</lang>
Alternative (only gets modification time): <lang haskell>import System.Directory import System.Time
do ct <- getModificationTime filename
cal <- toCalendarTime ct putStrLn (calendarTimeToString cal)</lang>
HicEst
<lang hicest>CHARACTER timestamp*18
timestamp = ' ' ! blank timestamp will read: SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp) ! 20100320141940.525
timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp)</lang>
Icon and Unicon
Icon doesn't support 'stat' or 'utime'; however, information can be obtained by use of the system function to access command line. <lang Unicon> every dir := !["./","/"] do {
if i := stat(f := dir || "input.txt") then { write("info for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime)) utime(f,i.atime,i.mtime-1024) i := stat(f) write("update for ",f ," mtime= ",ctime(i.mtime),", atime=",ctime(i.ctime), ", atime=",ctime(i.atime)) } else stop("failure to stat ",f) }</lang>
Notes:
- Icon and Unicon accept both / and \ for directory separators.
- 'ctime' formats an integer representing an epoch time into human readable form
- 'utime' updates the atime and mtime values
J
The standard file access library only supports reading the file modification time. <lang j> load 'files'
fstamp 'input.txt'
2009 8 24 20 34 30</lang> It is possible to set the time but it has to be done through OS specific external calls.
Java
<lang java>import java.io.File; import java.util.Date; public class FileModificationTimeTest {
public static void test(String type, File file) { long t = file.lastModified(); System.out.println("The following " + type + " called " + file.getPath() + (t == 0 ? " does not exist." : " was modified at " + new Date(t).toString() ) ); System.out.println("The following " + type + " called " + file.getPath() + (!file.setLastModified(System.currentTimeMillis()) ? " does not exist." : " was modified to current time." ) ); System.out.println("The following " + type + " called " + file.getPath() + (!file.setLastModified(t) ? " does not exist." : " was modified to previous time." ) ); } public static void main(String args[]) { test("file", new File("output.txt")); test("directory", new File("docs")); }
}</lang>
JavaScript
Get only. <lang javascript>var fso = new ActiveXObject("Scripting.FileSystemObject"); var f = fso.GetFile('input.txt'); var mtime = f.DateLastModified;</lang> The following works in all browsers, including IE10. <lang javascript>var file = document.getElementById("fileInput").files.item(0); var last_modified = file.lastModifiedDate;</lang>
Lasso
Note this is retrieve only.
File modification date is updated on save of file. <lang Lasso>local(f) = file('input.txt') handle => { #f->close }
- f->modificationDate->format('%-D %r')
// result: 12/2/2010 11:04:15 PM</lang>
Lua
<lang lua>require "lfs" local attributes = lfs.attributes("input.txt") if attributes then
print(path .. " was last modified " .. os.date("%c", attributes.modification) .. ".")
-- set access and modification time to now ... lfs.touch("input.txt")
-- ... or set modification time to now, keep original access time lfs.touch("input.txt", attributes.access, os.time())
else
print(path .. " does not exist.")
end</lang>
Mathematica
Get file modification time: <lang Mathematica> FileDate["file","Modification"]</lang> results is returned in format: {year,month,day,hour,minute,second}. Setting file modification time: <lang Mathematica> SetFileDate["file",date,"Modification"]</lang> where date is specified as {year,month,day,hour,minute,second}.
MATLAB / Octave
<lang Matlab> f = dir('output.txt'); % struct f contains file information
f.date % is string containing modification time f.datenum % numerical format (number of days) datestr(f.datenum) % is the same as f.date % see also: stat, lstat </lang>
Modifying of file access time can be done through system calls:
<lang Matlab> system('touch -t 201002032359.59 output.txt'); </lang>
MAXScript
MAXScript has no method to set the mod time <lang maxscript>-- Returns a string containing the mod date for the file, e.g. "1/29/99 1:52:05 PM" getFileModDate "C:\myFile.txt"</lang>
Modula-3
<lang modula3>MODULE ModTime EXPORTS Main;
IMPORT IO, Fmt, File, FS, Date, OSError;
TYPE dateArray = ARRAY [0..5] OF TEXT;
VAR
file: File.Status; date: Date.T;
PROCEDURE DateArray(date: Date.T): dateArray =
BEGIN RETURN dateArray{Fmt.Int(date.year), Fmt.Int(ORD(date.month) + 1), Fmt.Int(date.day), Fmt.Int(date.hour), Fmt.Int(date.minute), Fmt.Int(date.second)}; END DateArray;
BEGIN
TRY file := FS.Status("test.txt"); date := Date.FromTime(file.modificationTime); IO.Put(Fmt.FN("%s-%02s-%02s %02s:%02s:%02s", DateArray(date))); IO.Put("\n"); EXCEPT | OSError.E => IO.Put("Error: Failed to get file status.\n"); END;
END ModTime.</lang> Output:
2011-07-14 14:12:46
This program sets the modification time to any value we wish: <lang modula3>MODULE SetModTime EXPORTS Main;
IMPORT Date, FS;
<*FATAL ANY*>
VAR
date: Date.T;
BEGIN
(* Set the modification time to January 1st, 1999 *) date.year := 1999; date.month := Date.Month.Jan; date.day := 1; date.hour := 0; date.minute := 0; date.second := 0; date.offset := 21601; date.zone := "CST";
FS.SetModificationTime("test.txt", Date.ToTime(date)); END SetModTime.</lang> We can see the output with the Unix command stat
stat test.txt | grep Mod Modify: 1999-01-01 00:00:01.000000000 -0600
NetRexx
<lang NetRexx>/* NetRexx */ options replace format comments java crossref symbols binary
runSample(arg) return
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ method runSample(arg) public static
parse arg fileName if fileName = then fileName = 'data/tempfile01' mfile = File(fileName) mtime = mfile.lastModified() dtime = Date(mtime).toString() say 'File' fileName 'last modified at' dtime say if mfile.setLastModified(0) then do dtime = Date(mfile.lastModified()).toString() say 'File modification time altered...' say 'File' fileName 'now last modified at' dtime say say 'Resetting...' mfile.setLastModified(mtime) dtime = Date(mfile.lastModified()).toString() say 'File' fileName 'reset to last modified at' dtime end else do say 'Unable to modify time for file' fileName end return
</lang>
- Output:
File data/tempfile01 last modified at Fri May 24 14:45:55 PDT 2013 File modification time altered... File data/tempfile01 now last modified at Wed Dec 31 16:00:00 PST 1969 Resetting... File data/tempfile01 reset to last modified at Fri May 24 14:45:55 PDT 2013
Objective-C
<lang objc>NSFileManager *fm = [NSFileManager defaultManager];
// Pre-OS X 10.5 NSLog(@"%@", [[fm fileAttributesAtPath:@"input.txt" traverseLink:YES] fileModificationDate]); [fm changeFileAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
atPath:@"input.txt"];
// OS X 10.5+ NSLog(@"%@", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileModificationDate]); [fm setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
ofItemAtPath:@"input.txt" error:NULL];</lang>
OCaml
<lang ocaml>#load "unix.cma";; open Unix;; let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)
utimes filename (stat filename).st_atime (time ());; (* keep atime unchanged
set mtime to current time *)</lang>
OpenEdge/Progress
The file modified time can only be read.
<lang progress>FILE-INFO:FILE-NAME = 'c:/temp'. MESSAGE
STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX</lang>
Oz
Getting the modification time: <lang oz>declare
[Path] = {Module.link ['x-oz://system/os/Path.ozf']} Modified = {Path.mtime "input.txt"} %% posix time
in
{Show {OsTime.localtime Modified}} %% human readable record</lang>
Setting the modification time is not possible, unless implemented as an extension in C or C++.
Pascal
See Delphi
Perl
<lang perl>my $mtime = (stat($file))[9]; # seconds since the epoch
- you should use the more legible version below:
use File::stat qw(stat); my $mtime = stat($file)->mtime; # seconds since the epoch
utime(stat($file)->atime, time, $file);
- keep atime unchanged
- set mtime to current time</lang>
Perl 6
<lang perl6>use NativeCall;
class utimbuf is repr('CStruct') {
has int $.actime; has int $.modtime;
submethod BUILD(:$atime, :$mtime) { $!actime = $atime; $!modtime = $mtime; }
}
sub sysutime(Str, utimbuf --> int) is native is symbol('utime') {*}
sub MAIN (Str $file) {
my $mtime = $file.IO.modified // die "Can't stat $file: $!";
my $ubuff = utimbuf.new(:atime(time),:mtime($mtime));
sysutime($file, $ubuff);
}</lang> Sets the last access time to now, while restoring the modification time to what it was before.
PHP
<lang php><?php $filename = 'input.txt';
$mtime = filemtime($filename); // seconds since the epoch
touch($filename,
time(), // set mtime to current time fileatime($filename)); // keep atime unchanged
?></lang>
PicoLisp
<lang PicoLisp>(let File "test.file"
(and (info File) (prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC (call 'touch File) ) # Set modification time to "now"</lang>
Output:
2010-02-20 15:46:37
Pop11
<lang pop11>;;; Print modification time (seconds since Epoch) sysmodtime('file') =></lang>
PowerShell
<lang powershell> $modificationTime = (Get-ChildItem file.txt).LastWriteTime Set-ItemProperty file.txt LastWriteTime (Get-Date)
$LastReadTime = (Get-ChildItem file.txt).LastAccessTime Set-ItemProperty file.txt LastAccessTime(Get-Date)
$CreationTime = (Get-ChildItem file.txt).CreationTime Set-ItemProperty file.txt CreationTime(Get-Date) </lang>
You can also use alternates to get UTC time: LastWriteTimeUtc LastAccessTimeUtc CreationTimeUtc
PureBasic
<lang PureBasic>Debug FormatDate("%yyyy/%mm/%dd", GetFileDate("file.txt",#PB_Date_Modified))
SetFileDate("file.txt",#PB_Date_Modified,Date(1987, 10, 23, 06, 43, 15))
Debug FormatDate("%yyyy/%mm/%dd - %hh:%ii:%ss", GetFileDate("file.txt",#PB_Date_Modified))</lang>
Python
<lang python>import os
- Get modification time:
modtime = os.path.getmtime('filename')
- Set the access and modification times:
os.utime('path', (actime, mtime))
- Set just the modification time:
os.utime('path', (os.path.getatime('path'), mtime))
- Set the access and modification times to the current time:
os.utime('path', None)</lang>
R
See this R-devel mailing list thread for more information. <lang r># Get the value file.info(filename)$mtime
- To set the value, we need to rely on shell commands. The following works under windows.
shell("copy /b /v filename +,,>nul")
- and on Unix (untested)
shell("touch -m filename")</lang>
Racket
<lang racket>
- lang racket
(file-or-directory-modify-seconds "foo.rkt") </lang>
RapidQ
<lang rapidq>name$ = DIR$("input.txt", 0) PRINT "File date: "; FileRec.Date PRINT "File time: "; FileRec.Time</lang>
REALbasic
The Date object has properties which correspond to various date formats such as SQLDateTime (YYYY-MM-DD HH:MM:SS), DayOfWeek, DayOfYear, and TotalSeconds since 12:00AM, January 1, 1904, among others. <lang REALbasic> Function getModDate(f As FolderItem) As Date
Return f.ModificationDate
End Function</lang>
Ruby
<lang ruby>#Get modification time: modtime = File.mtime('filename')
- Set the access and modification times:
File.utime(actime, mtime, 'path')
- Set just the modification time:
File.utime(File.atime('path'), mtime, 'path')
- Set the access and modification times to the current time:
File.utime(nil, nil, 'path')</lang>
Run BASIC
<lang runbasic>files #f, DefaultDir$ + "\*.*" ' all files in the defalt directory
print "hasanswer: ";#f HASANSWER() ' does it exist print "rowcount: ";#f ROWCOUNT() ' number of files in the directory print '
- f DATEFORMAT("mm/dd/yy") ' set format of file date to template given
- f TIMEFORMAT("hh:mm:ss") ' set format of file time to template given
for i = 1 to #f rowcount() ' loop through the files if #f hasanswer() then ' or loop with while #f hasanswer()
print "nextfile info: ";#f nextfile$(" ") ' set the delimiter for nextfile info print "name: ";name$ ' file name print "size: ";#f SIZE() ' file size print "date: ";#f DATE$() ' file date print "time: ";#f TIME$() ' file time print "isdir: ";#f ISDIR() ' is it a directory or file
name$ = #f NAME$() shell$("touch -t 201002032359.59 ";name$;""") ' sell to os to set date
end if next</lang>
Seed7
<lang seed7>$ include "seed7_05.s7i";
include "osfiles.s7i"; include "time.s7i";
const proc: main is func
local var time: modificationTime is time.value; begin modificationTime := getMTime("data.txt"); setMTime("data.txt", modificationTime); end func;</lang>
Slate
Modifying the timestamp value is not currently a built-in feature. This code gets a raw value:
<lang slate>slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp. 1240349799</lang>
Smalltalk
<lang smalltalk>|a| a := File name: 'input.txt'. (a lastModifyTime) printNl.</lang>
Standard ML
<lang sml>val mtime = OS.FileSys.modTime filename; (* returns a Time.time data structure *)
(* unfortunately it seems like you have to set modification & access times together *) OS.FileSys.setTime (filename, NONE); (* sets modification & access time to now *) (* equivalent to: *) OS.FileSys.setTime (filename, SOME (Time.now ()))</lang>
Tcl
Assuming that the variable filename holds the name of the file... <lang tcl># Get the modification time: set timestamp [file mtime $filename]
- Set the modification time to ‘now’:
file mtime $filename [clock seconds]</lang>
TUSCRIPT
TUSCRIPT does not allow to modify/set the timestamp of a file, but it is able to read it <lang tuscript> $$ MODE TUSCRIPT file="rosetta.txt" ERROR/STOP OPEN (file,READ,-std-) modified=MODIFIED (file) PRINT "file ",file," last modified: ",modified </lang> Output:
file rosetta.txt last modified: 2011-12-14 23:50:48
UNIX Shell
There are several ways to handle files' timestamps in most *nix systems. For these examples, we'll assume you need to retrieve the timestamp to a variable. These examples use stat and touch from the GNU Core Utilities, under bash, but they should work with any POSIX-compliant implementation under any sh-compatible shell.
For all of these examples, $F
is a variable holding the filename to examine, while T
(and $T
) is the timestamp.
To get the timestamp in seconds since the epoch: <lang bash>T=`stat -c %Y $F`</lang>
To get the timestamp in human-readable format: <lang bash>T=`stat -c %y $F`</lang>
Note that the only difference between the above examples is capital Y vs lower-case y.
In the following examples, the "-c" argument to touch tells it to not create any files that don't already exist.
To set file F to time T, where T is in a human-readable format: <lang bash># Note the quotation marks -- very important! T="2000-01-01 01:02:03.040506070 -0800" touch -c -d "$T" $F</lang>
To set file F to time T, where T is in the format [[CC]YY]MMDDhhmm[.ss] (the square brackets mark optional parts): <lang bash>T=200102030405.06 touch -c -t $T $F</lang>
If the year is left out, the current year is used. If the seconds are left out, 0 (zero) is used. Leaving out the optional parts of the above results in this: <lang bash>T=02030405 touch -c -t $T $F</lang>
If no time is specified, then the timestamp is set to the current time: <lang bash>touch -c $F</lang>
There are, of course, other ways to do both tasks -- for example, one could use ls -l --time-style=full-iso
and then process the resulting list with some other tool (e.g. awk or Perl).
Vedit macro language
Display file's last modification time as number of seconds since midnight. <lang vedit>Num_Type(File_Stamp_Time("input.txt"))</lang>
Displays file's last modification date and time as a string. <lang vedit>File_Stamp_String(10, "input.txt") Reg_Type(10)</lang> Vedit Macro Language has Blog in SEO no method to set the modification time
Visual Basic .NET
Platform: .NET
<lang vbnet>Dim file As New IO.FileInfo("test.txt")
'Creation Time Dim createTime = file.CreationTime file.CreationTime = createTime.AddHours(1)
'Write Time Dim writeTime = file.LastWriteTime file.LastWriteTime = writeTime.AddHours(1)
'Access Time Dim accessTime = file.LastAccessTime file.LastAccessTime = accessTime.AddHours(1)</lang>
- Programming Tasks
- File System Operations
- Ada
- AutoHotkey
- Batch File
- BBC BASIC
- C
- POSIX
- BSD libc
- Win32
- C++
- C sharp
- Clojure
- Common Lisp
- D
- Delphi
- E
- Erlang
- F Sharp
- Factor
- Go
- GUISS
- Haskell
- HicEst
- Icon
- Unicon
- J
- Java
- JavaScript
- Lasso
- Lua
- Mathematica
- MATLAB
- Octave
- MAXScript
- Modula-3
- NetRexx
- Objective-C
- OCaml
- OpenEdge/Progress
- Oz
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- Pop11
- PowerShell
- PureBasic
- Python
- R
- Racket
- RapidQ
- REALbasic
- Ruby
- Run BASIC
- Seed7
- Slate
- Smalltalk
- Standard ML
- Tcl
- TUSCRIPT
- UNIX Shell
- Vedit macro language
- Visual Basic .NET
- Befunge/Omit
- HTML/Omit
- M4/Omit
- Maxima/Omit
- PARI/GP/Omit
- Retro/Omit
- TI-83 BASIC/Omit
- TI-89 BASIC/Omit
- ZX Spectrum Basic/Omit
- Locomotive Basic/Omit
- Date and time