System time
![Task](http://static.miraheze.org/rosettacodewiki/thumb/b/ba/Rcode-button-task-crushed.png/64px-Rcode-button-task-crushed.png)
You are encouraged to solve this task according to the task description, using any language you may know.
Output the system time (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.
See Also
Ada
The following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian. <lang ada>with Ada.Calendar; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones; with Ada.Text_Io; use Ada.Text_Io;
procedure System_Time is
Now : Time := Clock;
begin
Put_line(Image(Date => Now, Time_Zone => -7*60));
end System_Time;</lang>
Output:
2008-01-23 19:14:19
ALGOL 68
<lang algol68>FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,", minutes="2d,", seconds="2d,", day of week="d,", daylight-saving-time flag="dl$; printf((time repr, local time)); printf((time repr, utc time))</lang>
Sample output:
year=2009, month=03, day=12, hours=11, minutes=53, seconds=32, day of week=5, daylight-saving-time flag=0 year=2009, month=03, day=12, hours=01, minutes=53, seconds=32, day of week=5, daylight-saving-time flag=0
AppleScript
<lang AppleScript>display dialog (current date)</lang>
Sample output:
Sunday, August 14, 2011 10:43:57 PM
AutoHotkey
<lang autohotkey>FormatTime, t MsgBox,% t</lang>
Sample output:
4:18 PM Saturday, May 30, 2009
AutoIt
<lang autoit>MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC)</lang>
Sample Output:
Year: 2011,Day: 05,Hour: 09, Minutes: 15, Seconds: 25
AWK
<lang awk>$ awk 'BEGIN{print systime(),strftime()}' 1242401632 Fri May 15 17:33:52 2009</lang>
BASIC
This shows the system time in seconds since midnight. <lang qbasic>PRINT TIMER</lang>
This shows the time in human-readable format (using a 24-hour clock): <lang qbasic>PRINT TIME$</lang>
Batch File
There is no way to get a computer-readable date or time representation in batch files. All output is human-readable and follows the current locale.
Both date
and time
have a /t
argument which makes them output only the value instead of prompting for a new one as well.
<lang dos>date /t
time /t</lang>
Furthermore there are two pseudo-variables %DATE%
and %TIME%
:
<lang dos>echo %DATE% %TIME%</lang>
C
This probably isn't the best way to do this, but it works. It shows system time as "Www Mmm dd hh:mm:ss yyyy", where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. <lang c>#include<time.h>
- include<stdio.h>
- include<stdlib.h>
int main(){
time_t my_time = time(NULL); printf("%s", ctime(&my_time)); return 0;
}</lang>
C++
to be compiled under linux with g++ -lboost_date_time systemtime.cpp -o systemtime( or whatever you like) <lang cpp>#include <iostream>
- include <boost/date_time/posix_time/posix_time.hpp>
int main( ) {
boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ; std::cout << to_simple_string( t ) << std::endl ; return 0 ;
}</lang>
C#
<lang csharp>Console.WriteLine(DateTime.Now);</lang>
Clojure
<lang lisp>(import '[java.util Date])
- the current system date time string
(print (new Date))
- the system time as milliseconds since 1970
(print (. (new Date) getTime))
- or
(print (System/currentTimeMillis)) </lang>
Common Lisp
<lang lisp>(multiple-value-bind (second minute hour day month year) (get-decoded-time)
(format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second))</lang>
D
Clock.now.span in the example below returnes the time-span since 1 Jan 1 A.D. Days are used in the example, but lower units are available, with the lowest being nanoseconds (nanos field). <lang D>Stdout(Clock.now.span.days / 365).newline;</lang>
Delphi
<lang Delphi>lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);</lang>
This populates a label with the date
E
<lang e>println(timer.now())</lang>
The value is the number of milliseconds since 1970.
Erlang
By default, Erlang timestamps are turned in the {megasecs, secs, microsecs} format. <lang erlang>1> os:timestamp(). {1250,222584,635452}</lang>
These can be changed with the calendar module: <lang erlang>2> calendar:now_to_datetime(os:timestamp()). {{2009,8,14},{4,3,24}} 3> calendar:now_to_universal_time(os:timestamp()). {{2009,8,14},{4,3,40}} 4> calendar:now_to_local_time(os:timestamp()). {{2009,8,14},{0,7,01}}</lang>
Note that you will often encounter the function erlang:now/0 giving a time similar to the system time. However, erlang:now/0 may get delayed if the system time changes suddenly (i.e.: coming back from sleep mode). The delay is in place to make sure receive clauses that are millisecond-sensitive do not get false timeouts.
Factor
<lang factor>USE: calendar
now .</lang>
Fantom
DateTime.now
returns the current time, which can then be formatted into different styles. For example, toJava
returns the current time in milliseconds since 1 Jan 1970.
DateTime.nowTicks
returns the number of nanoseconds since 1 Jan 2000 UTC.
<lang fantom> fansh> DateTime.nowTicks 351823905158000000 fansh> DateTime.now 2011-02-24T00:51:47.066Z London fansh> DateTime.now.toJava 1298508885979 </lang>
Forth
Forth's only standard access to the system timers is via DATE&TIME ( -- s m h D M Y ) and MS ( n -- ) which pauses the program for at least n milliseconds. Particular Forth implementations give different access to millisecond and microsecond timers:
<lang forth>[UNDEFINED] MS@ [IF] \ Win32Forth (rolls over daily)
[DEFINED] ?MS [IF] ( -- ms ) : ms@ ?MS ; \ iForth [ELSE] [DEFINED] cputime [IF] ( -- Dusec ) : ms@ cputime d+ 1000 um/mod nip ; \ gforth: Anton Ertl [ELSE] [DEFINED] timer@ [IF] ( -- Dusec ) : ms@ timer@ >us 1000 um/mod nip ; \ bigForth [ELSE] [DEFINED] gettimeofday [IF] ( -- usec sec ) : ms@ gettimeofday 1000 MOD 1000 * SWAP 1000 / + ; \ PFE [ELSE] [DEFINED] counter [IF] : ms@ counter ; \ SwiftForth [ELSE] [DEFINED] GetTickCount [IF] : ms@ GetTickCount ; \ VFX Forth [ELSE] [DEFINED] MICROSECS [IF] : ms@ microsecs 1000 UM/MOD nip ; \ MacForth
[THEN] [THEN] [THEN] [THEN] [THEN] [THEN] [THEN]
MS@ . \ print millisecond counter</lang>
Fortran
In ISO Fortran 90 or later, use the SYSTEM_CLOCK intrinsic subroutine: <lang fortran>integer :: start, stop, rate real :: result
! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!) ! optional 2nd integer argument (COUNT_RATE) is clock cycles per second ! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value call system_clock( start, rate )
result = do_timed_work()
call system_clock( stop )
print *, "elapsed time: ", real(stop - start) / real(rate)</lang>
In ISO Fortran 95 or later, use the CPU_TIME intrinsic subroutine: <lang fortran>real :: start, stop real :: result
! System clock value interpreted as floating point seconds call cpu_time( start )
result = do_timed_work()
call cpu_time( stop )
print *, "elapsed time: ", stop - start</lang>
Go
<lang go>package main import "time" import "fmt"
func main() {
t := time.LocalTime() fmt.Println(t) // default format fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format
}</lang>
Groovy
Solution (based on Java solution. <lang groovy>def nowMillis = new Date().time println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis</lang> Output:
Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == 1243395159250
GUISS
We can only show the clock, but this might not be set to system time:
<lang guiss>Taskbar</lang>
Haskell
<lang haskell>import System.Time import System.Locale
main = do ct <- getClockTime
print ct -- print default format, or cal <- toCalendarTime ct putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal</lang>
or with the time library: <lang haskell>import Data.Time import System.Locale
main = do zt <- getZonedTime
print zt -- print default format, or putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt</lang>
HicEst
<lang HicEst>seconds_since_midnight = TIME() ! msec as fraction
seconds_since_midnight = TIME(Year=yr, Day=day, WeekDay=wday, Gregorian=gday)
! other options e.g. Excel, YYYYMMDD (num or text) </lang>
IDL
The systime() function returns system time either as a formatted string (if the argument is zero or absent) or as a double-precision (floating-point) number of seconds (with fractionals) since 1-Jan-1970 otherwise:
print,systime(0) Wed Feb 10 09:41:14 2010 print,systime(1) 1.2658237e+009
The default format can also be invoked for a different moment in time by passing a different number of elapsed seconds to the routine as a second argument:
print,systime(0,1e9) Sat Sep 08 17:46:40 2001
Otherwise, the system time can be retrieved in Julian dates:
print,systime(/julian),format='(F15.7)' 2455237.9090278
The local time zone is ignored if the utc flag is used:
print,systime() Wed Feb 10 09:50:15 2010 print,systime(/utc) Wed Feb 10 17:50:10 2010
Io
<lang io>Date now println</lang>
Example output: <lang io>2008-08-26 00:15:52 EDT</lang>
Icon and Unicon
<lang Unicon>procedure main()
write("&time - milliseconds of CPU time = ",&time) write("&clock - Time of day as hh:mm:ss (24-hour format) = ",&clock) write("&date - current date in yyyy/mm/dd format = ",&date) write("&dateline - timestamp with day of the week, date, and current time to the minute = ",&dateline)
if find("Unicon",&version) then write("&now - time in seconds since the epoch = ", &now) # Unicon only
end</lang>
Sample output:
&time - milliseconds of CPU time = 0 &clock - Time of day as hh:mm:ss (24-hour format) = 15:56:14 &date - current date in yyyy/mm/dd format = 2011/06/06 &dateline - timestamp with day of the week, date, and current time to the minute = Monday, June 6, 2011 3:56 pm &now - time in seconds since the epoch = 1307400974
J
The external verb 6!:0
returns a six-element floating-point array in which the elements correspond to year, month, day, hour, minute, and second. Fractional portion of second is given to thousandths.
<lang j> 6!:0
2008 1 23 12 52 10.341</lang>
A formatted string representation of the current time can also be returned: <lang j> 6!:0 'YYYY-MM-DD hh:mm:ss.sss' 2009-08-26 10:38:53.171</lang>
Java
<lang java>public class SystemTime{
public static void main(String[] args){ System.out.format("%tc%n", System.currentTimeMillis()); }
}</lang>
Output:
Mon Jun 21 13:02:19 BST 2010
Or using a Date
object:
<lang java>import java.util.Date;
public class SystemTime{
public static void main(String[] args){ Date now = new Date(); System.out.println(now); // string representation
System.out.println(now.getTime()); // Unix time (# of milliseconds since Jan 1 1970) //System.currentTimeMillis() returns the same value }
}</lang>
Alternately, you can use a Calendar object, which allows you to retrieve specific fields of the date.
JavaScript
<lang javascript> console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT
console.log(Date.now()) // => 1306571005417 // Unix epoch </lang>
Liberty BASIC
<lang lb>print time$() 'time now as string "16:21:44" print time$("seconds") 'seconds since midnight as number 32314 print time$("milliseconds") 'milliseconds since midnight as number 33221342 print time$("ms") 'milliseconds since midnight as number 33221342
</lang>
Logo
Other Logo variants might have a built-in command, but UCB Logo must access the Unix shell to get time. <lang logo> to time
output first first shell [date +%s]
end
make "start time wait 300 ; 60ths of a second print time - :start ; 5 </lang>
Lua
<lang lua> print(os.date())</lang>
Mathematica
Different ways of doing this, here are 2 most common: <lang Mathematica>Print[DateList[]] Print[AbsoluteTime[]]</lang> DateList will return the list {year,month,day,hour,minute,second} where all of them are integers except for second; that is a float. AbsoluteTime gives the total number of seconds since january 1st 1900 in your time zone.
MATLAB
<lang MATLAB>>> datestr(now)
ans =
13-Aug-2010 12:59:56</lang>
Modula-3
<lang modula3>MODULE MyTime EXPORTS Main;
IMPORT IO, FmtTime, Time;
BEGIN
IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n");
END MyTime.</lang>
Output:
Current time: Tue Dec 30 20:50:07 CST 2008
MUMPS
System time since midnight (in seconds) is kept in the second part of the system variable $HOROLOG. <lang MUMPS>SYSTIME
NEW PH SET PH=$PIECE($HOROLOG,",",2) WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60 KILL PH QUIT</lang>
Usage:
USER>D SYSTIME^ROSETTA The system time is 22:55:44
NetRexx
<lang netrexx> import java.text.SimpleDateFormat say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date()) </lang>
Objective-C
<lang objc>NSLog(@"%@", [NSDate date]);</lang> or (deprecated) <lang objc>NSLog(@"%@", [NSCalendarDate calendarDate]);</lang>
Objeck
<lang objeck> function : Time() ~ Nil {
t := Time->New(); IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds());
} </lang>
OCaml
<lang ocaml>#load "unix.cma";; open Unix;; let {tm_sec = sec;
tm_min = min; tm_hour = hour; tm_mday = mday; tm_mon = mon; tm_year = year; tm_wday = wday; tm_yday = yday; tm_isdst = isdst} = localtime (time ());;
Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hour min sec;;</lang>
Oz
<lang oz>{Show {OS.time}} %% posix time (seconds since 1970-01-01) {Show {OS.gmTime}} %% current UTC as a record {Show {OS.localTime}} %% current local time as record
%% Also interesting: undocumented module OsTime %% When did posix time reach 1 billion? {Show {OsTime.gmtime 1000000000}} {Show {OsTime.localtime 1000000000}}</lang>
Output:
1263347902 time(hour:1 isDst:0 mDay:13 min:58 mon:0 sec:22 wDay:3 yDay:12 year:110) time(hour:2 isDst:0 mDay:13 min:58 mon:0 sec:22 wDay:3 yDay:12 year:110) time(hour:1 isDst:0 mDay:9 min:46 mon:8 sec:40 wDay:0 yDay:251 year:101) time(hour:3 isDst:1 mDay:9 min:46 mon:8 sec:40 wDay:0 yDay:251 year:101)
PARI/GP
For timing the gettime
is usually used, which measures CPU time rather than walltime. But to get the raw time you'll need a system call:
<lang parigp>system("date")</lang>
Pascal
<lang Pascal>program systime; uses DOS;
{ Format digit with leading zero } function lz(w: word): string; var
s: string;
begin
str(w,s); if length(s) = 1 then s := '0' + s; lz := s;
end;
var
h,m,s,c: word; yr,mo,da,dw: word; dt: datetime; t,ssm: longint; regs: registers;
begin
{ Time and Date } GetTime(h,m,s,c); writeln(lz(h),':',lz(m),':',lz(s),'.',c); GetDate(yr,mo,da,dw); writeln(yr,'-',lz(mo),'-',lz(da));
{ Turbo Epoch, seconds } with dt do begin year := yr; month := mo; day := da; hour := h; min := m; sec := s; end; packtime(dt,t); writeln(t);
{ Seconds since midnight, PC-BIOS 1Ah } regs.ah := 0; Intr($1A,regs); ssm := round((regs.cx * 65536 + regs.dx) * (65536 / 1192180)); writeln(ssm);
end.</lang>
Output:
23:42:35.9 2010-07-29 1023262033 85427
Perl
Simple localtime use in scalar context. <lang perl>print scalar localtime, "\n";</lang>
Output:
Thu Jan 24 11:23:30 2008
localtime use in array context. <lang perl>($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime; printf("%04d-%02d-%02d %02d:%02d:%02d\n", $year + 1900, $mon + 1, $mday, $hour, $min, $sec);</lang>
Output:
2008-01-24 11:23:30
The same using DateTime: <lang perl>use DateTime; my $dt = DateTime->now; my $d = $dt->ymd; my $t = $dt->hms; print "$d $t\n";</lang> Output:
2010-03-29 19:46:26
localtime use in array context with POSIX strftime:
<lang perl>use POSIX qw(strftime);
$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; print "$now_string\n";</lang>
Output (with cs_CZ.UTF-8 locale):
Čt led 24 11:23:30 2008
Using the DateTime module: <lang perl>use DateTime; my $dt = DateTime->now; say $dt->iso8601(); say $dt->year_with_christian_era(); say $dt->year_with_secular_era();
- etc.</lang>
Unix epoch: <lang perl>print time;</lang>
Output:
1280473609
Perl 6
<lang perl6>say DateTime.now;</lang>
Output:
2010-09-07T21:26:29Z
PHP
Seconds since the Unix epoch: <lang php>echo time(), "\n";</lang>
Formatted time: <lang php>echo date('D M j H:i:s Y'), "\n"; // custom format; see format characters here:
// http://us3.php.net/manual/en/function.date.php
echo date('c'), "\n"; // ISO 8601 format echo date('r'), "\n"; // RFC 2822 format echo date(DATE_RSS), "\n"; // can also use one of the predefined formats here:
// http://us3.php.net/manual/en/class.datetime.php#datetime.constants.types</lang>
PicoLisp
<lang PicoLisp>(stamp)</lang> Output:
-> "2010-02-19 15:14:06
PL/I
<lang PL/I> put (datetime()); /* writes out the date and time */
/* The time is given to thousandths of a second, */ /* in the format hhmiss999 */
put (time()); /* gives the time in the format hhmiss999. */ </lang>
PowerShell
Using a cmdlet: <lang powershell>Get-Date</lang> or using .NET classes and properties: <lang powershell>[DateTime]::Now</lang>
PureBasic
<lang PureBasic>time=Date() ; Unix timestamp time$=FormatDate("%mm.%dd.%yyyy %hh:%ii:%ss",time)
- following value is only reasonable accurate, on Windows it can differ by +/- 20 ms
ms_counter=ElapsedMilliseconds()
- could use API like QueryPerformanceCounter_() on Windows for more accurate values</lang>
Python
<lang python>import time print time.ctime()</lang>
Q
date & time are accessible via the virtual .z namespace. lowercase names are UTC, uppercase are local:
<lang q>q).z.D 2010.01.25 q).z.N 0D14:17:45.519682000 q).z.P 2010.01.25D14:17:46.962375000 q).z.T 14:17:47.817 q).z.Z 2010.01.25T14:17:48.711 q).z.z 2010.01.25T19:17:59.445</lang>
R
Note that this is output as a standard style string.
<lang R>Sys.time()</lang> Output:
[1] "2009-07-27 15:27:04 PDT"
REBOL
<lang REBOL>now print rejoin [now/year "-" now/month "-" now/day " " now/time] </lang>
Output:
10-Dec-2009/7:43:55-5:00 2009-12-10 7:43:55
Retro
Displays the number of seconds since the Unix epoch:
<lang Retro>time putn</lang>
REXX
Note that REXX only examines the first character of the option and can be in upper or lower case.
<lang rexx> say time() /* hh:mm:ss (hh is 00 --> 23). */ say time('n') /* (same as above) */ say time('N') /* (same as above) */ say time('Normal') /* (same as above) */ say time('nitPick') /* (same as above) */
say time('C') /* hh:mmam or hh:mmpm (hh is 0 --> 12). */ say time('Civil') /* (same as above) */
say time('L') /* hh:mm:ss.ffffff (hh is ---> 23). */ say time('Long') /* (same as above) */ </lang>
Ruby
<lang ruby>t = Time.now
- textual
puts t # => Wed Aug 05 20:14:50 -0400 2009
- epoch time
puts t.to_i # => 1249517690
- epoch time with fractional seconds
puts t.to_f # => 1249517690.74388</lang>
Scala
<lang scala>println(new java.util.Date)</lang> Output:
Sun Aug 14 22:47:42 EDT 2011
Scheme
<lang scheme>(use posix) (seconds->string (current-seconds))</lang> Output:
"Sat May 16 21:42:47 2009"
Seed7
<lang seed7>$ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
begin writeln(time(NOW)); end func;</lang>
Output:
2009-12-07 17:09:44.687500 UTC+1
Smalltalk
<lang smalltalk>DateTime now displayNl.</lang> Output:
2011-08-10T00:43:36-0-7:00
SNOBOL4
<lang SNOBOL4> OUTPUT = DATE() END</lang> Output:
03/30/2010 20:58:09
Standard ML
<lang sml>print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n")</lang>
Tcl
This uses a timestamp that is a number of seconds since the start of the UNIX Epoch. <lang tcl>puts [clock seconds]</lang> More readable forms may be created by formatting the time: <lang tcl>puts [clock format [clock seconds]]</lang>
TI-89 BASIC
<lang ti89b>■ getTime() {13 28 55} ■ getDate() {2009 8 13}</lang>
Note that the system clock can be turned off, in which case the value returned will remain constant. isClkOn()
can be used to check it.
TUSCRIPT
<lang tuscript> $$ MODE TUSCRIPT time=time() PRINT time </lang> Output:
2011-04-05 13:45:44
UNIX Shell
<lang bash> date # Thu Dec 3 15:38:06 PST 2009
date +%s # 1259883518, seconds since the epoch, like C stdlib time(0) </lang>
Ursala
A library function, now, ignores its argument and returns the system time as a character string. <lang Ursala>#import cli
- cast %s
main = now 0</lang> output:
'Fri, 26 Jun 2009 20:31:49 +0100'
This string can be converted to seconds since 1970 (ignoring leap seconds) by the library function string_to_time.
- Programming Tasks
- Programming environment operations
- Ada
- ALGOL 68
- Examples needing attention
- AppleScript
- AutoHotkey
- AutoIt
- AWK
- BASIC
- Batch File
- C
- C++
- C sharp
- Clojure
- Common Lisp
- D
- Delphi
- E
- Erlang
- Factor
- Fantom
- Forth
- Fortran
- Go
- Groovy
- GUISS
- Haskell
- HicEst
- IDL
- Io
- Icon
- Unicon
- J
- Java
- JavaScript
- Liberty BASIC
- Logo
- Lua
- Mathematica
- MATLAB
- Modula-3
- MUMPS
- NetRexx
- Objective-C
- Objeck
- OCaml
- Oz
- PARI/GP
- Pascal
- Perl
- Perl 6
- PHP
- PicoLisp
- PL/I
- PowerShell
- PureBasic
- Python
- Q
- R
- REBOL
- Retro
- REXX
- Ruby
- Scala
- Scheme
- Seed7
- Smalltalk
- SNOBOL4
- Standard ML
- Tcl
- TI-89 BASIC
- TUSCRIPT
- UNIX Shell
- Ursala
- Locomotive Basic/Omit
- ML/I/Omit
- ZX Spectrum Basic/Omit
- Date and time