File modification time: Difference between revisions

m
No edit summary
m (→‎{{header|Wren}}: Minor tidy)
 
(19 intermediate revisions by 13 users not shown)
Line 2:
[[Category:Date and time]]
{{omit from|Befunge|No filesystem support}}
{{omit from|EasyLang}}
{{omit from|HTML}}
{{omit from|Locomotive Basic|Does not have a real time clock.}}
Line 18 ⟶ 19:
=={{header|Ada}}==
Ada does not allow you to change the date of a file but you can definitely read it:
<langsyntaxhighlight lang="ada">with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Calendar.Formatting; use Ada.Calendar.Formatting;
Line 25 ⟶ 26:
begin
Put_Line (Image (Modification_Time ("file_time_test.adb")));
end File_Time_Test;</langsyntaxhighlight>
 
=={{header|ALGOL 68}}==
Definition of the PROC is lifted from the Algol68 Genie documentation.
<langsyntaxhighlight lang="algol68">PROC get output = (STRING cmd) VOID:
IF STRING sh cmd = " " + cmd + " ; 2>&1";
STRING output;
Line 39 ⟶ 40:
get output ("touch -t 200109111246.40 WTC_1"); CO Change its last modified time CO
get output ("ls -l --time-style=full-iso WTC_1") CO Verify it changed CO
</syntaxhighlight>
</lang>
{{Out}}
<pre>-rw-r--r-- 1 pcl pcl 0 2015-08-10 17:57:50.279854695 +0100 WTC_1
Line 45 ⟶ 46:
 
=={{header|AutoHotkey}}==
<langsyntaxhighlight AutoHotkeylang="autohotkey">FileGetTime, OutputVar, output.txt
MsgBox % OutputVar
FileSetTime, 20080101, output.txt
FileGetTime, OutputVar, output.txt
MsgBox % OutputVar</langsyntaxhighlight>
 
=={{header|AWK}}==
{{works with|gawk}}
<langsyntaxhighlight lang="awk">@load "filefuncs"
BEGIN {
 
Line 67 ⟶ 68:
close(cmd)
 
}</langsyntaxhighlight>
 
Non-GNU awk's don't have direct access to the filesystem but can execute system-commands.
 
<langsyntaxhighlight lang="awk">#!/bin/awk -f
BEGIN { # file modification time on Unix, using stat
fn ="input.txt"
Line 104 ⟶ 105:
cmd="stat " fn
print "#", cmd; system(cmd)
}</langsyntaxhighlight>
 
{{out}}
Line 132 ⟶ 133:
=={{header|Batch File}}==
{{works with|Windows NT|4}}
<langsyntaxhighlight lang="dos">for %%f in (file.txt) do echo.%%~tf</langsyntaxhighlight>
The date/time format is dependent on the user's locale, like the contents of the <code>%DATE%</code> and <code>%TIME%</code> built-ins.
There is no built-in way of setting a file's modification time.
Line 138 ⟶ 139:
=={{header|BBC BASIC}}==
{{works with|BBC BASIC for Windows}}
<langsyntaxhighlight 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&}, \
Line 165 ⟶ 166:
SYS "SetFileTime", @hfile%(file%), 0, 0, ft{}
CLOSE #file%
</syntaxhighlight>
</lang>
 
=={{header|C}}==
Line 174 ⟶ 175:
 
{{libheader|POSIX}}
<langsyntaxhighlight lang="c">#include <sys/stat.h>
#include <stdio.h>
#include <time.h>
Line 200 ⟶ 201:
 
return 0;
}</langsyntaxhighlight>
 
===BSD utimes()===
Line 207 ⟶ 208:
 
{{libheader|BSD libc}}
<langsyntaxhighlight lang="c">#include <sys/stat.h>
#include <sys/time.h>
#include <err.h>
Line 230 ⟶ 231:
 
return 0;
}</langsyntaxhighlight>
 
=== POSIX utimensat() ===
Line 238 ⟶ 239:
{{libheader|POSIX}}
{{works with|POSIX|-1.2008}}
<langsyntaxhighlight lang="c">#include <sys/stat.h>
#include <sys/time.h>
#include <time.h>
Line 267 ⟶ 268:
return 0;
}</langsyntaxhighlight>
 
=== Windows ===
Line 273 ⟶ 274:
 
{{libheader|Win32}}
<langsyntaxhighlight lang="c">#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
Line 379 ⟶ 380:
if (setmodtime(argv[i])) r = 1;
return r;
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<syntaxhighlight lang="csharp">using System;
using System.IO;
 
Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now);</syntaxhighlight>
 
=={{header|C++}}==
compiled with g++ -lboost_filesystem <sourcefile> -o <destination file>
<langsyntaxhighlight lang="cpp">#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>
Line 407 ⟶ 416:
return 2 ;
}
}</langsyntaxhighlight>
 
=={{header|C sharp|C#}}==
 
<lang csharp>using System;
using System.IO;
 
Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now);</lang>
 
=={{header|Clojure}}==
<langsyntaxhighlight lang="lisp">(import '(java.io File)
'(java.util Date))
 
Line 425 ⟶ 426:
 
(.setLastModified (File. "output.txt")
(.lastModified (File. "docs")))</langsyntaxhighlight>
 
=={{header|Common Lisp}}==
Line 432 ⟶ 433:
The write date can be accessed, however, using [http://www.lispworks.com/documentation/HyperSpec/Body/f_file_w.htm file-write-date]:
 
<langsyntaxhighlight lang="lisp">(file-write-date "input.txt")</langsyntaxhighlight>
 
Implementations may, in addition, provide other ways of accessing these file attributes, e.g., POSIX bindings:
Line 440 ⟶ 441:
(<code>sb-posix:utime</code> takes an access time and a modification time rather than an array of two times.)
 
<langsyntaxhighlight 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)))</langsyntaxhighlight>
 
