File modification time: Difference between revisions

m
(Frink)
m (→‎{{header|Wren}}: Minor tidy)
 
(8 intermediate revisions by 7 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#}}==
 
<langsyntaxhighlight lang="csharp">using System;
using System.IO;
 
Console.WriteLine(File.GetLastWriteTime("file.txt"));
File.SetLastWriteTime("file.txt", DateTime.Now);</langsyntaxhighlight>
 
=={{header|C++}}==
compiled with g++ -lboost_filesystem <sourcefile> -o <destination file>
<langsyntaxhighlight lang="cpp">#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>
Line 415 ⟶ 416:
return 2 ;
}
}</langsyntaxhighlight>
 
=={{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|Elixir}}==
Line 523 ⟶ 524:
 
=={{header|Emacs Lisp}}==
<langsyntaxhighlight Lisplang="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</langsyntaxhighlight>
 
<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.
Line 536 ⟶ 537:
=={{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 603 ⟶ 604:
=={{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.
<langsyntaxhighlight lang="frink">f = newJava["java.io.File", "FileModificationTime.frink"]
f.setLastModified[(#2022-01-01epoch 5:00 AM# -= #1970 UTC#) / ms]
f.setLastModified[(#2022-01-01 5:00 AM# - epoch) / ms]
println[f.lastModified[] ms + #1970 UTC#epoch]</langsyntaxhighlight>
{{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 620 ⟶ 635:
Print "Rosetta.txt was last modified " & Format(stInfo.LastModified, "dd/mm/yyy hh:nn:ss")
 
End</langsyntaxhighlight>
Output:
<pre>
Line 627 ⟶ 642:
 
=={{header|Go}}==
<langsyntaxhighlight lang="go">package main
 
import (
Line 653 ⟶ 668:
os.Chtimes(filename, atime, mtime)
fmt.Println("mod time now:", mtime)
}</langsyntaxhighlight>
 
=={{header|GUISS}}==
Line 660 ⟶ 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 672 ⟶ 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 689 ⟶ 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 703 ⟶ 718:
}
else stop("failure to stat ",f)
}</langsyntaxhighlight>
Notes:
* Icon and Unicon accept both / and \ for directory separators.
Line 711 ⟶ 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
</langpre>
<br />
An alternate demonstration
<syntaxhighlight lang="java">import java.io.File;
import java.util.Date;
public class FileModificationTimeTest {
Line 736 ⟶ 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}}==
Line 753 ⟶ 785:
A C extension could provide access to the ''utime'' system call if desired.
 
<langsyntaxhighlight lang="javascript">/* File modification times, in Jsi */
 
var fileTime = File.mtime('fileModificationTime.jsi');
Line 761 ⟶ 793:
 
fileTime = File.mtime('fileModificationTime.jsi');
puts("Mod time now: ", strftime(fileTime * 1000));</langsyntaxhighlight>
 
{{out}}
Line 769 ⟶ 801:
 
=={{header|Julia}}==
<langsyntaxhighlight lang="julia">using Dates
 
fname, _ = mktemp()
Line 776 ⟶ 808:
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 792 ⟶ 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 798 ⟶ 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 816 ⟶ 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 828 ⟶ 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 836 ⟶ 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 889 ⟶ 943:
| OSError.E => IO.Put("Error: Failed to get file status.\n");
END;
END ModTime.</langsyntaxhighlight>
{{Out}}
<pre>
Line 895 ⟶ 949:
</pre>
This program sets the modification time to any value we wish:
<langsyntaxhighlight lang="modula3">MODULE SetModTime EXPORTS Main;
 
IMPORT Date, FS;
Line 916 ⟶ 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 925 ⟶ 979:
 
=={{header|NetRexx}}==
<langsyntaxhighlight NetRexxlang="netrexx">/* NetRexx */
options replace format comments java crossref symbols binary
 
Line 954 ⟶ 1,008:
end
return
</syntaxhighlight>
</lang>
{{out}}
<pre>
Line 967 ⟶ 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
 
if paramCount() == 0: quit(QuitSuccess)
Line 984 ⟶ 1,038:
 
# Change last modification time to current time.
fileName.setLastModificationTime(now().toTime())</langsyntaxhighlight>
 
=={{header|Objeck}}==
Get only
 
<langsyntaxhighlight lang="objeck">use System.IO.File;
 
class Program {
Line 995 ⟶ 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 1,009 ⟶ 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 1,018 ⟶ 1,072:
utimes filename (stat filename).st_atime (time ());;
(* keep atime unchanged
set mtime to current time *)</langsyntaxhighlight>
 
=={{header|Oforth}}==
Line 1,024 ⟶ 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,051 ⟶ 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,059 ⟶ 1,113:
utime(stat($file)->atime, time, $file);
# keep atime unchanged
# set mtime to current time</langsyntaxhighlight>
 
=={{header|Phix}}==
<!--<langsyntaxhighlight Phixlang="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>
Line 1,072 ⟶ 1,126:
<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>
<!--</langsyntaxhighlight>-->
{{out}}
<pre>
Line 1,081 ⟶ 1,135:
 
=={{header|PHP}}==
<langsyntaxhighlight lang="php"><?php
$filename = 'input.txt';
 
Line 1,089 ⟶ 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,114 ⟶ 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,122 ⟶ 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,139 ⟶ 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,149 ⟶ 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" perl6line>use NativeCall;
 
class utimbuf is repr('CStruct') {
Line 1,181 ⟶ 1,235:
 
sysutime($file, $ubuff);
}</langsyntaxhighlight>
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,209 ⟶ 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,217 ⟶ 1,271:
 
=={{header|Ring}}==
<langsyntaxhighlight lang="ring">
load "stdlib.ring"
see GetFileInfo( "test.ring" )
Line 1,227 ⟶ 1,281:
aInfo = split(cLine," ")
return aInfo
</syntaxhighlight>
</lang>
Output:
<pre>
Line 1,239 ⟶ 1,293:
 
=={{header|Ruby}}==
<langsyntaxhighlight lang="ruby">#Get modification time:
modtime = File.mtime('filename')
 
Line 1,249 ⟶ 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,274 ⟶ 1,328:
print
end if
next</langsyntaxhighlight>
 
=={{header|Rust}}==
<langsyntaxhighlight lang="rust">use std::fs;
 
fn main() -> std::io::Result<()> {
Line 1,289 ⟶ 1,343:
Ok(())
}
</syntaxhighlight>
</lang>
 
=={{header|Scala}}==
{{libheader|Scala}}
<langsyntaxhighlight Scalalang="scala">import java.io.File
import java.util.Date
 
Line 1,310 ⟶ 1,364:
// main
List(new File("output.txt"), new File("docs")).foreach(test)
}</langsyntaxhighlight>
 
=={{header|Seed7}}==
<langsyntaxhighlight lang="seed7">$ include "seed7_05.s7i";
include "osfiles.s7i";
include "time.s7i";
Line 1,323 ⟶ 1,377:
modificationTime := getMTime("data.txt");
setMTime("data.txt", modificationTime);
end func;</langsyntaxhighlight>
 
=={{header|Sidef}}==
<langsyntaxhighlight 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);</langsyntaxhighlight>
 
=={{header|Slate}}==
Line 1,337 ⟶ 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,370 ⟶ 1,424:
modified=MODIFIED (file)
PRINT "file ",file," last modified: ",modified
</syntaxhighlight>
</lang>
{{Out}}
<pre>
Line 1,385 ⟶ 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,395 ⟶ 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,416 ⟶ 1,470:
=={{header|Ursa}}==
{{works with|Cygnus/X Ursa}}
<langsyntaxhighlight lang="ursa">decl java.util.Date d
decl file f
 
Line 1,423 ⟶ 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,445 ⟶ 1,499:
 
{{works with|Visual Basic .NET|9.0+}}
<langsyntaxhighlight lang="vbnet">Dim file As New IO.FileInfo("test.txt")
 
'Creation Time
Line 1,457 ⟶ 1,511:
'Access Time
Dim accessTime = file.LastAccessTime
file.LastAccessTime = accessTime.AddHours(1)</langsyntaxhighlight>
 
=={{header|Wren}}==
Line 1,464 ⟶ 1,518:
{{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 */
<lang ecmascript>/* file_mod_time_wren */
 
import "./date" for Date
Line 1,496 ⟶ 1,550:
}
st = Stat.new(fileName) // update info
System.print("File modification time changed to %(UT2Date.call(st.mtime)).")</langsyntaxhighlight>
<br>
We now embed this in the following C program, build and run it:
<langsyntaxhighlight lang="c">/* gcc file_mod_timeFile_modification_time.c -o file_mod_timeFile_modification_time -lwren -lm */
 
#include <sys/stat.h>
Line 1,637 ⟶ 1,691:
WrenVM* vm = wrenNewVM(&config);
const char* module = "main";
const char* fileName = "file_mod_timeFile_modification_time.wren";
char *script = readFile(fileName);
WrenInterpretResult result = wrenInterpret(vm, module, script);
Line 1,653 ⟶ 1,707:
free(script);
return 0;
}</langsyntaxhighlight>
 
{{out}}
Line 1,663 ⟶ 1,717:
 
=={{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