File modification time: Difference between revisions
m
→{{header|Wren}}: Minor tidy
SqrtNegInf (talk | contribs) m (→{{header|Perl 6}}: POSIX timestamp from Instant 'mtime') |
m (→{{header|Wren}}: Minor tidy) |
||
(27 intermediate revisions by 19 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:
<
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;</
=={{header|ALGOL 68}}==
Definition of the PROC is lifted from the Algol68 Genie documentation.
<
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>
{{Out}}
<pre>-rw-r--r-- 1 pcl pcl 0 2015-08-10 17:57:50.279854695 +0100 WTC_1
Line 45 ⟶ 46:
=={{header|AutoHotkey}}==
<
MsgBox % OutputVar
FileSetTime, 20080101, output.txt
FileGetTime, OutputVar, output.txt
MsgBox % OutputVar</
=={{header|AWK}}==
{{works with|gawk}}
<
BEGIN {
Line 67 ⟶ 68:
close(cmd)
}</
Non-GNU awk's don't have direct access to the filesystem but can execute system-commands.
<
BEGIN { # file modification time on Unix, using stat
fn ="input.txt"
Line 104 ⟶ 105:
cmd="stat " fn
print "#", cmd; system(cmd)
}</
{{out}}
Line 132 ⟶ 133:
=={{header|Batch File}}==
{{works with|Windows NT|4}}
<
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}}
<
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>
=={{header|C}}==
Line 174 ⟶ 175:
{{libheader|POSIX}}
<
#include <stdio.h>
#include <time.h>
Line 200 ⟶ 201:
return 0;
}</
===BSD utimes()===
Line 207 ⟶ 208:
{{libheader|BSD libc}}
<
#include <sys/time.h>
#include <err.h>
Line 230 ⟶ 231:
return 0;
}</
=== POSIX utimensat() ===
Line 238 ⟶ 239:
{{libheader|POSIX}}
{{works with|POSIX|-1.2008}}
<
#include <sys/time.h>
#include <time.h>
Line 267 ⟶ 268:
return 0;
}</
=== Windows ===
Line 273 ⟶ 274:
{{libheader|Win32}}
<
#include <stdio.h>
#include <stdlib.h>
Line 379 ⟶ 380:
if (setmodtime(argv[i])) r = 1;
return r;
}</
=={{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>
<
#include <ctime>
#include <iostream>
Line 407 ⟶ 416:
return 2 ;
}
}</
=={{header|Clojure}}==
<
'(java.util Date))
Line 425 ⟶ 426:
(.setLastModified (File. "output.txt")
(.lastModified (File. "docs")))</
=={{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]:
<
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.)
<
(stat (sb-posix:stat filename))
(mtime (sb-posix:stat-mtime stat)))
(sb-posix:utime filename
(sb-posix:stat-atime stat)
(sb-posix:time)))</
=={{header|D}}==
<
import std.file: getTimes, setTimes, SysTime;
Line 457 ⟶ 458:
writeln(fileAccessTime, "\n", fileModificationTime);
setTimes(fname, fileAccessTime, fileModificationTime);
}</
For Windows systems there is also getTimesWin(),
that gives the file creation time too.
=={{header|Delphi}}==
<
var
hFile: Integer;
Line 477 ⟶ 478:
begin
FileSetDate(aFileName, DateTimeToFileDate(aDateTime));
end;</
=={{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.
<
return E.toString(<unsafe:java.util.makeDate>(date))
}
Line 502 ⟶ 503:
test("file", <file:output.txt>)
test("directory", <file:docs>)</
=={{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}
</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">
-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>
=={{header|F_Sharp|F#}}==
<
open System.IO
Line 558 ⟶ 559:
Console.WriteLine(File.GetLastWriteTime(args.[0]))
File.SetLastWriteTime(args.[0], DateTime.Now)
0</
=={{header|Factor}}==
<
Setting the modified time is not cross-platform, so here's a Unix version.
<
"foo.txt" now 2 hours time+ set-file-modified-time</
=={{header|Fortran}}==
Line 571 ⟶ 572:
=={{header|FreeBASIC}}==
<
' 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</
Sample input/output:
Line 599 ⟶ 600:
c:\windows\system32\kernel32.dll
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}}==
<syntaxhighlight 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
Public Sub Main()
Dim stInfo As Stat = Stat(User.home &/ "Rosetta.txt")
Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss")
End</syntaxhighlight>
Output:
<pre>
Rosetta.txt was last modified 28/05/2017 16:39:39
</pre>
=={{header|Go}}==
<
import (
Line 628 ⟶ 668:
os.Chtimes(filename, atime, mtime)
fmt.Println("mod time now:", mtime)
}</
=={{header|GUISS}}==
Line 635 ⟶ 675:
In this example, we get the date and timestamp for the file Foobar.txt.
<
=={{header|Haskell}}==
<
import System.Posix.Time
Line 647 ⟶ 687:
curTime <- epochTime
setFileTimes filename atime curTime -- keep atime unchanged
-- set mtime to current time</
Alternative (only gets modification time):
<
import System.Time
do ct <- getModificationTime filename
cal <- toCalendarTime ct
putStrLn (calendarTimeToString cal)</
=={{header|HicEst}}==
<
timestamp = ' ' ! blank timestamp will read:
Line 664 ⟶ 704:
timestamp = '19991231235950' ! set timestamp to Millenium - 10 seconds
SYSTEM(FIle="File_modification_time.hic", FileTime=timestamp)</
=={{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">
every dir := !["./","/"] do {
if i := stat(f := dir || "input.txt") then {
Line 678 ⟶ 718:
}
else stop("failure to stat ",f)
}</
Notes:
* Icon and Unicon accept both / and \ for directory separators.
Line 686 ⟶ 726:
=={{header|J}}==
The standard file access library only supports reading the file modification time.
<
fstamp 'input.txt'
2009 8 24 20 34 30</
It is possible to set the time but it has to be done through OS specific external calls.
=={{header|Java}}==
<syntaxhighlight lang
</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 711 ⟶ 768:
test("directory", new File("docs"));
}
}</
=={{header|JavaScript}}==
{{works with|JScript}}
Get only.
<
var f = fso.GetFile('input.txt');
var mtime = f.DateLastModified;</
The following works in all browsers, including IE10.
<
var last_modified = file.lastModifiedDate;</
=={{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
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)))</syntaxhighlight>
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.0.6
import java.io.File
fun main(args: Array<String>) {
val filePath = "input.txt" // or whatever
val file = File(filePath)
with (file) {
println("%tc".format(lastModified()))
// update to current time, say
setLastModified(System.currentTimeMillis())
println("%tc".format(lastModified()))
}
}</syntaxhighlight>
=={{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 752 ⟶ 850:
File modification date is updated on save of file.
<
handle => { #f->close }
#f->modificationDate->format('%-D %r')
// result: 12/2/2010 11:04:15 PM</
=={{header|Lua}}==
<
local attributes = lfs.attributes("input.txt")
if attributes then
Line 770 ⟶ 868:
else
print(path .. " does not exist.")
end</
=={{header|M2000 Interpreter}}==
Most of the file statements/functions use current directory as path.
<syntaxhighlight lang="m2000 interpreter">
Module CheckIt {
\\ without *for wide output* we open for ANSI (1 byte per character)
\\ but here we need it only for the creation of a file
Open "afile" for output as #f
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"
Print Str$(File.Stamp("afile" ,1),"hh:nn:ss dd/mm/yyyy") , "utc write time, 1"
Print Str$(File.Stamp("afile" ,-1),"hh:nn:ss dd/mm/yyyy"), "local write time, -1"
Print Str$(File.Stamp("afile" ,2),"hh:nn:ss dd/mm/yyyy"), "utc creation time, 2"
Print Str$(File.Stamp("afile" ,-2),"hh:nn:ss dd/mm/yyyy"), "local creation time, -2"
}
Checkit
</syntaxhighlight>
=={{header|Mathematica}} / {{header|Wolfram Language}}==
Get file modification time:
<
results is returned in format: {year,month,day,hour,minute,second}. Setting file modification time:
<
where date is specified as {year,month,day,hour,minute,second}.
=={{header|MATLAB}} / {{header|Octave}}==
<
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 </
Modifying of file access time can be done through system calls:
<
=={{header|MAXScript}}==
MAXScript has no method to set the mod time
<
getFileModDate "C:\myFile.txt"</
=={{header|Modula-3}}==
<
IMPORT IO, Fmt, File, FS, Date, OSError;
Line 823 ⟶ 943:
| OSError.E => IO.Put("Error: Failed to get file status.\n");
END;
END ModTime.</
{{Out}}
<pre>
Line 829 ⟶ 949:
</pre>
This program sets the modification time to any value we wish:
<
IMPORT Date, FS;
Line 850 ⟶ 970:
FS.SetModificationTime("test.txt", Date.ToTime(date));
END SetModTime.</
We can see the output with the Unix command <tt>stat</tt>
{{Out}}
Line 859 ⟶ 979:
=={{header|NetRexx}}==
<
options replace format comments java crossref symbols binary
Line 888 ⟶ 1,008:
end
return
</syntaxhighlight>
{{out}}
<pre>
Line 901 ⟶ 1,021:
=={{header|NewLISP}}==
<
(println (date (file-info "input.txt" 6)))
;; set modification time to now (Unix)
(! "touch -m input.txt")</
=={{header|Nim}}==
<
if paramCount() == 0: quit(QuitSuccess)
let fileName = paramStr(1)
#
var mtime = fileName.getLastModificationTime()
echo "File \"$1\" last modification time: $2".format(fileName, mtime.format("YYYY-MM-dd HH:mm:ss"))
# Change last modification time to current time.
fileName.setLastModificationTime(now().toTime())</syntaxhighlight>
=={{header|Objeck}}==
Get only
<syntaxhighlight lang="objeck">use System.IO.File;
class Program {
function : Main(args : String[]) ~ Nil {
File->ModifiedTime("file_mod.obs")->ToString()->PrintLine();
}
}</syntaxhighlight>
=={{header|Objective-C}}==
<
// Pre-OS X 10.5
Line 937 ⟶ 1,063:
NSLog(@"%@", [[fm attributesOfItemAtPath:@"input.txt" error:NULL] fileModificationDate]);
[fm setAttributes:[NSDictionary dictionaryWithObject:[NSDate date] forKey:NSFileModificationDate]
ofItemAtPath:@"input.txt" error:NULL];</
=={{header|OCaml}}==
<
open Unix;;
let mtime = (stat filename).st_mtime;; (* seconds since the epoch *)
Line 946 ⟶ 1,072:
utimes filename (stat filename).st_atime (time ());;
(* keep atime unchanged
set mtime to current time *)</
=={{header|Oforth}}==
Line 952 ⟶ 1,078:
Get only :
<
=={{header|OpenEdge/Progress}}==
The file modified time can only be read.
<
MESSAGE
STRING( FILE-INFO:FILE-MOD-TIME, 'HH:MM:SS' )
VIEW-AS ALERT-BOX</
=={{header|Oz}}==
Getting the modification time:
<
[Path] = {Module.link ['x-oz://system/os/Path.ozf']}
Modified = {Path.mtime "input.txt"} %% posix time
in
{Show {OsTime.localtime Modified}} %% human readable record</
Setting the modification time is not possible,
Line 979 ⟶ 1,105:
{{works with|Perl|5}}
<
# you should use the more legible version below:
Line 987 ⟶ 1,113:
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time</
=={{header|
<!--<syntaxhighlight lang="phix">(notonline)-->
<span style="color: #008080;">without</span> <span style="color: #008080;">js</span> <span style="color: #000080;font-style:italic;">-- file i/o
-- (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>
<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>
<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>
<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>
<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>
<!--</syntaxhighlight>-->
{{out}}
<pre>
{2019,5,2,14,46,40}
"2:46pm Thursday May 02nd, 2019"
"12:25pm Wednesday May 08nd, 2019"
</pre>
=={{header|PHP}}==
<
$filename = 'input.txt';
Line 1,024 ⟶ 1,143:
time(), // set mtime to current time
fileatime($filename)); // keep atime unchanged
?></
=={{header|PicoLisp}}==
<
(and
(info File)
(prinl (stamp (cadr @) (cddr @))) ) # Print date and time in UTC
(call 'touch File) ) # Set modification time to "now"</
{{Out}}
<pre>2010-02-20 15:46:37</pre>
=={{header|Pop11}}==
<
sysmodtime('file') =></
=={{header|PowerShell}}==
<
$modificationTime = (Get-ChildItem file.txt).LastWriteTime
Set-ItemProperty file.txt LastWriteTime (Get-Date)
Line 1,049 ⟶ 1,168:
$CreationTime = (Get-ChildItem file.txt).CreationTime
Set-ItemProperty file.txt CreationTime(Get-Date)
</syntaxhighlight>
You can also use alternates to get UTC time:
Line 1,057 ⟶ 1,176:
=={{header|PureBasic}}==
<
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))</
=={{header|Python}}==
<
#Get modification time:
Line 1,074 ⟶ 1,193:
#Set the access and modification times to the current time:
os.utime('path', None)</
=={{header|R}}==
See [http://tolstoy.newcastle.edu.au/R/e4/devel/08/02/0639.html this R-devel mailing list thread] for more information.
<
file.info(filename)$mtime
Line 1,084 ⟶ 1,203:
shell("copy /b /v filename +,,>nul")
# and on Unix (untested)
shell("touch -m filename")</
=={{header|Racket}}==
<
#lang racket
(file-or-directory-modify-seconds "foo.rkt")
</syntaxhighlight>
=={{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}}==
<
PRINT "File date: "; FileRec.Date
PRINT "File time: "; FileRec.Time</
=={{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">
Function getModDate(f As FolderItem) As Date
Return f.ModificationDate
End Function</
=={{header|REXX}}==
{{works with|Regina REXX}}
The REXX language has no facility to update a file's modification time.
<
parse arg $ . /*obtain required argument from the CL.*/
if $=='' then do; say "***error*** no filename was specified."; exit 13; end
Line 1,117 ⟶ 1,263:
say 'timestamp of last modification: ' q /*display the modification time info. */
/*stick a fork in it, we're all done. */
</syntaxhighlight>
'''output''' when using the file ID for this particular REXX program (source file): <tt> FILEMTIME.REX </tt>
<pre>
For file: FILEMTIM.REX
timestamp of last modification: 2015-05-30 14:22:26
</pre>
=={{header|Ring}}==
<syntaxhighlight lang="ring">
load "stdlib.ring"
see GetFileInfo( "test.ring" )
func GetFileInfo cFile
cOutput = systemcmd("dir /T:W " + cFile )
aList = str2list(cOutput)
cLine = aList[6]
aInfo = split(cLine," ")
return aInfo
</syntaxhighlight>
Output:
<pre>
2017.
08.
27.
10:31
189
test.ring
</pre>
=={{header|Ruby}}==
<
modtime = File.mtime('filename')
Line 1,135 ⟶ 1,303:
#Set the access and modification times to the current time:
File.utime(nil, nil, 'path')</
=={{header|Run BASIC}}==
<
print "hasanswer: ";#f HASANSWER() ' does it exist
Line 1,160 ⟶ 1,328:
print
end if
next</
=={{header|
<syntaxhighlight lang="rust">use std::fs;
fn main() -> std::io::Result<()> {
let metadata = fs::metadata("foo.txt")?;
if let Ok(time) = metadata.accessed() {
println!("{:?}", time);
} else {
println!("Not supported on this platform");
}
Ok(())
}
</syntaxhighlight>
=={{header|Scala}}==
{{libheader|Scala}}
<
import java.util.Date
Line 1,202 ⟶ 1,364:
// main
List(new File("output.txt"), new File("docs")).foreach(test)
}</
=={{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,208 ⟶ 1,391:
This code gets a raw value:
<
1240349799</
=={{header|Smalltalk}}==
<
a := File name: 'input.txt'.
(a lastModifyTime) printNl.</
=={{header|Standard ML}}==
<
(* 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 ()))</
=={{header|Tcl}}==
Assuming that the variable <tt>filename</tt> holds the name of the file...
<
set timestamp [file mtime $filename]
# Set the modification time to ‘now’:
file mtime $filename [clock seconds]</
=={{header|TUSCRIPT}}==
TUSCRIPT does not allow to modify/set the timestamp of a file,
but it is able to read it:
<
$$ MODE TUSCRIPT
file="rosetta.txt"
Line 1,241 ⟶ 1,424:
modified=MODIFIED (file)
PRINT "file ",file," last modified: ",modified
</syntaxhighlight>
{{Out}}
<pre>
Line 1,256 ⟶ 1,439:
To get the timestamp in seconds since the epoch:
<
To get the timestamp in human-readable format:
<
Note that the only difference between the above examples is capital Y vs lower-case y.
Line 1,266 ⟶ 1,449:
To set file F to time T, where T is in a human-readable format:
<
T="2000-01-01 01:02:03.040506070 -0800"
touch -c -d "$T" $F</
To set file F to time T, where T is in the format [[CC]YY]MMDDhhmm[.ss] (the square brackets mark optional parts):
<
touch -c -t $T $F</
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:
<
touch -c -t $T $F</
If no time is specified, then the timestamp is set to the current time:
<syntaxhighlight lang
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,287 ⟶ 1,470:
=={{header|Ursa}}==
{{works with|Cygnus/X Ursa}}
<
decl file f
Line 1,294 ⟶ 1,477:
out d endl console
f.setlastmodified 10</
=={{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">
WScript.Echo CreateObject("Scripting.FileSystemObject").GetFile("input.txt").DateLastModified
</syntaxhighlight>
=={{header|Vedit macro language}}==
Display file's last modification time as number of seconds since midnight.
<
Displays file's last modification date and time as a string.
<
Reg_Type(10)</
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,316 ⟶ 1,499:
{{works with|Visual Basic .NET|9.0+}}
<
'Creation Time
Line 1,328 ⟶ 1,511:
'Access Time
Dim accessTime = file.LastAccessTime
file.LastAccessTime = accessTime.AddHours(1)</
=={{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}}==
<
// -->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();</
{{Out}}
<pre>
|