=={{header|D}}==
<langsyntaxhighlight lang="d">import std.stdio;
import std.file: getTimes, setTimes, SysTime;
 
Line 457 ⟶ 458:
writeln(fileAccessTime, "\n", fileModificationTime);
setTimes(fname, fileAccessTime, fileModificationTime);
}</langsyntaxhighlight>
For Windows systems there is also getTimesWin(),
that gives the file creation time too.
 
=={{header|Delphi}}==
<langsyntaxhighlight Delphilang="delphi">function GetModifiedDate(const aFilename: string): TDateTime;
var
hFile: Integer;
Line 477 ⟶ 478:
begin
FileSetDate(aFileName, DateTimeToFileDate(aDateTime));
end;</langsyntaxhighlight>
 
=={{header|E}}==
Line 487 ⟶ 488:
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.
 
<langsyntaxhighlight lang="e">def strdate(date) {
return E.toString(<unsafe:java.util.makeDate>(date))
}
Line 502 ⟶ 503:
 
test("file", <file:output.txt>)
test("directory", <file:docs>)</langsyntaxhighlight>
 
=={{header|Emacs Lisp}}==
<lang Lisp>(nth 5 (file-attributes "input.txt")) ;; mod date+time
 
(set-file-times "input.txt") ;; to current-time
(set-file-times "input.txt"
(encode-time 0 0 0 1 1 2014)) ;; to given date+time</lang>
 
<code>set-file-times</code> sets both the access time and modification time of the file. Time values are in the usual Emacs list form.
Emacs file name handler magic applies to both <code>file-attributes</code> and <code>set-file-times</code> so they can act on "remote" files too.
 
File visiting buffers record the modification time of the file so as to guard against changes by another program. <code>set-file-times</code> from within Emacs doesn't update those buffer times and so looks like an external change.
 
=={{header|Elixir}}==
Line 531 ⟶ 520:
ctime: {{2016, 3, 7}, {23, 12, 35}}, gid: 0, inode: 0, links: 1,
major_device: 3, minor_device: 0, mode: 33206,
mtime: {{2016, 3, 7}, {23, 12, 35}}, size: 45, type: :regular, uid: 0}</lang>
</pre>
 
=={{header|Emacs Lisp}}==
<syntaxhighlight lang="lisp">(nth 5 (file-attributes "input.txt")) ;; mod date+time
 
(set-file-times "input.txt") ;; to current-time
(set-file-times "input.txt"
(encode-time 0 0 0 1 1 2014)) ;; to given date+time</syntaxhighlight>
 
<code>set-file-times</code> sets both the access time and modification time of the file. Time values are in the usual Emacs list form.
Emacs file name handler magic applies to both <code>file-attributes</code> and <code>set-file-times</code> so they can act on "remote" files too.
 
File visiting buffers record the modification time of the file so as to guard against changes by another program. <code>set-file-times</code> from within Emacs doesn't update those buffer times and so looks like an external change.
 
=={{header|Erlang}}==
 
<syntaxhighlight lang="erlang">
<lang Erlang>
-module( file_modification_time ).
 
Line 548 ⟶ 549:
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()} ).
</syntaxhighlight>
</lang>
 
=={{header|F_Sharp|F#}}==
<langsyntaxhighlight lang="fsharp">open System
open System.IO
 
Line 558 ⟶ 559:
Console.WriteLine(File.GetLastWriteTime(args.[0]))
File.SetLastWriteTime(args.[0], DateTime.Now)
0</langsyntaxhighlight>
 
=={{header|Factor}}==
<langsyntaxhighlight lang="factor">"foo.txt" file-info modified>> .</langsyntaxhighlight>
Setting the modified time is not cross-platform, so here's a Unix version.
<langsyntaxhighlight lang="factor">USE: io.files.info.unix
 
"foo.txt" now 2 hours time+ set-file-modified-time</langsyntaxhighlight>
 
=={{header|Fortran}}==
Line 571 ⟶ 572:
 
=={{header|FreeBASIC}}==
<langsyntaxhighlight lang="freebasic">' FB 1.05.0 Win64
 
' This example is taken directly from the FB documentation (see [http://www.freebasic.net/wiki/wikka.php?wakka=KeyPgFiledatetime])
Line 590 ⟶ 591:
End If
 
Sleep</langsyntaxhighlight>
 
Sample input/output:
Line 600 ⟶ 601:
File last modified: 2016-09-07 05:39 AM
</pre>
 
=={{header|Frink}}==
Frink runs on a Java Virtual Machine (JVM) and can use any of its methods. The underlying code returns the modification time as the number of milliseconds since 1970-01-01 00:00 UTC. The following converts between Frink's human-friendly time systems and the milliseconds since the epoch.
<syntaxhighlight lang="frink">f = newJava["java.io.File", "FileModificationTime.frink"]
epoch = #1970 UTC#
f.setLastModified[(#2022-01-01 5:00 AM# - epoch) / ms]
println[f.lastModified[] ms + epoch]</syntaxhighlight>
{{out}}
<pre>
AD 2022-01-01 AM 05:00:00.000 (Sat) Mountain Standard Time
</pre>
 
=={{header|FutureBasic}}==
<syntaxhighlight lang="futurebasic">
CFURLRef desktopURL = fn FileManagerURLForDirectory( NSDesktopDirectory, NSUserDomainMask )
CFURLRef url = fn URLByAppendingPathComponent( desktopURL, @"file.txt" )
CFDictionaryRef dict = fn FileManagerAttributesOfItemAtURL( url )
 
print dict[@NSFileModificationDate] // Read file's current date
 
// Reset file date to current
fn FileManagerSetAttributesOfItemAtURL( CFURLRef url, @{NSFileModificationDate:fn DateNow )
</syntaxhighlight>
 
 
=={{header|Gambas}}==
<langsyntaxhighlight lang="gambas">' There is no built in command in Gambas to 'set' the modification time of a file
' A shell call to 'touch' would do it
 
Line 610 ⟶ 635:
Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 617 ⟶ 642:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 643 ⟶ 668:
os.Chtimes(filename, atime, mtime)
fmt.Println("mod time now:", mtime)
}</langsyntaxhighlight>
 
=={{header|GUISS}}==
Line 650 ⟶ 675:
In this example, we get the date and timestamp for the file Foobar.txt.
 
<langsyntaxhighlight lang="guiss">Start,My Documents,Rightclick:Icon:Foobar.txt,Properties</langsyntaxhighlight>
 
=={{header|Haskell}}==
 
<langsyntaxhighlight lang="haskell">import System.Posix.Files
import System.Posix.Time
 
Line 662 ⟶ 687:
curTime <- epochTime
setFileTimes filename atime curTime -- keep atime unchanged
-- set mtime to current time</langsyntaxhighlight>
 
Alternative (only gets modification time):
<langsyntaxhighlight lang="haskell">import System.Directory
import System.Time
 
do ct <- getModificationTime filename
cal <- toCalendarTime ct
putStrLn (calendarTimeToString cal)</langsyntaxhighlight>
 
=={{header|HicEst}}==
<langsyntaxhighlight lang="hicest">CHARACTER timestamp*18
 
timestamp = ' ' ! blank timestamp will read:
Line 679 ⟶ 704:
 
timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp)</langsyntaxhighlight>
 
=={{header|Icon}} and {{header|Unicon}}==
Icon doesn't support 'stat' or 'utime'; however,
information can be obtained by use of the system function to access command line.
<syntaxhighlight lang="unicon">
<lang Unicon>
every dir := !["./","/"] do {
if i := stat(f := dir || "input.txt") then {
Line 693 ⟶ 718:
}
else stop("failure to stat ",f)
}</langsyntaxhighlight>
Notes:
* Icon and Unicon accept both / and \ for directory separators.
Line 701 ⟶ 726:
=={{header|J}}==
The standard file access library only supports reading the file modification time.
<langsyntaxhighlight lang="j"> load 'files'
fstamp 'input.txt'
2009 8 24 20 34 30</langsyntaxhighlight>
It is possible to set the time but it has to be done through OS specific external calls.
 
=={{header|Java}}==
<syntaxhighlight lang ="java">import java.io.File;
</syntaxhighlight>
<syntaxhighlight lang="java">
public static void main(String[] args) {
File file = new File("file.txt");
/* get */
/* returns '0' if the file does not exist */
System.out.printf("%tD %1$tT%n", file.lastModified());
/* set */
file.setLastModified(System.currentTimeMillis());
}
</syntaxhighlight>
<pre>
05/11/23 11:56:58
</pre>
<br />
An alternate demonstration
<syntaxhighlight lang="java">import java.io.File;
import java.util.Date;
public class FileModificationTimeTest {
Line 726 ⟶ 768:
test("directory", new File("docs"));
}
}</langsyntaxhighlight>
 
=={{header|JavaScript}}==
{{works with|JScript}}
Get only.
<langsyntaxhighlight lang="javascript">var fso = new ActiveXObject("Scripting.FileSystemObject");
var f = fso.GetFile('input.txt');
var mtime = f.DateLastModified;</langsyntaxhighlight>
The following works in all browsers, including IE10.
<langsyntaxhighlight lang="javascript">var file = document.getElementById("fileInput").files.item(0);
var last_modified = file.lastModifiedDate;</langsyntaxhighlight>
 
=={{header|Jsish}}==
Getting the mod time is a builtin. Setting the time is currently not, so ''touch'' is used here.
 
A C extension could provide access to the ''utime'' system call if desired.
 
<syntaxhighlight lang="javascript">/* File modification times, in Jsi */
 
var fileTime = File.mtime('fileModificationTime.jsi');
puts("Last mod time was: ", strftime(fileTime * 1000));
 
exec('touch fileModificationTime.jsi');
 
fileTime = File.mtime('fileModificationTime.jsi');
puts("Mod time now: ", strftime(fileTime * 1000));</syntaxhighlight>
 
{{out}}
<pre>prompt$ jsish fileModificationTime.jsi
Last mod time was: 2019-05-08 13:21:10
Mod time now: 2019-05-08 13:23:35</pre>
 
=={{header|Julia}}==
<syntaxhighlight lang="julia">using Dates
{{works with|Julia|0.6}}
 
<lang julia>fname, _ = mktemp()
 
println("The modification time of $fname is ", Dates.unix2datetime(mtime(fname)))
println("\nTouch this file.")
touch(fname)
println("The modification time of $fname is now ", Dates.unix2datetime(mtime(fname)))</langsyntaxhighlight>
 
=={{header|Kotlin}}==
<langsyntaxhighlight lang="scala">// version 1.0.6
 
import java.io.File
Line 762 ⟶ 824:
println("%tc".format(lastModified()))
}
}</langsyntaxhighlight>
 
=={{header|Lang}}==
{{libheader|lang-io-module}}
<syntaxhighlight lang="lang">
# Load the IO module
# Replace "<pathToIO.lm>" with the location where the io.lm Lang module was installed to without "<" and ">"
ln.loadModule(<pathToIO.lm>)
 
$file = [[io]]::fp.openFile(input.txt)
 
$modTime = [[io]]::fp.getModificationDate($file)
fn.println(Mod Time: $modTime)
 
[[io]]::fp.setModificationDate($file, fn.currentTimeMillis())
 
$modTime = [[io]]::fp.getModificationDate($file)
fn.println(Mod Time now: $modTime)
 
[[io]]::fp.closeFile($file)
</syntaxhighlight>
 
=={{header|Lasso}}==
Line 768 ⟶ 850:
 
File modification date is updated on save of file.
<langsyntaxhighlight Lassolang="lasso">local(f) = file('input.txt')
handle => { #f->close }
#f->modificationDate->format('%-D %r')
// result: 12/2/2010 11:04:15 PM</langsyntaxhighlight>
 
=={{header|Lua}}==
<langsyntaxhighlight lang="lua">require "lfs"
local attributes = lfs.attributes("input.txt")
if attributes then
Line 786 ⟶ 868:
else
print(path .. " does not exist.")
end</langsyntaxhighlight>
 
=={{header|M2000 Interpreter}}==
Most of the file statements/functions use current directory as path.
 
<syntaxhighlight lang="m2000 interpreter">
<lang M2000 Interpreter>
Module CheckIt {
\\ without *for wide output* we open for ANSI (1 byte per character)
Line 797 ⟶ 880:
Close #f
Print file.stamp("afile") 'it is a number in VB6 date format.
date k=file.stamp("afile", -2) // Version 12 has date type, convert number or string to date type
print k // this has type date but print as string using default system locale date and time format
\\ day format as for Greece
Print Str$(File.Stamp("afile"),"hh:nn:ss dd/mm/yyyy") , "utc write time - by default"
Line 805 ⟶ 890:
}
Checkit
</syntaxhighlight>
</lang>
 
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Get file modification time:
<langsyntaxhighlight Mathematicalang="mathematica"> FileDate["file","Modification"]</langsyntaxhighlight>
results is returned in format: {year,month,day,hour,minute,second}. Setting file modification time:
<langsyntaxhighlight Mathematicalang="mathematica"> SetFileDate["file",date,"Modification"]</langsyntaxhighlight>
where date is specified as {year,month,day,hour,minute,second}.
 
=={{header|MATLAB}} / {{header|Octave}}==
 
<langsyntaxhighlight Matlablang="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 </langsyntaxhighlight>
 
Modifying of file access time can be done through system calls:
 
<langsyntaxhighlight Matlablang="matlab"> system('touch -t 201002032359.59 output.txt'); </langsyntaxhighlight>
 
=={{header|MAXScript}}==
MAXScript has no method to set the mod time
<langsyntaxhighlight 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"</langsyntaxhighlight>
 
=={{header|Modula-3}}==
<langsyntaxhighlight lang="modula3">MODULE ModTime EXPORTS Main;
 
IMPORT IO, Fmt, File, FS, Date, OSError;
Line 858 ⟶ 943:
| OSError.E => IO.Put("Error: Failed to get file status.\n");
END;
END ModTime.</langsyntaxhighlight>
{{Out}}
<pre>
Line 864 ⟶ 949:
</pre>
This program sets the modification time to any value we wish:
<langsyntaxhighlight lang="modula3">MODULE SetModTime EXPORTS Main;
 
IMPORT Date, FS;
Line 885 ⟶ 970:
 
FS.SetModificationTime("test.txt", Date.ToTime(date));
END SetModTime.</langsyntaxhighlight>
We can see the output with the Unix command <tt>stat</tt>
{{Out}}
Line 894 ⟶ 979:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 923 ⟶ 1,008:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 936 ⟶ 1,021:
 
=={{header|NewLISP}}==
<langsyntaxhighlight NewLISPlang="newlisp">;; print modification time
(println (date (file-info "input.txt" 6)))
 
;; set modification time to now (Unix)
(! "touch -m input.txt")</langsyntaxhighlight>
 
=={{header|Nim}}==
<langsyntaxhighlight lang="nim">import os, strutils, times
let accTime = getLastAccessTime("filename")
let modTime = getLastModificationTime("filename")
 
if paramCount() == 0: quit(QuitSuccess)
import posix
let fileName = paramStr(1)
var unixAccTime = Timeval(tv_sec: int(accTime))
var unixModTime = Timeval(tv_sec: int(modTime))
 
# SetGet theand display last modification time.
var mtime = fileName.getLastModificationTime()
unixModTime.tv_sec = 0
echo "File \"$1\" last modification time: $2".format(fileName, mtime.format("YYYY-MM-dd HH:mm:ss"))
 
# Change last modification time to current time.
var times = [unixAccTime, unixModTime]
fileName.setLastModificationTime(now().toTime())</syntaxhighlight>
discard utimes("filename", addr(times))
 
# Set the access and modification times to the current time
discard utimes("filename", nil)</lang>
 
=={{header|Objeck}}==
Get only
 
<langsyntaxhighlight lang="objeck">use System.IO.File;
 
class Program {
Line 969 ⟶ 1,049:
File->ModifiedTime("file_mod.obs")->ToString()->PrintLine();
}
}</langsyntaxhighlight>
 
=={{header|Objective-C}}==
 
<langsyntaxhighlight lang="objc">NSFileManager *fm = [NSFileManager defaultManager];
 
// Pre-OS X 10.5
Line 983 ⟶ 1,063:
NSLog(@"%@", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileModificationDate]);
[fm setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
ofItemAtPath:@"input.txt" error:NULL];</langsyntaxhighlight>
 
=={{header|OCaml}}==
<langsyntaxhighlight lang="ocaml">#load "unix.cma";;
open Unix;;
let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)
Line 992 ⟶ 1,072:
utimes filename (stat filename).st_atime (time ());;
(* keep atime unchanged
set mtime to current time *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 998 ⟶ 1,078:
Get only :
 
<langsyntaxhighlight Oforthlang="oforth">File new("myfile.txt") modified</langsyntaxhighlight>
 
=={{header|OpenEdge/Progress}}==
The file modified time can only be read.
 
<langsyntaxhighlight lang="progress">FILE-INFO:FILE-NAME = 'c:/temp'.
MESSAGE
STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX</langsyntaxhighlight>
 
=={{header|Oz}}==
Getting the modification time:
<langsyntaxhighlight 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</langsyntaxhighlight>
 
Setting the modification time is not possible,
Line 1,025 ⟶ 1,105:
{{works with|Perl|5}}
 
<langsyntaxhighlight lang="perl">my $mtime = (stat($file))[9]; # seconds since the epoch
 
# you should use the more legible version below:
Line 1,033 ⟶ 1,113:
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time</langsyntaxhighlight>
 
=={{header|Perl 6Phix}}==
<!--<syntaxhighlight lang="phix">(notonline)-->
{{Works with|rakudo|2018.03}}
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o
<lang perl6>use NativeCall;
-- (however get as per the JavaScript entry above might be doable if needed)</span>
 
<span style="color: #008080;">constant</span> <span style="color: #000000;">filename</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"test.txt"</span>
class utimbuf is repr('CStruct') {
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">get_file_date</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
has int $.actime;
has int $.modtime;
<span style="color: #008080;">include</span> <span style="color: #004080;">timedate</span><span style="color: #0000FF;">.</span><span style="color: #000000;">e</span>
 
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">format_timedate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_file_date</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">))</span>
submethod BUILD(:$atime, :$mtime) {
<span style="color: #004080;">bool</span> <span style="color: #000000;">res</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">set_file_date</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">)</span>
$!actime = $atime;
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">format_timedate</span><span style="color: #0000FF;">(</span><span style="color: #7060A8;">get_file_date</span><span style="color: #0000FF;">(</span><span style="color: #000000;">filename</span><span style="color: #0000FF;">))</span>
$!modtime = $mtime.to-posix[0].round;
<!--</syntaxhighlight>-->
}
{{out}}
}
<pre>
 
{2019,5,2,14,46,40}
sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}
"2:46pm Thursday May 02nd, 2019"
 
"12:25pm Wednesday May 08nd, 2019"
sub MAIN (Str $file) {
</pre>
my $mtime = $file.IO.modified orelse .die;
 
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.
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$filename = 'input.txt';
 
Line 1,070 ⟶ 1,143:
time(), // set mtime to current time
fileatime($filename)); // keep atime unchanged
?></langsyntaxhighlight>
 
=={{header|PicoLisp}}==
<langsyntaxhighlight PicoLisplang="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"</langsyntaxhighlight>
{{Out}}
<pre>2010-02-20 15:46:37</pre>
 
=={{header|Pop11}}==
<langsyntaxhighlight lang="pop11">;;; Print modification time (seconds since Epoch)
sysmodtime('file') =></langsyntaxhighlight>
 
=={{header|PowerShell}}==
<langsyntaxhighlight lang="powershell">
$modificationTime = (Get-ChildItem file.txt).LastWriteTime
Set-ItemProperty file.txt LastWriteTime (Get-Date)
Line 1,095 ⟶ 1,168:
$CreationTime = (Get-ChildItem file.txt).CreationTime
Set-ItemProperty file.txt CreationTime(Get-Date)
</syntaxhighlight>
</lang>
 
You can also use alternates to get UTC time:
Line 1,103 ⟶ 1,176:
 
=={{header|PureBasic}}==
<langsyntaxhighlight PureBasiclang="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))</langsyntaxhighlight>
 
=={{header|Python}}==
<langsyntaxhighlight lang="python">import os
 
#Get modification time:
Line 1,120 ⟶ 1,193:
 
#Set the access and modification times to the current time:
os.utime('path', None)</langsyntaxhighlight>
 
=={{header|R}}==
See [http://tolstoy.newcastle.edu.au/R/e4/devel/08/02/0639.html this R-devel mailing list thread] for more information.
<langsyntaxhighlight lang="r"># Get the value
file.info(filename)$mtime
 
Line 1,130 ⟶ 1,203:
shell("copy /b /v filename +,,>nul")
# and on Unix (untested)
shell("touch -m filename")</langsyntaxhighlight>
 
=={{header|Racket}}==
 
<langsyntaxhighlight lang="racket">
#lang racket
(file-or-directory-modify-seconds "foo.rkt")
</syntaxhighlight>
</lang>
 
=={{header|Raku}}==
(formerly Perl 6)
{{Works with|rakudo|2018.03}}
<syntaxhighlight lang="raku" line>use NativeCall;
 
class utimbuf is repr('CStruct') {
has int $.actime;
has int $.modtime;
 
submethod BUILD(:$atime, :$mtime) {
$!actime = $atime;
$!modtime = $mtime.to-posix[0].round;
}
}
 
sub sysutime(Str, utimbuf --> int32) is native is symbol('utime') {*}
 
sub MAIN (Str $file) {
my $mtime = $file.IO.modified orelse .die;
 
my $ubuff = utimbuf.new(:atime(time),:mtime($mtime));
 
sysutime($file, $ubuff);
}</syntaxhighlight>
Sets the last access time to now,
while restoring the modification time to what it was before.
 
=={{header|RapidQ}}==
<langsyntaxhighlight lang="rapidq">name$ = DIR$("input.txt", 0)
PRINT "File date: "; FileRec.Date
PRINT "File time: "; FileRec.Time</langsyntaxhighlight>
 
=={{header|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.
<syntaxhighlight lang="realbasic">
<lang REALbasic>
Function getModDate(f As FolderItem) As Date
Return f.ModificationDate
End Function</langsyntaxhighlight>
 
=={{header|REXX}}==
{{works with|Regina REXX}}
The REXX language has no facility to update a file's modification time.
<langsyntaxhighlight lang="rexx">/*REXX program obtains and displays a file's time of modification. */
parse arg $ . /*obtain required argument from the CL.*/
if $=='' then do; say "***error*** no filename was specified."; exit 13; end
Line 1,163 ⟶ 1,263:
say 'timestamp of last modification: ' q /*display the modification time info. */
/*stick a fork in it, we're all done. */
</syntaxhighlight>
</lang>
'''output''' &nbsp; when using the file ID for this particular REXX program (source file): &nbsp; <tt> FILEMTIME.REX </tt>
<pre>
Line 1,171 ⟶ 1,271:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
see GetFileInfo( "test.ring" )
Line 1,181 ⟶ 1,281:
aInfo = split(cLine," ")
return aInfo
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,193 ⟶ 1,293:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">#Get modification time:
modtime = File.mtime('filename')
 
Line 1,203 ⟶ 1,303:
 
#Set the access and modification times to the current time:
File.utime(nil, nil, 'path')</langsyntaxhighlight>
 
=={{header|Run BASIC}}==
<langsyntaxhighlight lang="runbasic">files #f, DefaultDir$ + "\*.*" ' all files in the default directory
print "hasanswer: ";#f HASANSWER() ' does it exist
Line 1,228 ⟶ 1,328:
print
end if
next</langsyntaxhighlight>
 
=={{header|Seed7Rust}}==
<syntaxhighlight lang="rust">use std::fs;
<lang seed7>$ include "seed7_05.s7i";
include "osfiles.s7i";
include "time.s7i";
 
fn main() -> std::io::Result<()> {
const proc: main is func
let metadata = fs::metadata("foo.txt")?;
local
var time: modificationTime is time.value;
begin
modificationTime := getMTime("data.txt");
setMTime("data.txt", modificationTime);
end func;</lang>
 
if let Ok(time) = metadata.accessed() {
=={{header|Sidef}}==
println!("{:?}", time);
<lang ruby>var file = File.new(__FILE__);
} else {
say file.stat.mtime; # seconds since the epoch
println!("Not supported on this platform");
 
}
# keep atime unchanged
Ok(())
# set mtime to current time
}
file.utime(file.stat.atime, Time.now);</lang>
</syntaxhighlight>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import java.io.File
import java.util.Date
 
Line 1,270 ⟶ 1,364:
// main
List(new File("output.txt"), new File("docs")).foreach(test)
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<syntaxhighlight 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;</syntaxhighlight>
 
=={{header|Sidef}}==
<syntaxhighlight lang="ruby">var file = File.new(__FILE__);
say file.stat.mtime; # seconds since the epoch
 
# keep atime unchanged
# set mtime to current time
file.utime(file.stat.atime, Time.now);</syntaxhighlight>
 
=={{header|Slate}}==
Line 1,276 ⟶ 1,391:
This code gets a raw value:
 
<langsyntaxhighlight lang="slate">slate[1]> (File newNamed: 'LICENSE') fileInfo modificationTimestamp.
1240349799</langsyntaxhighlight>
 
=={{header|Smalltalk}}==
<langsyntaxhighlight lang="smalltalk">|a|
a := File name: 'input.txt'.
(a lastModifyTime) printNl.</langsyntaxhighlight>
 
=={{header|Standard ML}}==
<langsyntaxhighlight 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 ()))</langsyntaxhighlight>
 
=={{header|Tcl}}==
Assuming that the variable <tt>filename</tt> holds the name of the file...
<langsyntaxhighlight lang="tcl"># Get the modification time:
set timestamp [file mtime $filename]
 
# Set the modification time to ‘now’:
file mtime $filename [clock seconds]</langsyntaxhighlight>
 
=={{header|TUSCRIPT}}==
TUSCRIPT does not allow to modify/set the timestamp of a file,
but it is able to read it:
<langsyntaxhighlight lang="tuscript">
$$ MODE TUSCRIPT
file="rosetta.txt"
Line 1,309 ⟶ 1,424:
modified=MODIFIED (file)
PRINT "file ",file," last modified: ",modified
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,324 ⟶ 1,439:
 
To get the timestamp in seconds since the epoch:
<langsyntaxhighlight lang="bash">T=`stat -c %Y $F`</langsyntaxhighlight>
 
To get the timestamp in human-readable format:
<langsyntaxhighlight lang="bash">T=`stat -c %y $F`</langsyntaxhighlight>
 
Note that the only difference between the above examples is capital Y vs lower-case y.
Line 1,334 ⟶ 1,449:
 
To set file F to time T, where T is in a human-readable format:
<langsyntaxhighlight lang="bash"># Note the quotation marks -- very important!
T="2000-01-01 01:02:03.040506070 -0800"
touch -c -d "$T" $F</langsyntaxhighlight>
 
To set file F to time T, where T is in the format [[CC]YY]MMDDhhmm[.ss] (the square brackets mark optional parts):
<langsyntaxhighlight lang="bash">T=200102030405.06
touch -c -t $T $F</langsyntaxhighlight>
 
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:
<langsyntaxhighlight lang="bash">T=02030405
touch -c -t $T $F</langsyntaxhighlight>
 
If no time is specified, then the timestamp is set to the current time:
<syntaxhighlight lang ="bash">touch -c $F</langsyntaxhighlight>
 
There are, of course, other ways to do both tasks -- for example, one could use <code>ls -l --time-style=full-iso</code> and then process the resulting list with some other tool (e.g. [[awk]] or [[Perl]]).
Line 1,355 ⟶ 1,470:
=={{header|Ursa}}==
{{works with|Cygnus/X Ursa}}
<langsyntaxhighlight lang="ursa">decl java.util.Date d
decl file f
 
Line 1,362 ⟶ 1,477:
out d endl console
 
f.setlastmodified 10</langsyntaxhighlight>
 
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
VBScript provides no way to set the last modification time. It does allow you to retrieve it, however.
<syntaxhighlight lang="vbscript">
<lang VBScript>
WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified
</syntaxhighlight>
</lang>
 
=={{header|Vedit macro language}}==
Display file's last modification time as number of seconds since midnight.
<langsyntaxhighlight lang="vedit">Num_Type(File_Stamp_Time("input.txt"))</langsyntaxhighlight>
 
Displays file's last modification date and time as a string.
<langsyntaxhighlight lang="vedit">File_Stamp_String(10, "input.txt")
Reg_Type(10)</langsyntaxhighlight>
Vedit Macro Language has <span class="plainlinks">[http://seoph1.cafe24.com/wordpress/ <span style="color:black;font-weight:normal; text-decoration:none!important; background:none!important; text-decoration:none;">Blog in SEO</span>] no method to set the modification time
 
Line 1,384 ⟶ 1,499:
 
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Dim file As New IO.FileInfo("test.txt")
 
'Creation Time
Line 1,396 ⟶ 1,511:
'Access Time
Dim accessTime = file.LastAccessTime
file.LastAccessTime = accessTime.AddHours(1)</langsyntaxhighlight>
 
=={{header|Wren}}==
{{trans|C}}
{{libheader|POSIX}}
{{libheader|Wren-date}}
As there is currently no way for Wren-cli to get or set file modification times, we instead use an embedded script so the C host can do this for us.
<syntaxhighlight lang="wren">/* File_modification_time_wren */
 
import "./date" for Date
 
foreign class Stat {
construct new(fileName) {}
 
foreign atime
foreign mtime
}
 
foreign class Utimbuf {
construct new(actime, modtime) {}
 
foreign utime(fileName)
}
 
// gets a Date object from a Unix time in seconds
var UT2Date = Fn.new { |ut| Date.unixEpoch.addSeconds(ut) }
 
Date.default = "yyyy|-|mm|-|dd| |hh|:|MM|:|ss" // default format for printing
 
var fileName = "temp.txt"
var st = Stat.new(fileName)
System.print("'%(fileName)' was last modified on %(UT2Date.call(st.mtime)).")
 
var utb = Utimbuf.new(st.atime, 0) // atime unchanged, mtime = current time
if (utb.utime(fileName) < 0) {
System.print("There was an error changing the file modification time.")
return
}
st = Stat.new(fileName) // update info
System.print("File modification time changed to %(UT2Date.call(st.mtime)).")</syntaxhighlight>
<br>
We now embed this in the following C program, build and run it:
<syntaxhighlight lang="c">/* gcc File_modification_time.c -o File_modification_time -lwren -lm */
 
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utime.h>
#include "wren.h"
 
/* Stat functions */
 
void Stat_allocate(WrenVM* vm) {
struct stat *pStat = (struct stat*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct stat));
const char *filename = wrenGetSlotString(vm, 1);
if (stat(filename, pStat) < 0) {
perror(filename);
exit(1);
}
}
 
void Stat_atime(WrenVM* vm) {
struct stat *pStat = (struct stat*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)pStat->st_atime);
}
 
void Stat_mtime(WrenVM* vm) {
struct stat *pStat = (struct stat*)wrenGetSlotForeign(vm, 0);
wrenSetSlotDouble(vm, 0, (double)pStat->st_mtime);
}
 
/* Utimbuf functions */
 
void Utimbuf_allocate(WrenVM* vm) {
struct utimbuf *pUtimbuf = (struct utimbuf*)wrenSetSlotNewForeign(vm, 0, 0, sizeof(struct utimbuf));
time_t actime = (time_t)wrenGetSlotDouble(vm, 1);
if (!actime) actime = time(NULL);
pUtimbuf->actime = actime;
time_t modtime = (time_t)wrenGetSlotDouble(vm, 2);
if (!modtime) modtime = time(NULL);
pUtimbuf->modtime = modtime;
}
 
void Utimbuf_utime(WrenVM* vm) {
const struct utimbuf *pUtimbuf = (const struct utimbuf*)wrenGetSlotForeign(vm, 0);
const char *filename = wrenGetSlotString(vm, 1);
int res = utime(filename, pUtimbuf);
wrenSetSlotDouble(vm, 0, (double)res);
}
 
WrenForeignClassMethods bindForeignClass(WrenVM* vm, const char* module, const char* className) {
WrenForeignClassMethods methods;
methods.allocate = NULL;
methods.finalize = NULL;
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Stat") == 0) {
methods.allocate = Stat_allocate;
} else if (strcmp(className, "Utimbuf") == 0) {
methods.allocate = Utimbuf_allocate;
}
}
return methods;
}
 
WrenForeignMethodFn bindForeignMethod(
WrenVM* vm,
const char* module,
const char* className,
bool isStatic,
const char* signature) {
if (strcmp(module, "main") == 0) {
if (strcmp(className, "Stat") == 0) {
if(!isStatic && strcmp(signature, "atime") == 0) return Stat_atime;
if(!isStatic && strcmp(signature, "mtime") == 0) return Stat_mtime;
} else if (strcmp(className, "Utimbuf") == 0) {
if(!isStatic && strcmp(signature, "utime(_)") == 0) return Utimbuf_utime;
}
}
return NULL;
}
 
static void writeFn(WrenVM* vm, const char* text) {
printf("%s", text);
}
 
void errorFn(WrenVM* vm, WrenErrorType errorType, const char* module, const int line, const char* msg) {
switch (errorType) {
case WREN_ERROR_COMPILE:
printf("[%s line %d] [Error] %s\n", module, line, msg);
break;
case WREN_ERROR_STACK_TRACE:
printf("[%s line %d] in %s\n", module, line, msg);
break;
case WREN_ERROR_RUNTIME:
printf("[Runtime Error] %s\n", msg);
break;
}
}
 
char *readFile(const char *fileName) {
FILE *f = fopen(fileName, "r");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
rewind(f);
char *script = malloc(fsize + 1);
size_t ret = fread(script, 1, fsize, f);
if (ret != fsize) printf("Error reading %s\n", fileName);
fclose(f);
script[fsize] = 0;
return script;
}
 
static void loadModuleComplete(WrenVM* vm, const char* module, WrenLoadModuleResult result) {
if( result.source) free((void*)result.source);
}
 
WrenLoadModuleResult loadModule(WrenVM* vm, const char* name) {
WrenLoadModuleResult result = {0};
if (strcmp(name, "random") != 0 && strcmp(name, "meta") != 0) {
result.onComplete = loadModuleComplete;
char fullName[strlen(name) + 6];
strcpy(fullName, name);
strcat(fullName, ".wren");
result.source = readFile(fullName);
}
return result;
}
 
int main(int argc, char **argv) {
WrenConfiguration config;
wrenInitConfiguration(&config);
config.writeFn = &writeFn;
config.errorFn = &errorFn;
config.bindForeignClassFn = &bindForeignClass;
config.bindForeignMethodFn = &bindForeignMethod;
config.loadModuleFn = &loadModule;
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "File_modification_time.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
switch (result) {
case WREN_RESULT_COMPILE_ERROR:
printf("Compile Error!\n");
break;
case WREN_RESULT_RUNTIME_ERROR:
printf("Runtime Error!\n");
break;
case WREN_RESULT_SUCCESS:
break;
}
wrenFreeVM(vm);
free(script);
return 0;
}</syntaxhighlight>
 
{{out}}
Sample output:
<pre>
'temp.txt' was last modified on 2021-12-05 14:14:30.
File modification time changed to 2021-12-05 14:23:42.
</pre>
 
=={{header|zkl}}==
<langsyntaxhighlight lang="zkl">info:=File.info("input.txt");
// -->T(size,last status change time,last mod time,isDir,mode), from stat(2)
info.println();
Time.Date.ctime(info[2]).println();
File.setModTime("input.txt",Time.Clock.mktime(2014,2,1,0,0,0));
File.info("input.txt")[2] : Time.Date.ctime(_).println();</langsyntaxhighlight>
{{Out}}
<pre>
9,476

edits