System time: Difference between revisions
m Added output |
PascalABC.NET |
||
(312 intermediate revisions by more than 100 users not shown) | |||
Line 1: | Line 1: | ||
{{task|Programming environment operations}} |
|||
{{task}} |
|||
[[Category:Date and time]] |
|||
Output the system time (any units will do as long as they are noted) either by a [[Execute a System Command|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. |
|||
[[Category:Simple]] |
|||
{{omit from|ML/I}} |
|||
{{omit from|ZX Spectrum Basic|Does not have a real time clock.}} |
|||
;Task: |
|||
Output the system '''time''' (any units will do as long as they are noted) either by a [[Execute a System Command|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. |
|||
;Related task: |
|||
* [[Date format]] |
|||
;See also: |
|||
* [[wp:System time#Retrieving system time|Retrieving system time (wiki)]] |
|||
<br><br> |
|||
=={{header|11l}}== |
|||
<syntaxhighlight lang="11l">print(Time())</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2021-03-25 13:03:47.0505867 |
|||
</pre> |
|||
=={{header|AArch64 Assembly}}== |
|||
{{works with|as|Raspberry Pi 3B version Buster 64 bits}} |
|||
<syntaxhighlight lang="aarch64 assembly"> |
|||
/* ARM assembly AARCH64 Raspberry PI 3B */ |
|||
/* program sysTime64.s */ |
|||
/*******************************************/ |
|||
/* Constantes file */ |
|||
/*******************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly*/ |
|||
.include "../includeConstantesARM64.inc" |
|||
.equ GETTIME, 169 // call system linux gettimeofday |
|||
/*******************************************/ |
|||
/* Structures */ |
|||
/********************************************/ |
|||
/* example structure time */ |
|||
.struct 0 |
|||
timeval_sec: // |
|||
.struct timeval_sec + 8 |
|||
timeval_usec: // |
|||
.struct timeval_usec + 8 |
|||
timeval_end: |
|||
.struct 0 |
|||
timezone_min: // |
|||
.struct timezone_min + 8 |
|||
timezone_dsttime: // |
|||
.struct timezone_dsttime + 8 |
|||
timezone_end: |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessEmpty: .asciz "Empty queue. \n" |
|||
szMessNotEmpty: .asciz "Not empty queue. \n" |
|||
szMessError: .asciz "Error detected !!!!. \n" |
|||
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" // message result |
|||
szCarriageReturn: .asciz "\n" |
|||
.align 4 |
|||
tbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 |
|||
.quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700 |
|||
.quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065 |
|||
.quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430 |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
.align 4 |
|||
stTVal: .skip timeval_end |
|||
stTZone: .skip timezone_end |
|||
sZoneConv: .skip 100 |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: // entry of program |
|||
ldr x0,qAdrstTVal // time zones |
|||
ldr x1,qAdrstTZone |
|||
mov x8,GETTIME // call system |
|||
svc 0 |
|||
cmp x0,-1 // error ? |
|||
beq 99f |
|||
ldr x1,qAdrstTVal |
|||
ldr x0,[x1,timeval_sec] // timestamp in second |
|||
bl convTimeStamp |
|||
//ldr x0,qTStest1 |
|||
//bl convTimeStamp |
|||
//ldr x0,qTStest2 |
|||
//bl convTimeStamp |
|||
//ldr x0,qTStest3 |
|||
//bl convTimeStamp |
|||
b 100f |
|||
99: |
|||
ldr x0,qAdrszMessError |
|||
bl affichageMess |
|||
100: // standard end of the program |
|||
mov x0,0 // return code |
|||
mov x8,EXIT // request to exit program |
|||
svc 0 // perform the system call |
|||
qAdrszMessError: .quad szMessError |
|||
qAdrstTVal: .quad stTVal |
|||
qAdrstTZone: .quad stTZone |
|||
qAdrszMessResult: .quad szMessResult |
|||
qAdrszCarriageReturn: .quad szCarriageReturn |
|||
qTStest1: .quad 1609508339 // 01/01/2021 |
|||
qTStest2: .quad 1657805939 // 14/07/2022 |
|||
qTStest3: .quad 1767221999 // 31/12/2025 |
|||
/******************************************************************/ |
|||
/* conversion timestamp to date */ |
|||
/******************************************************************/ |
|||
/* x0 contains the value of timestamp */ |
|||
convTimeStamp: |
|||
stp x1,lr,[sp,-16]! // save registers |
|||
ldr x2,qSecJan2020 |
|||
sub x3,x0,x2 // total secondes to 01/01/2020 |
|||
mov x4,60 |
|||
udiv x5,x3,x4 |
|||
msub x6,x5,x4,x3 // compute secondes |
|||
udiv x3,x5,x4 |
|||
msub x7,x3,x4,x5 // compute minutes |
|||
mov x4,24 |
|||
udiv x5,x3,x4 |
|||
msub x8,x5,x4,x3 // compute hours |
|||
mov x4,(365 * 4 + 1) |
|||
udiv x9,x5,x4 |
|||
lsl x9,x9,2 // multiply by 4 = year1 |
|||
udiv x12,x5,x4 |
|||
msub x10,x12,x4,x5 |
|||
ldr x11,qAdrtbDayMonthYear |
|||
mov x12,3 |
|||
mov x13,12 |
|||
1: |
|||
mul x14,x13,x12 |
|||
ldr x15,[x11,x14,lsl 3] // load days by year |
|||
cmp x10,x15 |
|||
bge 2f |
|||
sub x12,x12,1 |
|||
cmp x12,0 |
|||
cbnz x12,1b |
|||
2: // x12 = year2 |
|||
mov x16,11 |
|||
mul x15,x13,x12 |
|||
lsl x15,x15,3 // * par 8 |
|||
add x14,x15,x11 |
|||
3: |
|||
ldr x15,[x14,x16,lsl 3] // load days by month |
|||
cmp x10,x15 |
|||
bge 4f |
|||
sub x16,x16,1 |
|||
cmp x16,0 |
|||
cbnz x16,3b |
|||
4: // x16 = month - 1 |
|||
mul x15,x13,x12 |
|||
add x15,x15,x16 |
|||
ldr x1,qAdrtbDayMonthYear |
|||
ldr x3,[x1,x15,lsl 3] |
|||
sub x0,x10,x3 |
|||
add x0,x0,1 // final compute day |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
ldr x0,qAdrszMessResult |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at first @ character |
|||
mov x2,x0 |
|||
add x0,x16,1 // final compute month |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
mov x2,x0 |
|||
add x0,x9,2020 |
|||
add x0,x0,x12 // final compute year = 2020 + year1 + year2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
mov x2,x0 |
|||
mov x0,x8 // hours |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
mov x2,x0 |
|||
mov x0,x7 // minutes |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
mov x2,x0 |
|||
mov x0,x6 // secondes |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
mov x2,x0 |
|||
ldr x1,qAdrstTVal |
|||
ldr x0,[x1,timeval_usec] // millisecondes |
|||
ldr x1,qAdrsZoneConv |
|||
bl conversion10 |
|||
mov x0,x2 |
|||
ldr x1,qAdrsZoneConv |
|||
bl strInsertAtCharInc // insert result at next @ character |
|||
bl affichageMess |
|||
b 100f |
|||
99: |
|||
ldr x0,qAdrszMessError |
|||
bl affichageMess |
|||
100: |
|||
ldp x1,lr,[sp],16 // restaur 2 registers |
|||
ret // return to address lr x30 |
|||
qAdrsZoneConv: .quad sZoneConv |
|||
qSecJan2020: .quad 1577836800 |
|||
qAdrtbDayMonthYear: .quad tbDayMonthYear |
|||
/********************************************************/ |
|||
/* File Include fonctions */ |
|||
/********************************************************/ |
|||
/* for this file see task include a file in language AArch64 assembly */ |
|||
.include "../includeARM64.inc" |
|||
</syntaxhighlight> |
|||
{{Output}} |
|||
<pre> |
|||
GMT: 28/3/2020 20:29:58 862484ms |
|||
</pre> |
|||
=={{header|ABAP}}== |
|||
<syntaxhighlight lang="aime">REPORT system_time. |
|||
WRITE: sy-uzeit.</syntaxhighlight> |
|||
=={{header|Ada}}== |
=={{header|Ada}}== |
||
The following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian. |
The following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian.<syntaxhighlight 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; |
|||
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;</syntaxhighlight>{{out}} |
|||
Output: |
|||
2008-01-23 19:14:19 |
2008-01-23 19:14:19 |
||
=={{header|Aime}}== |
|||
<syntaxhighlight lang="aime">date d; |
|||
d_now(d); |
|||
o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d), |
|||
d_d_hour(d), d_h_minute(d), d_m_second(d));</syntaxhighlight>{{out}} |
|||
2011-09-04 15:05:08 |
|||
=={{header|ALGOL 68}}== |
|||
<!-- {{does not work with|ALGOL 68|Standard - POSIX local time, and utc time extensions to language used}} --> |
|||
{{works with|ALGOL 68G|Any - tested with release mk15-0.8b.fc9.i386}} |
|||
<!-- {{does not work with|ELLA ALGOL 68|Any (with appropriate job cards) - tested with release 1.8.8d.fc9.i386 - test missing transput, and POSIX local time, and utc time extensions to language used}} --><syntaxhighlight 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))</syntaxhighlight>{{out}} |
|||
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 |
|||
=={{header|AmigaBASIC}}== |
|||
<syntaxhighlight lang="amigabasic">print date$,time$</syntaxhighlight> |
|||
{{output}} |
|||
<pre>11-19-2020 20:47:44</pre> |
|||
=={{header|AppleScript}}== |
|||
<syntaxhighlight lang="applescript">display dialog ((current date) as text)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Sunday, August 14, 2011 10:43:57 PM |
|||
</pre> |
|||
macOS's system time epoch is 1st January 2001 00:00:00 UTC. The number of seconds since then can be calculated in vanilla AppleScript like this: |
|||
<syntaxhighlight lang="applescript">set now to (current date) |
|||
set GMTOffset to (time to GMT) |
|||
copy now to epoch |
|||
tell epoch to set {its day, its month, its year, its time} to {1, January, 2001, 0} |
|||
set systemTime to now - GMTOffset - epoch |
|||
-- Format output: |
|||
set offsetStr to GMTOffset div hours * 100 + GMTOffset mod hours div minutes |
|||
if (GMTOffset < 0) then |
|||
set offsetStr to " -" & text 3 thru -1 of ((-10000 + offsetStr) as text) |
|||
else |
|||
set offsetStr to " +" & text 2 thru -1 of ((10000 + offsetStr) as text) |
|||
end if |
|||
return (now as text) & offsetStr & (linefeed & systemTime) & (" seconds since " & epoch & " UTC")</syntaxhighlight> |
|||
{{output}} |
|||
<syntaxhighlight lang="applescript">"Tuesday 30 June 2020 at 11:34:31 +0100 |
|||
6.15206071E+8 seconds since Monday 1 January 2001 at 00:00:00 UTC"</syntaxhighlight> |
|||
With AppleScriptObjC, it's more direct and fractions of a second are included: |
|||
<syntaxhighlight lang="applescript">use AppleScript version "2.4" -- Mac OS 10.10 (Yosemite) or later. |
|||
use framework "Foundation" |
|||
set now to current application's class "NSDate"'s |date|() |
|||
set systemTime to now's timeIntervalSinceReferenceDate() |
|||
-- Or, since timeIntervalSinceReferenceDate() is both an instance method and a class method: |
|||
-- set systemTime to current application's class "NSDate"'s timeIntervalSinceReferenceDate() |
|||
-- Format output: |
|||
set currentLocale to current application's class "NSLocale"'s currentLocale() |
|||
set nowAsText to (now's descriptionWithLocale:(currentLocale)) as text |
|||
set epoch to now's dateByAddingTimeInterval:(-systemTime) |
|||
-- Or: |
|||
-- set epoch to current application's class "NSDate"'s dateWithTimeIntervalSinceReferenceDate:(0) |
|||
set epochAsText to epoch's |description|() as text |
|||
return nowAsText & (linefeed & systemTime) & (" seconds since " & epochAsText)</syntaxhighlight> |
|||
{{output}} |
|||
<syntaxhighlight lang="applescript">"Tuesday 30 June 2020 at 11:34:34 British Summer Time |
|||
6.152060746444E+8 seconds since 2001-01-01 00:00:00 +0000"</syntaxhighlight> |
|||
=={{header|ARM Assembly}}== |
|||
{{works with|as|Raspberry Pi}} |
|||
<syntaxhighlight lang="arm assembly"> |
|||
/* ARM assembly Raspberry PI */ |
|||
/* program sysTime.s */ |
|||
/* REMARK 1 : this program use routines in a include file |
|||
see task Include a file language arm assembly |
|||
for the routine affichageMess conversion10 |
|||
see at end of this program the instruction include */ |
|||
/*******************************************/ |
|||
/* Constantes */ |
|||
/*******************************************/ |
|||
.equ STDOUT, 1 @ Linux output console |
|||
.equ EXIT, 1 @ Linux syscall |
|||
.equ WRITE, 4 @ Linux syscall |
|||
.equ BRK, 0x2d @ Linux syscall |
|||
.equ CHARPOS, '@' |
|||
.equ GETTIME, 0x4e @ call system linux gettimeofday |
|||
/*******************************************/ |
|||
/* Structures */ |
|||
/********************************************/ |
|||
/* example structure time */ |
|||
.struct 0 |
|||
timeval_sec: @ |
|||
.struct timeval_sec + 4 |
|||
timeval_usec: @ |
|||
.struct timeval_usec + 4 |
|||
timeval_end: |
|||
.struct 0 |
|||
timezone_min: @ |
|||
.struct timezone_min + 4 |
|||
timezone_dsttime: @ |
|||
.struct timezone_dsttime + 4 |
|||
timezone_end: |
|||
/*********************************/ |
|||
/* Initialized data */ |
|||
/*********************************/ |
|||
.data |
|||
szMessError: .asciz "Error detected !!!!. \n" |
|||
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" @ message result |
|||
szCarriageReturn: .asciz "\n" |
|||
.align 4 |
|||
tbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 |
|||
.int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700 |
|||
.int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065 |
|||
.int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430 |
|||
/*********************************/ |
|||
/* UnInitialized data */ |
|||
/*********************************/ |
|||
.bss |
|||
.align 4 |
|||
stTVal: .skip timeval_end |
|||
stTZone: .skip timezone_end |
|||
sZoneConv: .skip 100 |
|||
/*********************************/ |
|||
/* code section */ |
|||
/*********************************/ |
|||
.text |
|||
.global main |
|||
main: @ entry of program |
|||
ldr r0,iAdrstTVal |
|||
ldr r1,iAdrstTZone |
|||
mov r7,#GETTIME |
|||
svc 0 |
|||
cmp r0,#-1 @ error ? |
|||
beq 99f |
|||
ldr r0,iAdrstTVal |
|||
ldr r1,[r0,#timeval_sec] @ timestemp in second |
|||
//ldr r1,iTStest1 |
|||
//ldr r1,iTStest2 |
|||
//ldr r1,iTStest3 |
|||
ldr r2,iSecJan2020 |
|||
sub r0,r1,r2 @ total secondes to 01/01/2020 |
|||
mov r1,#60 |
|||
bl division |
|||
mov r0,r2 |
|||
mov r6,r3 @ compute secondes |
|||
mov r1,#60 |
|||
bl division |
|||
mov r7,r3 @ compute minutes |
|||
mov r0,r2 |
|||
mov r1,#24 |
|||
bl division |
|||
mov r8,r3 @ compute hours |
|||
mov r0,r2 |
|||
mov r11,r0 |
|||
mov r1,#(365 * 4 + 1) |
|||
bl division |
|||
lsl r9,r2,#2 @ multiply by 4 = year1 |
|||
mov r1,#(365 * 4 + 1) |
|||
mov r0,r11 |
|||
bl division |
|||
mov r10,r3 |
|||
ldr r1,iAdrtbDayMonthYear |
|||
mov r2,#3 |
|||
mov r3,#12 |
|||
1: |
|||
mul r11,r3,r2 |
|||
ldr r12,[r1,r11,lsl #2] @ load days by year |
|||
cmp r10,r12 |
|||
bge 2f |
|||
sub r2,r2,#1 |
|||
cmp r2,#0 |
|||
bne 1b |
|||
2: @ r2 = year2 |
|||
mov r5,#11 |
|||
mul r4,r3,r2 |
|||
lsl r4,#2 |
|||
add r4,r1 |
|||
3: |
|||
ldr r12,[r4,r5,lsl #2] @ load days by month |
|||
cmp r10,r12 |
|||
bge 4f |
|||
subs r5,r5,#1 |
|||
bne 3b |
|||
4: @ r5 = month - 1 |
|||
mul r11,r3,r2 |
|||
add r11,r5 |
|||
ldr r1,iAdrtbDayMonthYear |
|||
ldr r3,[r1,r11,lsl #2] |
|||
sub r0,r10,r3 |
|||
add r0,r0,#1 @ final compute day |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 @ this function do not zero final |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
ldr r0,iAdrszMessResult |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at first @ character |
|||
mov r3,r0 |
|||
add r0,r5,#1 @ final compute month |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
mov r3,r0 |
|||
ldr r11,iYearStart |
|||
add r0,r9,r11 |
|||
add r0,r0,r2 @ final compute year = 2020 + year1 + year2 |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
mov r3,r0 |
|||
mov r0,r8 @ hours |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
mov r3,r0 |
|||
mov r0,r7 @ minutes |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
mov r3,r0 |
|||
mov r0,r6 @ secondes |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
mov r3,r0 |
|||
ldr r1,iAdrstTVal |
|||
ldr r0,[r1,#timeval_usec] @ millisecondes |
|||
ldr r1,iAdrsZoneConv |
|||
bl conversion10 |
|||
mov r4,#0 @ store zero final |
|||
strb r4,[r1,r0] |
|||
mov r0,r3 |
|||
ldr r1,iAdrsZoneConv |
|||
bl strInsertAtCharInc @ insert result at next @ character |
|||
bl affichageMess |
|||
b 100f |
|||
99: |
|||
ldr r0,iAdrszMessError |
|||
bl affichageMess |
|||
100: @ standard end of the program |
|||
mov r0,#0 @ return code |
|||
mov r7,#EXIT @ request to exit program |
|||
svc 0 @ perform the system call |
|||
iAdrszMessError: .int szMessError |
|||
iAdrstTVal: .int stTVal |
|||
iAdrstTZone: .int stTZone |
|||
iAdrszMessResult: .int szMessResult |
|||
iAdrszCarriageReturn: .int szCarriageReturn |
|||
iAdrsZoneConv: .int sZoneConv |
|||
iSecJan2020: .int 1577836800 |
|||
iAdrtbDayMonthYear: .int tbDayMonthYear |
|||
iYearStart: .int 2020 |
|||
iTStest1: .int 1609508339 @ 01/01/2021 |
|||
iTStest2: .int 1657805939 @ 14/07/2022 |
|||
iTStest3: .int 1767221999 @ 31/12/2025 |
|||
/***************************************************/ |
|||
/* ROUTINES INCLUDE */ |
|||
/***************************************************/ |
|||
.include "../affichage.inc" |
|||
</syntaxhighlight> |
|||
{{Output}} |
|||
<pre> |
|||
GMT: 29/3/2020 18:39:13 717877ms |
|||
</pre> |
|||
=={{header|Arturo}}== |
|||
<syntaxhighlight lang="rebol">print now</syntaxhighlight> |
|||
{{out}} |
|||
<pre>2021-02-20T11:10:08+01:00</pre> |
|||
=={{header|Asymptote}}== |
|||
<syntaxhighlight lang="asymptote">time(); |
|||
time("%a %b %d %H:%M:%S %Z %Y"); |
|||
//are equivalent ways of returning the current time in the default format used by the UNIX date command.</syntaxhighlight> |
|||
See [https://asymptote.sourceforge.io/doc/Data-types.html time() in the Asymptote manual]. |
|||
=={{header|AutoHotkey}}== |
|||
<syntaxhighlight lang="autohotkey">FormatTime, t |
|||
MsgBox,% t</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
4:18 PM Saturday, May 30, 2009 |
|||
</pre> |
|||
=={{header|AutoIt}}== |
|||
<syntaxhighlight lang="autoit">MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Year: 2011,Day: 05,Hour: 09, Minutes: 15, Seconds: 25 |
|||
</pre> |
|||
=={{header|Avail}}== |
|||
The method <code>now</code> retrieves the current timestamp. |
|||
<syntaxhighlight lang="avail">Print: “now”;</syntaxhighlight> |
|||
=={{header|AWK}}== |
|||
'''One-liner:''' |
|||
{{works with|Gawk}} |
|||
<syntaxhighlight lang="awk">$ awk 'BEGIN{print systime(),strftime()}'</syntaxhighlight> |
|||
{{out}} |
|||
<pre>1242401632 Fri May 15 17:33:52 2009</pre> |
|||
'''Solution for other awk-versions:''' |
|||
{{works with|awk}} |
|||
<syntaxhighlight lang="awk"> |
|||
function dos_date( cmd,d,t,x) { # under MS Windows |
|||
# cmd = "DATE /T" |
|||
# cmd | getline d # Format depends on locale, e.g. MM/DD/YYYY or YYYY-MM-DD |
|||
# close(cmd) # close pipe |
|||
# ##print d |
|||
# cmd = "TIME /T" |
|||
# cmd | getline t # 13:59 |
|||
# close(cmd) |
|||
# ##print t |
|||
# return d t |
|||
cmd = "echo %DATE% %TIME%" # this gives better time-resolution |
|||
cmd | getline x # 2014-10-31 20:57:36.84 |
|||
close(cmd) |
|||
return x |
|||
} |
|||
BEGIN { |
|||
print "Date and time:", dos_date() |
|||
#print systime(), strftime() # gawk only |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2014-10-31 20:57:36.84 |
|||
</pre> |
|||
See also: [[System_time#Batch]], [http://rosettacode.org/wiki/Discordian_date#AWK Discordian_date] |
|||
=={{header|BaCon}}== |
|||
<syntaxhighlight lang="qbasic">' BaCon time |
|||
n = NOW |
|||
PRINT n, " seconds since January 1st, 1970" |
|||
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d " |
|||
PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n"</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1503869183 seconds since January 1st, 1970 |
|||
2017/08/27 17:26:23</pre> |
|||
=={{header|BASIC}}== |
=={{header|BASIC}}== |
||
{{works with|QBasic}} |
|||
'''Interpreter''': [[QuickBasic]] 4.5 |
|||
This shows the system time in |
This shows the system time in seconds since midnight. |
||
<syntaxhighlight lang="qbasic">PRINT TIMER</syntaxhighlight> |
|||
PRINT TIMER |
|||
This shows the time in human-readable format (using a 24-hour clock): |
|||
<syntaxhighlight lang="qbasic">PRINT TIME$</syntaxhighlight> |
|||
==={{header|Commodore BASIC}}=== |
|||
====TI$ and TI==== |
|||
Commodore BASIC maintains both a 24-hour clock as <code>TI$</code> and a jiffy clock (1 jiffy = 1/60 seconds) as the variable <code>TIME</code>. Since Commodore BASIC recognizes only the first two letters of a variable identifier, <code>TIME$</code>, <code>TIMPANI$</code>, and <code>TIMBUKTU$</code> would all refer to the time keeping variable of <code>TI$</code>. |
|||
Notes about the two variables: |
|||
* <code>TI$</code> counts in standard time format of HHMMSS from 00:00:00 to 23:59:59 after which it will reset back to 00:00:00. On certain CBM/PET computers, TI$ is seven digits to include 1/10 seconds at the end. |
|||
* <code>TI$</code> is both read and write capable. The user can initialize the clock to any valid time within the 24 hour range by assigning it a string value of the time, e.g. <code>TI$ = "111530"</code> for 11:15:30. Assigning improper values (e.g. "089900" as 99 minutes after 8 o'clock) will result in automatic correction for the true time (09:39:00). Unfortunately there is no tracking of overflow in the hours to keep track of days, etc. |
|||
* <code>TI</code> is read only, but always reflects the jiffy equivalent to the value in <code>TI$</code>, that is: TI = (HH × 216,000) + (MM × 3600) + (SS × 60) + JIFFIES. <code>TI</code> can be set or reset to a value by setting <code>TI$</code> to the equivalent HHMMSS time, although resolution to specific jiffies is not possible with this method. |
|||
* Particularly on the Commodore 64, the timer handler is driven off of a CIA chip interrupt, but is in no way tied to any of the [[#Time of Day Clocks|time-of-day clocks]] built into the CIA (see below.) |
|||
* Because the clock is managed by the KERNAL operating system, the clock will loose time during certain I/O processes, such as disk access, etc. when the interrupt is unable to be processed on time. |
|||
'''Code Examples''' |
|||
<syntaxhighlight lang="commodorebasic">1 rem time since last reset |
|||
5 print chr$(147);chr$(14); |
|||
10 t$=ti$ |
|||
20 h$=left$(t$,2) |
|||
30 m$=mid$(t$,3,2) |
|||
40 s$=right$(t$,2) |
|||
50 print chr$(19);"Roughly ";tab(9);h$;" hours " |
|||
51 print tab(9);m$;" minutes" |
|||
52 print tab(9);s$; " seconds":print |
|||
60 print "has elapsed since TI$ was last reset or" |
|||
65 print "the system was powered on.":print |
|||
70 print "Press any key to quit." |
|||
80 get k$:if k$="" then goto 10 |
|||
</syntaxhighlight> |
|||
<syntaxhighlight lang="commodorebasic">5 rem set time to current time of day |
|||
10 print chr$(147); |
|||
20 input "Enter hour of day (0-23)";h$ |
|||
25 if val(h$)<0 or val(h$)>23 then goto 20 |
|||
30 input "Enter minutes (0-59)";m$ |
|||
35 if val(m$)<0 or val(m$)>99 then goto 30 |
|||
40 input "Enter seconds (0-59)";s$ |
|||
45 if val(s$)<0 or val(s$)>99 then goto 40 |
|||
60 ti$=h$+m$+s$ |
|||
70 print chr$(147); |
|||
80 print chr$(19);"The time is now: ";ti$ |
|||
85 print:print "Press any key to end." |
|||
90 get k$:if k$="" then 80 |
|||
100 end</syntaxhighlight> |
|||
====Time of Day Clocks==== |
|||
The Commodore 64 and 128 models each have two MOS 6526 Complex Interface Adapters (CIA) that each have Time of Day (TOD) clocks. Interestingly, these clocks are ''not'' used to drive the internal variables <code>TI</code> and <code>TI$</code>. The advantage of these clocks is that they will continue to count time independent of the operating system, and therefore do not lose time during the same I/O operations that affect <code>TI</code> and <code>TI$</code>. |
|||
The time is represented in Binary Coded Decimal, and a separate register is used to access hours, minutes, seconds, and 1/10 seconds. |
|||
'''Reading''' the HOURS register will suspend further updates to ''all'' of the TOD registers to allow the program to accurately read the complete time. ''The clock itself does not stop''. Once the 1/10 register is read, updates to the registers will continue. If the programmer intends to read only the hours of a running clock, a subsequent read of the 1/10 register must be performed to resume updating of the registers. |
|||
'''Writing''' to the HOURS register will ''stop the clock completely''. The clock will start only when the 1/10 register is written to, even with a zero. |
|||
'''Code Example - Commodore 64/128 Only''' |
|||
<syntaxhighlight lang="commodorebasic">1 rem read and set cia time of day clock |
|||
2 rem rosetta code commodore 64/128 example |
|||
10 print chr$(147);chr$(14) |
|||
15 hr=56331:mr=56330:sr=56329:tr=56328:gosub 300 |
|||
20 print spc(11);"CIA #1 Time of Day" |
|||
21 print:print "Press S to start or stop the clock." |
|||
22 print "Press T to change the time." |
|||
23 print:print "Press Q to quit.":print |
|||
25 h=peek(hr):m=peek(mr):s=peek(sr):th=peek(tr):t=h:gosub 200 |
|||
35 print chr$(19);:for q=1 to 8:print chr$(17);:next q |
|||
36 print "Clock is:";tab(12);cl$(b):print |
|||
40 print "Hours:";tab(12);h;". " |
|||
45 print "Minutes:";tab(12);m;". " |
|||
50 print "Seconds:";tab(12);s;". " |
|||
55 print "1/10 Sec.:";tab(12);th;". " |
|||
60 print "AM or PM? ";tab(13);ap$ |
|||
65 get k$:if k$="" then goto 25 |
|||
70 if k$="s" and b=0 then poke tr,0:b=1:goto 25 |
|||
75 if k$="s" and b=1 then poke hr,t:b=0:goto 25 |
|||
80 if k$="t" then gosub 400:goto 20 |
|||
90 if k$="q" then end |
|||
100 goto 25 |
|||
200 rem decode bcd |
|||
210 ap$="AM":if (h and 128)=128 then ap$="PM" |
|||
220 s=int((s and 112)/16)*10+(s and 15) |
|||
230 m=int((m and 112)/16)*10+(m and 15) |
|||
240 h=int((h and 48)/16)*10+(h and 15) |
|||
250 return |
|||
300 rem decide if clock is running |
|||
305 cl$(0)="Stopped":cl$(1)="Running":b=0 |
|||
301 rem latch, read/resume |
|||
310 z=peek(hr):t1=peek(tr) |
|||
315 for i=1 to 100:next i |
|||
320 z=peek(hr):t2=peek(tr) |
|||
325 if t1<>t2 then b=1 |
|||
330 return |
|||
400 rem change clock value |
|||
405 print chr$(147) |
|||
410 input "Hour";nh$ |
|||
415 if val(nh$)<1 or val(nh$)>12 then goto 410 |
|||
416 if val(nh$)<10 then nh$="0"+nh$ |
|||
420 input "Minutes";nm$ |
|||
425 if val(nm$)<0 or val(nm$)>59 then goto 420 |
|||
426 if val(nm$)<10 then nm$="0"+nm$ |
|||
430 input "Seconds";ns$ |
|||
435 if val(ns$)<0 or val(ns$)>59 then goto 430 |
|||
436 if val(ns$)<10 then ns$="0"+ns$ |
|||
440 print "AM or PM (a,p)? "; |
|||
445 get ap$:if ap$<>"a" and ap$<>"p" then 445 |
|||
446 print ap$ |
|||
450 ap=0:if ap$="p" then ap=128 |
|||
455 rem convert input to bcd |
|||
457 ns=val(mid$(ns$,1,1))*16+val(mid$(ns$,2,1)) |
|||
460 nm=val(mid$(nm$,1,1))*16+val(mid$(nm$,2,1)) |
|||
465 nh=val(mid$(nh$,1,1))*16+val(mid$(nh$,2,1)) |
|||
470 nh=nh+ap |
|||
475 rem now set values into clock |
|||
480 poke hr,nh:rem set hour stops clock |
|||
485 poke mr,nm:rem set minute |
|||
490 poke sr,ns:rem set second |
|||
495 poke tr,0 :rem set 1/10 starts clock |
|||
497 b=1 |
|||
499 print chr$(147):return</syntaxhighlight> |
|||
=={{header|BASIC256}}== |
|||
<syntaxhighlight lang="basic256">print month+1; "-"; day; "-"; year |
|||
# returns system date in format: mm-dd-yyyy |
|||
print hour; ":"; minute; ":"; second |
|||
# returns system time in format: hh:mm:ss</syntaxhighlight> |
|||
=={{header|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 <tt>date</tt> and <tt>time</tt> have a <tt>/t</tt> argument which makes them output only the value instead of prompting for a new one as well. |
|||
{{works with|Windows NT}}<syntaxhighlight lang="dos">date /t |
|||
time /t</syntaxhighlight>Furthermore there are two pseudo-variables <tt>%DATE%</tt> and <tt>%TIME%</tt>: |
|||
{{works with|Windows NT|4}}<syntaxhighlight lang="dos">echo %DATE% %TIME%</syntaxhighlight> |
|||
=={{header|BBC BASIC}}== |
|||
<syntaxhighlight lang="bbcbasic"> PRINT TIME$</syntaxhighlight>Outputs the date and time. To output only the time:<syntaxhighlight lang="bbcbasic"> PRINT RIGHT$(TIME$,8)</syntaxhighlight> |
|||
=={{header|BQN}}== |
|||
The system value <code>•UnixTime</code> whenever called, gives time between the unix epoch the time the function was called, where the Unix epoch is 1970-01-01 00:00:00 UTC. [https://github.com/mlochbaum/bqn-libs/blob/master/datetime.bqn bqn-libs/datetime.bqn] has some functions for the manipulation of the given timestamp. |
|||
<syntaxhighlight lang="bqn">•Show •UnixTime @</syntaxhighlight> |
|||
=={{header|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.<syntaxhighlight 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; |
|||
}</syntaxhighlight> |
|||
=={{header|C sharp|C#}}== |
|||
<syntaxhighlight lang="csharp">Console.WriteLine(DateTime.Now);</syntaxhighlight> |
|||
=={{header|C++}}== |
|||
to be compiled under linux with g++ -lboost_date_time systemtime.cpp -o systemtime( or whatever you like) |
|||
<syntaxhighlight 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 ; |
|||
}</syntaxhighlight> |
|||
===C++ 11=== |
|||
<syntaxhighlight lang="cpp">#include <chrono> |
|||
#include <ctime> //for conversion std::ctime() |
|||
#include <iostream> |
|||
int main() { |
|||
auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now()); |
|||
std::cout << std::ctime(&timenow) << std::endl; |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Thu Dec 26 13:51:00 2013 |
|||
</pre> |
|||
=={{header|Clojure}}== |
|||
<syntaxhighlight 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))</syntaxhighlight> |
|||
=={{header|CLU}}== |
|||
<syntaxhighlight lang="clu">start_up = proc () |
|||
stream$putl(stream$primary_output(), date$unparse(now())) |
|||
end start_up</syntaxhighlight> |
|||
{{out}} |
|||
<pre>19 December 2021 01:50:11</pre> |
|||
=={{header|COBOL}}== |
|||
<syntaxhighlight lang="cobol"> WORKING-STORAGE SECTION. |
|||
01 WS-CURRENT-DATE-FIELDS. |
|||
05 WS-CURRENT-DATE. |
|||
10 WS-CURRENT-YEAR PIC 9(4). |
|||
10 WS-CURRENT-MONTH PIC 9(2). |
|||
10 WS-CURRENT-DAY PIC 9(2). |
|||
05 WS-CURRENT-TIME. |
|||
10 WS-CURRENT-HOUR PIC 9(2). |
|||
10 WS-CURRENT-MINUTE PIC 9(2). |
|||
10 WS-CURRENT-SECOND PIC 9(2). |
|||
10 WS-CURRENT-MS PIC 9(2). |
|||
05 WS-DIFF-FROM-GMT PIC S9(4). |
|||
PROCEDURE DIVISION. |
|||
MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS.</syntaxhighlight> |
|||
=={{header|ColdFusion}}== |
|||
=== Script Based CFML === |
|||
<syntaxhighlight lang="cfm"><cfscript> |
|||
// Date Time |
|||
currentTime = Now(); |
|||
writeOutput( currentTime ); |
|||
// Epoch |
|||
// Credit for Epoch time should go to Ben Nadel |
|||
// bennadel.com is his blog |
|||
utcDate = dateConvert( "local2utc", currentTime ); |
|||
writeOutput( utcDate.getTime() ); |
|||
</cfscript></syntaxhighlight> |
|||
{{Output}} |
|||
<pre> |
|||
Current DateTime: {ts '2017-06-06 10:36:28'} |
|||
Epoch: 1496763388434 |
|||
</pre> |
|||
=={{header|Common Lisp}}== |
|||
<syntaxhighlight 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))</syntaxhighlight> |
|||
=={{header|Crystal}}== |
|||
<syntaxhighlight lang="ruby"># current time in system's time zone: |
|||
Time.local |
|||
# current time in UTC |
|||
Time.utc |
|||
# monotonic time (useful for measuring elapsed time) |
|||
Time.monotonic |
|||
</syntaxhighlight> |
|||
=={{header|D}}== |
|||
{{works with|Tango}} |
|||
''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). |
|||
<syntaxhighlight lang="d">Stdout(Clock.now.span.days / 365).newline;</syntaxhighlight> |
|||
=={{header|DBL}}== |
|||
<syntaxhighlight lang="dbl">XCALL TIME (D6) ;D6=hhmmss</syntaxhighlight> |
|||
=={{header|DCL}}== |
|||
<syntaxhighlight lang="dcl">$ start_time = f$time() |
|||
$ wait 0::10 |
|||
$ end_time = f$time() |
|||
$ write sys$output "start time was ", start_time |
|||
$ write sys$output "end time was ", end_time |
|||
$ write sys$output "delta time is ", f$delta_time( start_time, end_time )</syntaxhighlight> |
|||
{{out}} |
|||
<pre>$ @system_time |
|||
start time was 4-JUN-2015 15:38:09.60 |
|||
end time was 4-JUN-2015 15:38:19.60 |
|||
delta time is 0 00:00:10.00</pre> |
|||
The alternative below doesn't facilitate the calculation of the delta time; |
|||
{{out}} |
|||
<pre>$ show time |
|||
4-JUN-2015 15:33:33</pre> |
|||
=={{header|Delphi}}== |
|||
<syntaxhighlight lang="delphi">lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);</syntaxhighlight>This populates a label with the date |
|||
=={{header|DWScript}}== |
|||
<syntaxhighlight lang="delphi">PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now));</syntaxhighlight> |
|||
=={{header|E}}== |
|||
<syntaxhighlight lang="e">println(timer.now())</syntaxhighlight> |
|||
The value is the number of milliseconds since 1970. |
|||
=={{header|EasyLang}}== |
|||
<syntaxhighlight lang="text">print timestr systime</syntaxhighlight> |
|||
=={{header|Ecstasy}}== |
|||
<syntaxhighlight lang="ecstasy"> |
|||
module WhatTimeIsIt { |
|||
@Inject Clock clock; |
|||
@Inject Console console; |
|||
void run() { |
|||
console.print($"current time: {clock.now}"); |
|||
} |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
current time: 2024-04-30 19:40:57.124 |
|||
</pre> |
|||
=={{header|Elena}}== |
|||
ELENA 4.x : |
|||
<syntaxhighlight lang="elena">import extensions; |
|||
import system'calendar; |
|||
public program() |
|||
{ |
|||
console.printLine(Date.Now); |
|||
}</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
01.10.2017 18:02:43 |
|||
</pre> |
|||
=={{header|Elixir}}== |
|||
<syntaxhighlight lang="elixir">:os.timestamp # => {MegaSecs, Secs, MicroSecs} |
|||
:erlang.time # => {Hour, Minute, Second} |
|||
:erlang.date # => {Year, Month, Day} |
|||
:erlang.localtime # => {{Year, Month, Day}, {Hour, Minute, Second}} |
|||
:erlang.universaltime # => {{Year, Month, Day}, {Hour, Minute, Second}} |
|||
:calendar.local_time # => {{Year, Month, Day}, {Hour, Minute, Second}} |
|||
:calendar.universal_time # => {{Year, Month, Day}, {Hour, Minute, Second}}</syntaxhighlight> |
|||
It is also guaranteed that subsequent calls to this BIF returns continuously increasing values. Hence, the return value from <code>:erlang.now()</code> can be used to generate unique time-stamps, and if it is called in a tight loop on a fast machine the time of the node can become skewed. |
|||
<syntaxhighlight lang="elixir">:random.seed(:erlang.now)</syntaxhighlight> |
|||
=={{header|Emacs Lisp}}== |
|||
<syntaxhighlight lang="lisp">(message "%s" (current-time-string)) |
|||
;; => "Wed Oct 14 22:21:05 1987"</syntaxhighlight> |
|||
<code>current-time</code> is the main programmatic interface, with various functions available to format or operate on the time values list it gives. |
|||
=={{header|Erlang}}== |
|||
By default, Erlang timestamps are turned in the {megasecs, secs, microsecs} format.<syntaxhighlight lang="erlang">1> os:timestamp(). |
|||
{1250,222584,635452}</syntaxhighlight> |
|||
These can be changed with the calendar module:<syntaxhighlight 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}}</syntaxhighlight>Note that you will often encounter the function <tt>erlang:now/0</tt> giving a time similar to the system time. However, <tt>erlang:now/0</tt> may get delayed if the system time changes suddenly (i.e.: coming back from sleep mode). The delay is in place to make sure <tt>receive</tt> clauses that are millisecond-sensitive do not get false timeouts. |
|||
=={{header|Excel}}== |
|||
NOW() returns the date and time to the minute. |
|||
Type in a cell :<syntaxhighlight lang="excel">=NOW()</syntaxhighlight> |
|||
{{out}} |
|||
<pre>9-8-2013 17:33</pre> |
|||
=={{header|F_Sharp|F#}}== |
|||
<syntaxhighlight lang="fsharp">printfn "%s" (System.DateTime.Now.ToString("u"))</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2013-09-19 23:56:50Z |
|||
</pre> |
|||
=={{header|Factor}}== |
|||
<syntaxhighlight lang="factor">USE: calendar |
|||
now .</syntaxhighlight> |
|||
=={{header|Falcon}}== |
|||
<syntaxhighlight lang="falcon"> |
|||
/* Added by Aykayayciti Earl Lamont Montgomery |
|||
April 10th, 2018 */ |
|||
> CurrentTime().toString() |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2018-04-10 09:40:35.798 |
|||
[Finished in 0.2s] |
|||
</pre> |
|||
=={{header|Fantom}}== |
|||
<tt>DateTime.now</tt> returns the current time, which can then be formatted into different styles. For example, <tt>toJava</tt> returns the current time in milliseconds since 1 Jan 1970. |
|||
<tt>DateTime.nowTicks</tt> returns the number of nanoseconds since 1 Jan 2000 UTC.<syntaxhighlight lang="fantom">fansh> DateTime.nowTicks |
|||
351823905158000000 |
|||
fansh> DateTime.now |
|||
2011-02-24T00:51:47.066Z London |
|||
fansh> DateTime.now.toJava |
|||
1298508885979</syntaxhighlight> |
|||
=={{header|Forth}}== |
=={{header|Forth}}== |
||
Forth's only standard access to the system timers is via <tt>DATE&TIME ( -- s m h D M Y )</tt> and <tt>MS ( n -- )</tt> which pauses the program for at least ''n'' milliseconds. Particular Forth implementations give different access to millisecond and microsecond timers: |
Forth's only standard access to the system timers is via <tt>DATE&TIME ( -- s m h D M Y )</tt> and <tt>MS ( n -- )</tt> which pauses the program for at least ''n'' milliseconds. Particular Forth implementations give different access to millisecond and microsecond timers: |
||
{{works with|Win32Forth}} |
|||
'''Interpreters:''' [[Win32Forth]], [[GNU Forth]], [[bigFORTH]], iForth, PFE, SwiftForth, VFX Forth, MacForth |
|||
{{works with|GNU Forth}} |
|||
{{works with|bigFORTH}} |
|||
{{works with|iForth}} |
|||
{{works with|PFE}} |
|||
{{works with|SwiftForth}} |
|||
{{works with|VFX Forth}} |
|||
{{works with|MacForth}} |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
[UNDEFINED] MS@ [IF] \ Win32Forth (rolls over daily) |
|||
[DEFINED] ?MS [IF] ( -- ms ) |
|||
=={{header|Fortran}}== |
|||
: ms@ ?MS ; \ iForth |
|||
In ISO Fortran 90 or later, use the SYSTEM_CLOCK intrinsic subroutine:<syntaxhighlight lang="fortran">integer :: start, stop, rate |
|||
[ELSE] [DEFINED] cputime [IF] ( -- Dusec ) |
|||
real :: result |
|||
: ms@ cputime d+ 1000 um/mod nip ; \ gforth: Anton Ertl |
|||
[ELSE] [DEFINED] timer@ [IF] ( -- Dusec ) |
|||
! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!) |
|||
: ms@ timer@ >us 1000 um/mod nip ; \ bigForth |
|||
! optional 2nd integer argument (COUNT_RATE) is clock cycles per second |
|||
[ELSE] [DEFINED] gettimeofday [IF] ( -- usec sec ) |
|||
! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value |
|||
: ms@ gettimeofday 1000 MOD 1000 * SWAP 1000 / + ; \ PFE |
|||
call system_clock( start, rate ) |
|||
[ELSE] [DEFINED] counter [IF] |
|||
: ms@ counter ; \ SwiftForth |
|||
result = do_timed_work() |
|||
[ELSE] [DEFINED] GetTickCount [IF] |
|||
: ms@ GetTickCount ; \ VFX Forth |
|||
call system_clock( stop ) |
|||
[ELSE] [DEFINED] MICROSECS [IF] |
|||
: ms@ microsecs 1000 UM/MOD nip ; \ MacForth |
|||
print *, "elapsed time: ", real(stop - start) / real(rate)</syntaxhighlight>In ISO Fortran 95 or later, use the CPU_TIME intrinsic subroutine:<syntaxhighlight lang="fortran">real :: start, stop |
|||
[THEN] [THEN] [THEN] [THEN] [THEN] [THEN] [THEN] |
|||
real :: result |
|||
MS@ . \ print millisecond counter |
|||
! 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</syntaxhighlight> |
|||
=={{header|FreeBASIC}}== |
|||
<syntaxhighlight lang="freebasic">' FB 1.05.0 Win64 |
|||
Print Date + " " + Time '' returns system date/time in format : mm-dd-yyyy hh:mm:ss |
|||
Sleep</syntaxhighlight> |
|||
=={{header|Frink}}== |
|||
<syntaxhighlight lang="frink">println[now[]]</syntaxhighlight> |
|||
{{out}} |
|||
<pre>AD 2020-06-24 PM 06:37:01.326 (Wed) Mountain Daylight Time</pre> |
|||
=={{header|FutureBasic}}== |
|||
Time can be configured from simple to specialized in FB. Here's the simplest way. |
|||
<syntaxhighlight lang="futurebasic">window 1 |
|||
print time |
|||
print time(@"hh:mm:ss" ) |
|||
print time(@"h:mm a" ) |
|||
print time(@"h:mm a zzz") |
|||
HandleEvents</syntaxhighlight> |
|||
{{output}} |
|||
<pre> |
|||
19:30:58 |
|||
07:30:58 |
|||
7:30 PM |
|||
7:30 PM EDT |
|||
</pre> |
|||
More accurate timing... |
|||
<syntaxhighlight lang="futurebasic">window 1 |
|||
print fn CFAbsoluteTimeGetCurrent |
|||
print fn CACurrentMediaTime |
|||
print fn ProcessInfoSystemUptime |
|||
HandleEvents</syntaxhighlight> |
|||
=={{header|Gambas}}== |
|||
'''[https://gambas-playground.proko.eu/?gist=f061cc0cf175496b37bbcd14bd1e7058 Click this link to run this code]''' |
|||
<syntaxhighlight lang="gambas">Public Sub Main() |
|||
Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss") |
|||
End</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
Thursday 08 June 2017 15:58:41 |
|||
</pre> |
|||
=={{header|Genie}}== |
|||
<syntaxhighlight lang="genie">[indent=4] |
|||
init |
|||
var now = new DateTime.now_local() |
|||
print now.to_string()</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ valac systemTime.gs |
|||
prompt$ ./systemTime |
|||
2019-06-01T13:07:54-0400</pre> |
|||
=={{header|Go}}== |
|||
<syntaxhighlight lang="go">package main |
|||
import "time" |
|||
import "fmt" |
|||
func main() { |
|||
t := time.Now() |
|||
fmt.Println(t) // default format |
|||
fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format |
|||
}</syntaxhighlight> |
|||
=={{header|Groovy}}== |
|||
Solution (based on [[#Java|Java]] solution).<syntaxhighlight lang="groovy">def nowMillis = new Date().time |
|||
println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis</syntaxhighlight> |
|||
{{out}} |
|||
Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == 1243395159250 |
|||
=={{header|GUISS}}== |
|||
We can only show the clock, but this might not be set to system time:<syntaxhighlight lang="guiss">Taskbar</syntaxhighlight> |
|||
=={{header|Haskell}}== |
|||
<syntaxhighlight lang="haskell">import System.Time |
|||
(getClockTime, toCalendarTime, formatCalendarTime) |
|||
import System.Locale (defaultTimeLocale) |
|||
main :: IO () |
|||
main = do |
|||
ct <- getClockTime |
|||
print ct -- print default format, or |
|||
cal <- toCalendarTime ct |
|||
putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal</syntaxhighlight> |
|||
or with the time library: |
|||
<syntaxhighlight lang="haskell">import Data.Time (getZonedTime, formatTime, defaultTimeLocale) |
|||
main :: IO () |
|||
main = do |
|||
zt <- getZonedTime |
|||
print zt -- print default format, or |
|||
putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt</syntaxhighlight> |
|||
=={{header|HicEst}}== |
|||
<syntaxhighlight 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)</syntaxhighlight> |
|||
=={{header|HolyC}}== |
|||
<syntaxhighlight lang="holyc">CDateStruct ds; |
|||
Date2Struct(&ds, Now + local_time_offset); |
|||
Print("%04d-%02d-%02d %02d:%02d:%02d\n", ds.year, ds.mon, ds.day_of_mon, ds.hour, ds.min, ds.sec); |
|||
</syntaxhighlight> |
|||
=={{header|Hoon}}== |
|||
The time of the current system event is made available on the subject in most contexts as <tt>now</tt>. |
|||
<syntaxhighlight lang="hoon">now</syntaxhighlight>{{out}} |
|||
~2016.7.24..01.25.02..0f8e |
|||
Absolute times have 64-bit subsecond precision, which is used to ensure that no two system events have the same timestamp. |
|||
=={{header|Icon}} and {{header|Unicon}}== |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
{{out}} |
|||
<pre>&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</pre> |
|||
=={{header|IDL}}== |
|||
The <tt>systime()</tt> 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 <tt>utc</tt> flag is used: |
|||
print,systime() |
|||
Wed Feb 10 09:50:15 2010 |
|||
print,systime(/utc) |
|||
Wed Feb 10 17:50:10 2010 |
|||
=={{header|Io}}== |
|||
<syntaxhighlight lang="io">Date now println</syntaxhighlight>{{out}} |
|||
2008-08-26 00:15:52 EDT |
|||
=={{header|IS-BASIC}}== |
|||
<syntaxhighlight lang="is-basic">100 PRINT TIME$</syntaxhighlight> |
|||
=={{header|J}}== |
=={{header|J}}== |
||
The external verb <code>6!:0</code> 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.<syntaxhighlight lang="j"> 6!:0 '' |
|||
2008 1 23 12 52 10.341</syntaxhighlight> |
|||
A formatted string representation of the current time can also be returned:<syntaxhighlight lang="j"> 6!:0 'YYYY-MM-DD hh:mm:ss.sss' |
|||
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 accurate to thousandths. |
|||
2009-08-26 10:38:53.171</syntaxhighlight> |
|||
6!:0 <nowiki>''</nowiki> |
|||
=={{header|Java}}== |
=={{header|Java}}== |
||
{{works with|Java|1.5+}} |
|||
<syntaxhighlight lang="java">public class SystemTime{ |
|||
This shows the system time in [[POSIX]] time. |
|||
import java.util.Date; |
|||
public class SystemTime{ |
|||
public static void main(String[] args){ |
public static void main(String[] args){ |
||
System.out.format("%tc%n", System.currentTimeMillis()); |
|||
Date now = new Date(); |
|||
System.out.println(now.getTime()); |
|||
} |
} |
||
}</syntaxhighlight>{{out}} |
|||
} |
|||
Mon Jun 21 13:02:19 BST 2010 |
|||
Other methods are available in the <tt>Date</tt> object such as: getDay(), getHours(), getMinutes(), getSeconds(), getYear(), etc. |
|||
Or using <code>ZonedDateTime</code> object:<syntaxhighlight lang="java">import java.time.ZonedDateTime; |
|||
public class SystemTime{ |
|||
public static void main(String[] args){ |
|||
var now = ZonedDateTime.now(); |
|||
System.out.println(now); |
|||
} |
|||
}</syntaxhighlight> |
|||
=={{header|JavaScript}}== |
|||
<syntaxhighlight lang="javascript">console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT |
|||
console.log(Date.now()) // => 1306571005417 // Unix epoch</syntaxhighlight> |
|||
=={{header|Joy}}== |
|||
<syntaxhighlight lang="joy">time localtime "%T\n" strftime putchars.</syntaxhighlight> |
|||
=={{header|jq}}== |
|||
{{works with|jq |1.5}} |
|||
<syntaxhighlight lang="sh">$ jq -n 'now | [., todate]' |
|||
[ |
|||
1437619000.970498, |
|||
"2015-07-23T02:36:40Z" |
|||
]</syntaxhighlight> |
|||
"now" reports the number of seconds since the beginning of the [https://en.wikipedia.org/wiki/Unix_epoch Unix epoch]. |
|||
=={{header|Jsish}}== |
|||
Jsish does not implement the standard ECMAScript Date module but provides '''strftime''' and '''strptime'''. |
|||
<syntaxhighlight lang="javascript">console.log(strftime());</syntaxhighlight> |
|||
{{out}} using interactive echo of results |
|||
<pre> |
|||
prompt$ jsish |
|||
# strftime(); |
|||
"2019-02-20 19:43:20"</pre> |
|||
=={{header|Julia}}== |
|||
<syntaxhighlight lang="julia"> |
|||
ts = time() |
|||
println("The system time is (in ISO 8601 format):") |
|||
println(strftime(" %F %T %Z", ts)) |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
The system time is (in ISO 8601 format): |
|||
2015-04-08 14:19:38 CDT |
|||
</pre> |
|||
=={{header|Kotlin}}== |
|||
<syntaxhighlight lang="scala">// version 1.0.6 |
|||
fun main(args: Array<String>) { |
|||
println("%tc".format(System.currentTimeMillis())) |
|||
} |
|||
</syntaxhighlight> |
|||
=={{header|Lambdatalk}}== |
|||
<syntaxhighlight lang="scheme"> |
|||
{date} |
|||
-> 2021 02 22 07 23 12 |
|||
</syntaxhighlight> |
|||
=={{header|Lasso}}== |
|||
<syntaxhighlight lang="lasso">date->format('%Q %T') |
|||
date->asInteger</syntaxhighlight>{{out}} |
|||
2013-11-02 11:47:27 |
|||
1383407747 |
|||
=={{header|LFE}}== |
|||
{{trans|Erlang}} |
|||
By default, LFE timestamps are turned in the <code>#(megasecs secs microsecs)</code> format. |
|||
<syntaxhighlight lang="lisp"> |
|||
> (os:timestamp) |
|||
#(1423 786308 145798) |
|||
</syntaxhighlight> |
|||
These can be changed to the more common date/time stamp with the <code>calendar</code> module: |
|||
<syntaxhighlight lang="lisp"> |
|||
> (calendar:now_to_datetime (os:timestamp)) |
|||
#(#(2015 2 13) #(0 12 18)) |
|||
</syntaxhighlight> |
|||
Locale taken into account: |
|||
<syntaxhighlight lang="lisp"> |
|||
> (calendar:now_to_universal_time (os:timestamp)) |
|||
#(#(2015 2 13) #(0 13 51)) |
|||
> (calendar:now_to_local_time (os:timestamp)) |
|||
#(#(2015 2 12) #(16 14 26)) |
|||
</syntaxhighlight> |
|||
Note that you will often encounter the function <code>erlang:now/0</code> giving a time similar to the system time. However, <code>erlang:now/0</code> may get delayed if the system time changes suddenly (i.e.: coming back from sleep mode). The delay is in place to ensure that <code>receive</code> clauses which are millisecond-sensitive do not get false timeouts. |
|||
=={{header|Liberty BASIC}}== |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
=={{header|LIL}}== |
|||
The '''system''' command is provided in the lil shell. On GNU/Linux: |
|||
<syntaxhighlight lang="tcl">print [system date]; print [system date +%s.%N]</syntaxhighlight> |
|||
<pre>Fri Aug 23 20:50:08 EDT 2019 |
|||
1566607808.225126400</pre> |
|||
=={{header|Lingo}}== |
|||
<syntaxhighlight lang="lingo">put time() |
|||
-- "03:45" |
|||
put date() |
|||
-- "01.10.2016" |
|||
put the systemdate |
|||
-- date( 2016, 10, 1 ) |
|||
put the systemdate.seconds |
|||
-- 13950 |
|||
-- milliseconds since last boot, due to higher resolution better suited for random number seeding |
|||
put _system.milliseconds |
|||
-- 41746442</syntaxhighlight> |
|||
=={{header|LiveCode}}== |
|||
<syntaxhighlight lang="livecode">put the system time</syntaxhighlight> |
|||
=={{header|Locomotive Basic}}== |
|||
The variable "time" contains the time elapsed since last system start or reset. Each unit equals 1/300 s.<syntaxhighlight lang="locobasic">print time |
|||
print time/300;"s since last reboot"</syntaxhighlight> |
|||
=={{header|Logo}}== |
|||
{{works with|UCB Logo}} |
|||
Other Logo variants might have a built-in command, but UCB Logo must access the Unix shell to get time.<syntaxhighlight lang="logo"> |
|||
to time |
|||
output first first shell [date +%s] |
|||
end |
|||
make "start time |
|||
wait 300 ; 60ths of a second |
|||
print time - :start ; 5</syntaxhighlight> |
|||
=={{header|Lua}}== |
|||
<syntaxhighlight lang="lua">print(os.date())</syntaxhighlight> |
|||
=={{header|M2000 Interpreter}}== |
|||
<syntaxhighlight lang="m2000 interpreter"> |
|||
print str$(now,"long time"), time$(now) |
|||
</syntaxhighlight> |
|||
=={{header|Mathematica}}/{{header|Wolfram Language}}== |
|||
Different ways of doing this, here are 2 most common:<syntaxhighlight lang="mathematica">Print[DateList[]] |
|||
Print[AbsoluteTime[]]</syntaxhighlight>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. |
|||
=={{header|MATLAB}} / {{header|Octave}}== |
|||
<syntaxhighlight lang="matlab"> datestr(now)</syntaxhighlight><pre>ans = |
|||
13-Aug-2010 12:59:56</pre><syntaxhighlight lang="matlab"> clock</syntaxhighlight><pre>ans = |
|||
2010 8 13 12 59 56.52</pre> |
|||
=={{header|Maxima}}== |
|||
<syntaxhighlight lang="maxima">/* Time and date in a formatted string */ |
|||
timedate(); |
|||
"2012-08-27 20:26:23+10:00" |
|||
/* Time in seconds elapsed since 1900/1/1 0:0:0 */ |
|||
absolute_real_time(); |
|||
/* Time in seconds since Maxima was started */ |
|||
elapsed_real_time(); |
|||
elapsed_run_time();</syntaxhighlight> |
|||
=={{header|Microsoft Small Basic}}== |
|||
Date and time follows the user's locale. |
|||
<syntaxhighlight lang="smallbasic">TextWindow.WriteLine(Clock.Date + " " + Clock.Time)</syntaxhighlight> |
|||
{{out}} |
|||
<pre>02/12/2022 8:27:15 PM |
|||
Press any key to continue...</pre> |
|||
=={{header|min}}== |
|||
{{works with|min|0.27.1}} |
|||
<syntaxhighlight lang="min">now datetime puts!</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
2021-01-09T17:41:59Z |
|||
</pre> |
|||
=={{header|Modula-2}}== |
|||
{{works with|ADW Modula-2|any (Compile with the linker option ''Console Application'').}} |
|||
<syntaxhighlight lang="modula2"> |
|||
MODULE Mytime; |
|||
FROM SysClock IMPORT |
|||
GetClock, DateTime; |
|||
FROM STextIO IMPORT |
|||
WriteString, WriteLn; |
|||
FROM FormatDT IMPORT |
|||
DateTimeToString; |
|||
VAR |
|||
CurrentTime: DateTime; |
|||
DateStr, TimeStr: ARRAY [0 .. 20] OF CHAR; |
|||
BEGIN |
|||
GetClock(CurrentTime); |
|||
DateTimeToString(CurrentTime, DateStr, TimeStr); |
|||
WriteString("Current time: "); |
|||
WriteString(DateStr); |
|||
WriteString(" "); |
|||
WriteString(TimeStr); |
|||
WriteLn; |
|||
END Mytime. |
|||
</syntaxhighlight> |
|||
=={{header|Modula-3}}== |
|||
<syntaxhighlight lang="modula3">MODULE MyTime EXPORTS Main; |
|||
IMPORT IO, FmtTime, Time; |
|||
BEGIN |
|||
IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n"); |
|||
END MyTime.</syntaxhighlight>{{out}} |
|||
Current time: Tue Dec 30 20:50:07 CST 2008 |
|||
=={{header|MUMPS}}== |
|||
System time since midnight (in seconds) is kept in the second part of the system variable $HOROLOG.<syntaxhighlight 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</syntaxhighlight>Usage:<pre>USER>D SYSTIME^ROSETTA |
|||
The system time is 22:55:44</pre> |
|||
=={{header|Nanoquery}}== |
|||
<syntaxhighlight lang="nanoquery">import Nanoquery.Util |
|||
println new(Date).getTime()</syntaxhighlight> |
|||
=={{header|Neko}}== |
|||
<syntaxhighlight lang="actionscript">/** |
|||
<doc> |
|||
<h2>System time</h2> |
|||
<p>Neko uses Int32 to store system date/time values. |
|||
And lib C strftime style formatting for converting to string form</p> |
|||
</doc> |
|||
*/ |
|||
var date_now = $loader.loadprim("std@date_now", 0) |
|||
var date_format = $loader.loadprim("std@date_format", 2) |
|||
var now = date_now() |
|||
$print(now, " ", date_format(now, "%T"), "\n")</syntaxhighlight> |
|||
{{out}} |
|||
<pre>prompt$ nekoc system-time.neko |
|||
prompt$ neko system-time.n |
|||
1542158592 20:23:12</pre> |
|||
=={{header|Nemerle}}== |
|||
<syntaxhighlight lang="nemerle">System.Console.Write(System.DateTime.Now);</syntaxhighlight> |
|||
=={{header|NetRexx}}== |
|||
<syntaxhighlight lang="netrexx"> |
|||
import java.text.SimpleDateFormat |
|||
say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date())</syntaxhighlight> |
|||
=={{header|NewLISP}}== |
|||
<syntaxhighlight lang="newlisp">> (date) |
|||
"Sun Sep 28 20:17:55 2014"</syntaxhighlight> |
|||
=={{header|Nim}}== |
|||
<syntaxhighlight lang="nim">import times |
|||
echo getDateStr() |
|||
echo getClockStr() |
|||
echo getTime() |
|||
echo now() # shorthand for "getTime().local"</syntaxhighlight> |
|||
{{out}} |
|||
<pre>2021-04-21 |
|||
00:28:01 |
|||
2021-04-21T00:28:01+02:00 |
|||
2021-04-21T00:28:01+02:00</pre> |
|||
=={{header|Objeck}}== |
|||
<syntaxhighlight lang="objeck">function : Time() ~ Nil { |
|||
t := Time->New(); |
|||
IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds()); |
|||
}</syntaxhighlight> |
|||
=={{header|Objective-C}}== |
|||
<syntaxhighlight lang="objc">NSLog(@"%@", [NSDate date]);</syntaxhighlight>or (deprecated)<syntaxhighlight lang="objc">NSLog(@"%@", [NSCalendarDate calendarDate]);</syntaxhighlight> |
|||
=={{header|OCaml}}== |
|||
<syntaxhighlight 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;</syntaxhighlight> |
|||
=={{header|Oforth}}== |
|||
System.tick is used to retrieve a tick from the system in order to compute small intervals of time. It is used by #bench method to compute duration of a runnable (unit is micro second). |
|||
<syntaxhighlight lang="oforth">System.tick println |
|||
#[ #sqrt 1000000 seq map sum println ] bench</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
707095319487 |
|||
666667166.458841 |
|||
259819 |
|||
</pre> |
|||
System.localTime returns number of micro seconds since 01/01/1970:00:00:00 |
|||
Integer returned by System.localTime allows to create a Date object. |
|||
<syntaxhighlight lang="oforth">import: date |
|||
System.localTime dup println asDate println drop drop</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
1421095428478000 |
|||
2015-01-12 21:43:48,478 |
|||
</pre> |
|||
=={{header|Oz}}== |
|||
<syntaxhighlight 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}}</syntaxhighlight>{{out}} |
|||
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) |
|||
=={{header|PARI/GP}}== |
|||
For timing the <code>gettime</code> is usually used, which measures CPU time rather than walltime. But to get the raw time you'll need a system call |
|||
<syntaxhighlight lang="parigp">system("date")</syntaxhighlight> |
|||
Direct access to the C library <code>time()</code> function can be had by an <code>install()</code>, and it should be faster than running the date program. |
|||
<syntaxhighlight lang="parigp">install(time, "lf"); |
|||
t = time(); |
|||
print(t); \\ integer seconds since the epoch (usually 1 Jan 1970)</syntaxhighlight> |
|||
<code>install()</code> can't give the higher resolution C library time functions like <code>gettimeofday()</code> or <code>clock_gettime()</code> but some further C code could put their results into a Pari integer or rational suitable for <code>install()</code> in GP. |
|||
=={{header|Pascal}}== |
|||
{{works with|Extended Pascal}} |
|||
Extended Pascal, as defined by the ISO standard 10206, defines a <tt>record</tt> data type that at least identifies the following members:<syntaxhighlight lang="pascal">type |
|||
timeStamp = packed record |
|||
dateValid: Boolean; |
|||
year: integer; |
|||
month: 1..12; |
|||
day: 1..31; |
|||
timeValid: Boolean; |
|||
hour: 0..23; |
|||
minute: 0..59; |
|||
second: 0..59; |
|||
end;</syntaxhighlight>A variable of this built-in data type can be populated with the <tt>getTimeStamp</tt> procedure as demostrated below:<syntaxhighlight lang="pascal">program systemTime(output); |
|||
var |
|||
ts: timeStamp; |
|||
begin |
|||
getTimeStamp(ts); |
|||
{ |
|||
If `getTimeStamp` is unable to obtain the time, it will |
|||
set `timeValid` to `false` and `hour`, `minute` and |
|||
`second` are set to a time representing midnight (0:00:00). |
|||
} |
|||
if ts.timeValid then |
|||
begin |
|||
writeLn(time(ts)); |
|||
end; |
|||
end.</syntaxhighlight> |
|||
{{out}} |
|||
{{CURRENTTIME}}:42 |
|||
The <tt>string</tt> representation generated by the standard function <tt>time</tt> is implementation-defined. |
|||
The shown output was generated by a <tt>program</tt> compiled with the GPC, the GNU Pascal Compiler. |
|||
A different processor might generate different output, for instance in an “AM”/“PM” format. |
|||
=={{header|PascalABC.NET}}== |
|||
<syntaxhighlight lang="delphi"> |
|||
## |
|||
Print(DateTime.Now) |
|||
</syntaxhighlight> |
|||
=={{header|Perl}}== |
|||
Simple localtime use in scalar context.<syntaxhighlight lang="perl">print scalar localtime, "\n";</syntaxhighlight>{{out}} |
|||
Thu Jan 24 11:23:30 2008 |
|||
localtime use in array context.<syntaxhighlight 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</syntaxhighlight> |
|||
{{out}} |
|||
2008-01-24 11:23:30 |
|||
The same using DateTime:<syntaxhighlight lang="perl">use DateTime; |
|||
my $dt = DateTime->now; |
|||
my $d = $dt->ymd; |
|||
my $t = $dt->hms; |
|||
print "$d $t\n";</syntaxhighlight>{{out}} |
|||
2010-03-29 19:46:26 |
|||
localtime use in array context with [[POSIX]] strftime:<syntaxhighlight lang="perl">use POSIX qw(strftime); |
|||
$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime; |
|||
print "$now_string\n";</syntaxhighlight>Output (with cs_CZ.UTF-8 locale): |
|||
<pre>Čt led 24 11:23:30 2008</pre>Using the [http://search.cpan.org/perldoc?DateTime DateTime] module:<syntaxhighlight lang="perl">use DateTime; |
|||
my $dt = DateTime->now; |
|||
say $dt->iso8601(); |
|||
say $dt->year_with_christian_era(); |
|||
say $dt->year_with_secular_era(); |
|||
# etc.</syntaxhighlight>Unix epoch:<syntaxhighlight lang="perl">print time;</syntaxhighlight>{{out}} |
|||
1280473609 |
|||
=={{header|Phix}}== |
|||
{{libheader|Phix/basics}} |
|||
<!--<syntaxhighlight lang="phix">--> |
|||
<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;">date</span><span style="color: #0000FF;">(),</span><span style="color: #008000;">"Dddd, Mmmm dth, YYYY, h:mm:ss pm"</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #004080;">atom</span> <span style="color: #000000;">t0</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">time</span><span style="color: #0000FF;">()</span> |
|||
<span style="color: #7060A8;">sleep</span><span style="color: #0000FF;">(</span><span style="color: #000000;">0.9</span><span style="color: #0000FF;">)</span> |
|||
<span style="color: #0000FF;">?</span><span style="color: #7060A8;">time</span><span style="color: #0000FF;">()-</span><span style="color: #000000;">t0</span> |
|||
<!--</syntaxhighlight>--> |
|||
{{out}} |
|||
<pre> |
|||
"Tuesday, July 12th, 2016, 11:30:07 am" |
|||
0.906 |
|||
</pre> |
|||
Note the system clock tick rate mean times can be out by ~0.0155s; |
|||
it is not unusual to see total elapsed times of 0,0,0,0.016,0.016,0.016,0.031,0.031,0.031, etc. |
|||
=={{header|Phixmonti}}== |
|||
<syntaxhighlight lang="phixmonti">def printList len for get print endfor enddef |
|||
time |
|||
"Actual time is " swap 1 get " hour, " rot 2 get " minutes, " rot 3 get nip " seconds, " |
|||
"and elapsed " msec " seconds of running time." 10 tolist printList</syntaxhighlight> |
|||
=={{header|PHP}}== |
|||
Seconds since the Unix epoch:<syntaxhighlight lang="php">echo time(), "\n";</syntaxhighlight> |
|||
Microseconds since the Unix epoch:<syntaxhighlight lang="php">echo microtime(), "\n";</syntaxhighlight>Formatted time:<syntaxhighlight 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</syntaxhighlight> |
|||
=={{header|PicoLisp}}== |
|||
<syntaxhighlight lang="picolisp">(stamp)</syntaxhighlight>{{out}} |
|||
-> "2010-02-19 15:14:06 |
|||
=={{header|Pike}}== |
|||
<syntaxhighlight lang="pike">write( ctime(time()) );</syntaxhighlight> |
|||
{{Out}} |
|||
<pre> |
|||
Thu Jan 2 23:58:19 2020 |
|||
</pre> |
|||
=={{header|PL/I}}== |
|||
<syntaxhighlight 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. */</syntaxhighlight> |
|||
=={{header|PowerShell}}== |
|||
Using a cmdlet:<syntaxhighlight lang="powershell">Get-Date</syntaxhighlight>or using .NET classes and properties:<syntaxhighlight lang="powershell">[DateTime]::Now</syntaxhighlight> |
|||
=={{header|Prolog}}== |
|||
==={{header|GNU_Prolog}}=== |
|||
{{works with|GNU Prolog}} |
|||
<syntaxhighlight lang="prolog">date_time(H).</syntaxhighlight> |
|||
{{out}} |
|||
<pre>H = dt(2022,1,23,21,37,16)</pre> |
|||
==={{header|B-Prolog}}=== |
|||
{{works with|B-Prolog}} |
|||
<syntaxhighlight lang="prolog">time(H,M,S)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
H = 21 |
|||
M = 37 |
|||
S = 16 |
|||
</pre> |
|||
{{works with|B-Prolog}} |
|||
<syntaxhighlight lang="prolog">date(Y,M,D)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Y = 2022 |
|||
M = 1 |
|||
D = 23 |
|||
</pre> |
|||
=={{header|PureBasic}}== |
|||
<syntaxhighlight 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</syntaxhighlight> |
|||
=={{header|Python}}== |
|||
<syntaxhighlight lang="python">import time |
|||
print time.ctime()</syntaxhighlight> |
|||
=={{header|Q}}== |
|||
Date & time are accessible via the virtual .z namespace. lowercase names are UTC, uppercase are local:<syntaxhighlight 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</syntaxhighlight> |
|||
=={{header|Quackery}}== |
|||
<syntaxhighlight lang="quackery">time 1000000 / echo say " seconds since the Unix epoch."</syntaxhighlight> |
|||
'''Output''' |
|||
<pre>1610201941 seconds since the Unix epoch.</pre> |
|||
=={{header|R}}== |
|||
{{works with|R|2.8.1}} |
|||
Note that this is output as a standard style string.<syntaxhighlight lang="r">Sys.time()</syntaxhighlight>{{out}} |
|||
[1] "2009-07-27 15:27:04 PDT" |
|||
=={{header|Racket}}== |
|||
The system time as a date string: |
|||
<syntaxhighlight lang="racket">#lang racket |
|||
(require racket/date) |
|||
(date->string (current-date))</syntaxhighlight> |
|||
Or, as seconds after midnight UTC, January 1, 1970:<syntaxhighlight lang="racket">#lang racket |
|||
(current-seconds)</syntaxhighlight> |
|||
=={{header|Raku}}== |
|||
(formerly Perl 6) |
|||
<syntaxhighlight lang="raku" line>say DateTime.now; |
|||
dd DateTime.now.Instant;</syntaxhighlight> |
|||
{{out}} |
|||
2015-11-02T13:34:09+01:00 |
|||
Instant $var = Instant.new(<2159577143734/1493>) |
|||
=={{header|Raven}}== |
|||
Note the use of single quotation marks for the date specifier.<syntaxhighlight lang="text">time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date</syntaxhighlight> |
|||
{{out}} |
|||
1353352623.511231 |
|||
Tue Nov 20 05:17:03 2012 |
|||
=={{header|REBOL}}== |
|||
<syntaxhighlight lang="rebol">now |
|||
print rejoin [now/year "-" now/month "-" now/day " " now/time]</syntaxhighlight>{{out}} |
|||
10-Dec-2009/7:43:55-5:00 |
|||
2009-12-10 7:43:55 |
|||
=={{header|Retro}}== |
|||
Displays the number of seconds since the Unix epoch: |
|||
<syntaxhighlight lang="retro">time putn</syntaxhighlight> |
|||
=={{header|REXX}}== |
|||
Note that REXX only examines the first character of the option and can be in upper or lower case. |
|||
<syntaxhighlight lang="rexx">/*REXX program shows various ways to display the system time, including other options. */ |
|||
say '════════════ Normal format of time' |
|||
say 'hh:mm:ss ◄─────────────── hh= is 00 ──► 23' |
|||
say 'hh:mm:ss ◄─────────────── hh= hour mm= minute ss= second' |
|||
say time() |
|||
say time('n') /* (same as the previous example.) */ |
|||
say time('N') /* " " " " " */ |
|||
say time('Normal') /* " " " " " */ |
|||
say time('nitPick') /* " " " " " */ |
|||
say |
|||
say '════════════ Civil format of time' |
|||
say 'hh:mmcc ◄─────────────── hh= is 1 ──► 12' |
|||
say 'hh:mmam ◄─────────────── hh= hour mm= minute am= ante meridiem' |
|||
say 'hh:mmpm ◄─────────────── pm= post meridiem' |
|||
say time('C') |
|||
say time('civil') /* (same as the previous example.) */ |
|||
/*ante meridiem≡Latin for before midday*/ |
|||
/*post " " " after " */ |
|||
say |
|||
say '════════════ long format of time' |
|||
say 'hh:mm:ss ◄─────────────── hh= is 0 ──► 23' |
|||
say 'hh:mm:ss.ffffff ◄─────────────── hh= hour mm= minute fffff= fractional seconds' |
|||
say time('L') |
|||
say time('long') /* (same as the previous example.) */ |
|||
say time('long time no see') /* " " " " " */ |
|||
say |
|||
say '════════════ complete hours since midnight' |
|||
say 'hh ◄─────────────── hh = 0 ───► 23' |
|||
say time('H') |
|||
say time('hours') /* (same as the previous example.) */ |
|||
say |
|||
say '════════════ complete minutes since midnight' |
|||
say 'mmmm ◄─────────────── mmmm = 0 ───► 1439' |
|||
say time('M') |
|||
say time('minutes') /* (same as the previous example.) */ |
|||
say |
|||
say '════════════ complete seconds since midnight' |
|||
say 'sssss ◄─────────────── sssss = 0 ───► 86399' |
|||
say time('S') |
|||
say time('seconds') /* (same as the previous example.) */ |
|||
/*stick a fork in it, we're all done. */</syntaxhighlight> |
|||
{{out|output|:}} |
|||
<pre> |
|||
════════════ Normal format of time |
|||
hh:mm:ss ◄─────────────── hh= is 00 ──► 23 |
|||
hh:mm:ss ◄─────────────── hh= hour mm= minute ss= second |
|||
19:59:40 |
|||
19:59:40 |
|||
19:59:40 |
|||
19:59:40 |
|||
19:59:40 |
|||
════════════ Civil format of time |
|||
hh:mmcc ◄─────────────── hh= is 1 ──► 12 |
|||
hh:mmam ◄─────────────── hh= hour mm= minute am= ante meridiem |
|||
hh:mmpm ◄─────────────── pm= post meridiem |
|||
7:59pm |
|||
7:59pm |
|||
════════════ long format of time |
|||
hh:mm:ss ◄─────────────── hh= is 0 ──► 23 |
|||
hh:mm:ss.ffffff ◄─────────────── hh= hour mm= minute fffff= fractional seconds |
|||
19:59:40.250000 |
|||
19:59:40.250000 |
|||
19:59:40.250000 |
|||
════════════ complete hours since midnight |
|||
hh ◄─────────────── hh = 0 ───► 23 |
|||
19 |
|||
19 |
|||
════════════ complete minutes since midnight |
|||
mmmm ◄─────────────── mmmm = 0 ───► 1439 |
|||
1199 |
|||
1199 |
|||
════════════ complete seconds since midnight |
|||
sssss ◄─────────────── sssss = 0 ───► 86399 |
|||
71980 |
|||
71980 |
|||
</pre> |
|||
=={{header|Ring}}== |
|||
<syntaxhighlight lang="ring"> |
|||
/* Output: |
|||
** Sun abbreviated weekday name |
|||
** Sunday full weekday name |
|||
** May abbreviated month name |
|||
** May full month name |
|||
** 05/24/15 09:58:38 Date & Time |
|||
** 24 Day of the month |
|||
** 09 Hour (24) |
|||
** 09 Hour (12) |
|||
** 144 Day of the year |
|||
** 05 Month of the year |
|||
** 58 Minutes after hour |
|||
** AM AM or PM |
|||
** 38 Seconds after the hour |
|||
** 21 Week of the year (sun-sat) |
|||
** 0 day of the week |
|||
** 05/24/15 date |
|||
** 09:58:38 time |
|||
** 15 year of the century |
|||
** 2015 year |
|||
** Arab Standard Time time zone |
|||
** % percent sign |
|||
*/ |
|||
See TimeList() |
|||
</syntaxhighlight> |
|||
=={{header|RPL}}== |
|||
Since 1990, there is a command named <code>TICKS</code> which returns the system time in 1/8192ths of a second, using a 64-bit unsigned integer: |
|||
{{out}} |
|||
<pre> |
|||
1: #1DBC0D1698BE0h |
|||
</pre> |
|||
There is also a <code>TIME</code> command, returning the system time in a hh.mmss format: |
|||
'''Output:''' |
|||
1: 20.4526471679 <span style="color:grey">@ 8:45:26 PM</span> |
|||
=={{header|Ruby}}== |
|||
version 1.9+<syntaxhighlight lang="ruby">t = Time.now |
|||
# textual |
|||
puts t # => 2013-12-27 18:00:23 +0900 |
|||
# epoch time |
|||
puts t.to_i # => 1388134823 |
|||
# epoch time with fractional seconds |
|||
puts t.to_f # => 1388134823.9801579 |
|||
# epoch time as a rational (more precision): |
|||
puts Time.now.to_r # 1424900671883862959/1000000000 |
|||
</syntaxhighlight> |
|||
=={{header|Rust}}== |
|||
<syntaxhighlight lang="rust">// 20210210 Rust programming solution |
|||
extern crate chrono; |
|||
use chrono::prelude::*; |
|||
fn main() { |
|||
let utc: DateTime<Utc> = Utc::now(); |
|||
println!("{}", utc.format("%d/%m/%Y %T")); |
|||
} |
|||
</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
10/02/2021 16:26:23 |
|||
</pre> |
|||
=={{header|Scala}}== |
|||
{{libheader|Scala}}Ad hoc solution as [http://en.wikipedia.org/wiki/Read%E2%80%93eval%E2%80%93print_loop REPL] scripts: |
|||
===JDK < 8=== |
|||
<syntaxhighlight lang="scala">println(new java.util.Date)</syntaxhighlight>{{out}} |
|||
Sun Aug 14 22:47:42 EDT 2011 |
|||
===JDK >= 8 (recommended)=== |
|||
<syntaxhighlight lang="scala">println(java.time.LocalTime.now())</syntaxhighlight>{{out}} |
|||
11:32:39.002 |
|||
=={{header|Scheme}}== |
|||
{{works with|Chicken Scheme}}<syntaxhighlight lang="scheme">(use posix) |
|||
(seconds->string (current-seconds))</syntaxhighlight>{{out}} |
|||
"Sat May 16 21:42:47 2009" |
|||
{{works with|Chez Scheme}} |
|||
<syntaxhighlight lang="scheme">(display (date-and-time)) (newline)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
Mon Jun 27 19:51:09 2022 |
|||
</pre> |
|||
=={{header|Seed7}}== |
|||
<syntaxhighlight lang="seed7">$ include "seed7_05.s7i"; |
|||
include "time.s7i"; |
|||
const proc: main is func |
|||
begin |
|||
writeln(time(NOW)); |
|||
end func;</syntaxhighlight>{{out}} |
|||
2009-12-07 17:09:44.687500 UTC+1 |
|||
=={{header|SETL}}== |
|||
<syntaxhighlight lang="setl">$ Unix time |
|||
print(tod); |
|||
$ Human readable time and date |
|||
print(date);</syntaxhighlight> |
|||
{{out}} |
|||
<syntaxhighlight lang="setl"> |
|||
1447628158908 |
|||
Sun Nov 15 22:55:58 2015 |
|||
</syntaxhighlight> |
|||
=={{header|Sidef}}== |
|||
<syntaxhighlight lang="ruby"># textual |
|||
say Time.local.ctime; # => Thu Mar 19 15:10:41 2015 |
|||
# epoch time |
|||
say Time.sec; # => 1426770641 |
|||
# epoch time with fractional seconds |
|||
say Time.micro_sec; # => 1426770641.68409</syntaxhighlight> |
|||
=={{header|Smalltalk}}== |
|||
{{works with|GNU Smalltalk}}<syntaxhighlight lang="smalltalk">DateTime now displayNl.</syntaxhighlight>{{out}} |
|||
2011-08-10T00:43:36-0-7:00 |
|||
{{works with|Pharo}}{{works with|Smalltalk/X}}<syntaxhighlight lang="smalltalk">DateAndTime now</syntaxhighlight>{{out}} |
|||
2011-08-16T19:40:37-03:00 |
|||
=={{header|SNOBOL4}}== |
|||
<syntaxhighlight lang="snobol4"> OUTPUT = DATE() |
|||
END</syntaxhighlight>{{out}} |
|||
03/30/2010 20:58:09 |
|||
=={{header|SPL}}== |
|||
<syntaxhighlight lang="spl">hour,min,sec = #.now() |
|||
day,month,year = #.today() |
|||
#.output(#.str(hour,"00:"),#.str(min,"00:"),#.str(sec,"00.000")) |
|||
#.output(day,".",#.str(month,"00"),".",year)</syntaxhighlight> |
|||
{{out}} |
|||
<pre> |
|||
03:15:34.068 |
|||
24.08.2017 |
|||
</pre> |
|||
=={{header|SQL PL}}== |
|||
{{works with|Db2 LUW}} |
|||
<syntaxhighlight lang="sql pl"> |
|||
SELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1; |
|||
</syntaxhighlight> |
|||
Output: |
|||
<pre> |
|||
db2 -t |
|||
db2 => SELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1; |
|||
1 2 3 |
|||
---------- -------- -------------------------- |
|||
04/29/2018 14:27:10 2018-04-29-14.27.10.674182 |
|||
1 record(s) selected. |
|||
</pre> |
|||
=={{header|Standard ML}}== |
|||
<syntaxhighlight lang="sml">print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n")</syntaxhighlight> |
|||
=={{header|Stata}}== |
|||
<syntaxhighlight lang="stata">di c(current_date) |
|||
di c(current_time)</syntaxhighlight> |
|||
=={{header|Swift}}== |
|||
<syntaxhighlight lang="swift">import Foundation |
|||
var ⌚️ = NSDate() |
|||
println(⌚️)</syntaxhighlight>{{out}} |
|||
2014-06-22 20:43:42 +0000 |
|||
=={{header|Tcl}}== |
|||
This uses a timestamp that is a number of seconds since the start of the UNIX Epoch.<syntaxhighlight lang="tcl">puts [clock seconds]</syntaxhighlight> |
|||
More readable forms may be created by formatting the time:<syntaxhighlight lang="tcl">puts [clock format [clock seconds]]</syntaxhighlight> |
|||
=={{header|TI-89 BASIC}}== |
|||
<syntaxhighlight lang="ti89b">■ getTime() {13 28 55} |
|||
■ getDate() {2009 8 13}</syntaxhighlight>Note that the system clock can be turned off, in which case the value returned will remain constant. <tt>isClkOn()</tt> can be used to check it. |
|||
=={{header|True BASIC}}== |
|||
<syntaxhighlight lang="qbasic">PRINT DATE$ |
|||
! returns system date in format: “YYYYMMDD”. |
|||
! Here YYYY is the year, MM is the month number, and DD is the day number. |
|||
PRINT TIME$ |
|||
! returns system time in format: “HH:MM:SS”. |
|||
END</syntaxhighlight> |
|||
=={{header|TUSCRIPT}}== |
|||
<syntaxhighlight lang="tuscript"> |
|||
$$ MODE TUSCRIPT |
|||
time=time() |
|||
PRINT time</syntaxhighlight>{{out}} |
|||
2011-04-05 13:45:44 |
|||
=={{header|UNIX Shell}}== |
|||
<syntaxhighlight lang="bash">date # Thu Dec 3 15:38:06 PST 2009 |
|||
date +%s # 1259883518, seconds since the epoch, like C stdlib time(0)</syntaxhighlight> |
|||
=={{header|Ursa}}== |
|||
<syntaxhighlight lang="ursa"># outputs time in milliseconds |
|||
import "time" |
|||
out (time.getcurrent) endl console</syntaxhighlight> |
|||
=={{header|Ursala}}== |
|||
A library function, now, ignores its argument and returns the system time as a character string.<syntaxhighlight lang="ursala">#import cli |
|||
#cast %s |
|||
main = now 0</syntaxhighlight>{{out}} |
|||
'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. |
|||
=={{header|Vala}}== |
|||
<syntaxhighlight lang="vala"> |
|||
var now = new DateTime.now_local(); |
|||
string now_string = now.to_string();</syntaxhighlight>{{out}} |
|||
2011-11-12T20:23:24-0800 |
|||
=={{header|VBA}}== |
|||
<syntaxhighlight lang="vb">Debug.Print Now()</syntaxhighlight> |
|||
{{out}} |
|||
12/12/2013 16:16:16 |
|||
=={{header|VBScript}}== |
|||
<syntaxhighlight lang="vb">WScript.Echo Now</syntaxhighlight> |
|||
=={{header|V (Vlang)}}== |
|||
<syntaxhighlight lang="v (vlang)">import time |
|||
fn main() { |
|||
t := time.Now() |
|||
println(t) // default format YYYY-MM-DD HH:MM:SS |
|||
println(t.custom_format("ddd MMM d HH:mm:ss YYYY")) // some custom format |
|||
}</syntaxhighlight> |
|||
=={{header|Wren}}== |
|||
{{libheader|Wren-date}} |
|||
Although Wren CLI can tell how much time has elapsed since the script started, it currently has no way of knowing what the time was then or what the time is now (in the current locale) unless the user passes the former as a command line argument. |
|||
<syntaxhighlight lang="wren">import "os" for Process |
|||
import "./date" for Date |
|||
var args = Process.arguments |
|||
if (args.count != 1) Fiber.abort("Please pass the current time in hh:mm:ss format.") |
|||
var startTime = Date.parse(args[0], Date.isoTime) |
|||
for (i in 0..1e8) {} // do something which takes a bit of time |
|||
var now = startTime.addMillisecs((System.clock * 1000).round) |
|||
Date.default = Date.isoTime + "|.|ttt" |
|||
System.print("Time now is %(now)")</syntaxhighlight> |
|||
{{out}} |
|||
Sample session. |
|||
<pre> |
|||
$ wren systemTime.wren 19:00:00 |
|||
Time now is 19:00:01.992 |
|||
</pre> |
|||
=={{header|XPL0}}== |
|||
The intrinsics GetReg and SoftInt are used to access DOS and BIOS routines. GetReg returns the address of an array where a copy of the processor's hardware registers are stored. Values (such as $2C00 in the example) can be stored into this array. When SoftInt is called, the values in the array are loaded into the processor's registers and the specified interrupt ($21 in the example) is called.<syntaxhighlight lang="xpl0">include c:\cxpl\codes; \include intrinsic 'code' declarations |
|||
proc NumOut(N); \Output a 2-digit number, including leading zero |
|||
int N; |
|||
[if N <= 9 then ChOut(0, ^0); |
|||
IntOut(0, N); |
|||
]; \NumOut |
|||
int Reg; |
|||
[Reg:= GetReg; \get address of array with copy of CPU registers |
|||
Reg(0):= $2C00; \call DOS function 2C (hex) |
|||
SoftInt($21); \DOS calls are interrupt 21 (hex) |
|||
NumOut(Reg(2) >> 8); \the high byte of register CX contains the hours |
|||
ChOut(0, ^:); |
|||
NumOut(Reg(2) & $00FF); \the low byte of CX contains the minutes |
|||
ChOut(0, ^:); |
|||
NumOut(Reg(3) >> 8); \the high byte of DX contains the seconds |
|||
ChOut(0, ^.); |
|||
NumOut(Reg(3) & $00FF); \the low byte of DX contains hundreths |
|||
CrLf(0); |
|||
]</syntaxhighlight>{{out}} |
|||
13:08:26.60 |
|||
=={{header|Yabasic}}== |
|||
<syntaxhighlight lang="yabasic">print time$</syntaxhighlight> |
|||
== |
=={{header|zkl}}== |
||
<syntaxhighlight lang="zkl">Time.Clock.time //-->seconds since the epoch (C/OS defined)</syntaxhighlight> |
|||
[[Date format]] |
|||
{{omit from|Axe}} |
|||
[http://en.wikipedia.org/wiki/Time_%28computing%29#Retrieving_system_time Retrieving system time (wiki)] |
|||
{{omit from|bc}} |
|||
{{omit from|dc}} |
Latest revision as of 19:35, 9 June 2024
You are encouraged to solve this task according to the task description, using any language you may know.
- Task
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.
- Related task
- See also
11l
print(Time())
- Output:
2021-03-25 13:03:47.0505867
AArch64 Assembly
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program sysTime64.s */
/*******************************************/
/* Constantes file */
/*******************************************/
/* for this file see task include a file in language AArch64 assembly*/
.include "../includeConstantesARM64.inc"
.equ GETTIME, 169 // call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: //
.struct timeval_sec + 8
timeval_usec: //
.struct timeval_usec + 8
timeval_end:
.struct 0
timezone_min: //
.struct timezone_min + 8
timezone_dsttime: //
.struct timezone_dsttime + 8
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessEmpty: .asciz "Empty queue. \n"
szMessNotEmpty: .asciz "Not empty queue. \n"
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" // message result
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .quad 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.quad 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.quad 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.quad 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: // entry of program
ldr x0,qAdrstTVal // time zones
ldr x1,qAdrstTZone
mov x8,GETTIME // call system
svc 0
cmp x0,-1 // error ?
beq 99f
ldr x1,qAdrstTVal
ldr x0,[x1,timeval_sec] // timestamp in second
bl convTimeStamp
//ldr x0,qTStest1
//bl convTimeStamp
//ldr x0,qTStest2
//bl convTimeStamp
//ldr x0,qTStest3
//bl convTimeStamp
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
100: // standard end of the program
mov x0,0 // return code
mov x8,EXIT // request to exit program
svc 0 // perform the system call
qAdrszMessError: .quad szMessError
qAdrstTVal: .quad stTVal
qAdrstTZone: .quad stTZone
qAdrszMessResult: .quad szMessResult
qAdrszCarriageReturn: .quad szCarriageReturn
qTStest1: .quad 1609508339 // 01/01/2021
qTStest2: .quad 1657805939 // 14/07/2022
qTStest3: .quad 1767221999 // 31/12/2025
/******************************************************************/
/* conversion timestamp to date */
/******************************************************************/
/* x0 contains the value of timestamp */
convTimeStamp:
stp x1,lr,[sp,-16]! // save registers
ldr x2,qSecJan2020
sub x3,x0,x2 // total secondes to 01/01/2020
mov x4,60
udiv x5,x3,x4
msub x6,x5,x4,x3 // compute secondes
udiv x3,x5,x4
msub x7,x3,x4,x5 // compute minutes
mov x4,24
udiv x5,x3,x4
msub x8,x5,x4,x3 // compute hours
mov x4,(365 * 4 + 1)
udiv x9,x5,x4
lsl x9,x9,2 // multiply by 4 = year1
udiv x12,x5,x4
msub x10,x12,x4,x5
ldr x11,qAdrtbDayMonthYear
mov x12,3
mov x13,12
1:
mul x14,x13,x12
ldr x15,[x11,x14,lsl 3] // load days by year
cmp x10,x15
bge 2f
sub x12,x12,1
cmp x12,0
cbnz x12,1b
2: // x12 = year2
mov x16,11
mul x15,x13,x12
lsl x15,x15,3 // * par 8
add x14,x15,x11
3:
ldr x15,[x14,x16,lsl 3] // load days by month
cmp x10,x15
bge 4f
sub x16,x16,1
cmp x16,0
cbnz x16,3b
4: // x16 = month - 1
mul x15,x13,x12
add x15,x15,x16
ldr x1,qAdrtbDayMonthYear
ldr x3,[x1,x15,lsl 3]
sub x0,x10,x3
add x0,x0,1 // final compute day
ldr x1,qAdrsZoneConv
bl conversion10
ldr x0,qAdrszMessResult
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at first @ character
mov x2,x0
add x0,x16,1 // final compute month
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
add x0,x9,2020
add x0,x0,x12 // final compute year = 2020 + year1 + year2
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x8 // hours
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x7 // minutes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
mov x0,x6 // secondes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
mov x2,x0
ldr x1,qAdrstTVal
ldr x0,[x1,timeval_usec] // millisecondes
ldr x1,qAdrsZoneConv
bl conversion10
mov x0,x2
ldr x1,qAdrsZoneConv
bl strInsertAtCharInc // insert result at next @ character
bl affichageMess
b 100f
99:
ldr x0,qAdrszMessError
bl affichageMess
100:
ldp x1,lr,[sp],16 // restaur 2 registers
ret // return to address lr x30
qAdrsZoneConv: .quad sZoneConv
qSecJan2020: .quad 1577836800
qAdrtbDayMonthYear: .quad tbDayMonthYear
/********************************************************/
/* File Include fonctions */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
- Output:
GMT: 28/3/2020 20:29:58 862484ms
ABAP
REPORT system_time.
WRITE: sy-uzeit.
Ada
The following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian.
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;
- Output:
2008-01-23 19:14:19
Aime
date d;
d_now(d);
o_form("~-/f2/-/f2/ /f2/:/f2/:/f2/\n", d_year(d), d_y_month(d), d_m_day(d),
d_d_hour(d), d_h_minute(d), d_m_second(d));
- Output:
2011-09-04 15:05:08
ALGOL 68
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))
- 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
AmigaBASIC
print date$,time$
- Output:
11-19-2020 20:47:44
AppleScript
display dialog ((current date) as text)
- Output:
Sunday, August 14, 2011 10:43:57 PM
macOS's system time epoch is 1st January 2001 00:00:00 UTC. The number of seconds since then can be calculated in vanilla AppleScript like this:
set now to (current date)
set GMTOffset to (time to GMT)
copy now to epoch
tell epoch to set {its day, its month, its year, its time} to {1, January, 2001, 0}
set systemTime to now - GMTOffset - epoch
-- Format output:
set offsetStr to GMTOffset div hours * 100 + GMTOffset mod hours div minutes
if (GMTOffset < 0) then
set offsetStr to " -" & text 3 thru -1 of ((-10000 + offsetStr) as text)
else
set offsetStr to " +" & text 2 thru -1 of ((10000 + offsetStr) as text)
end if
return (now as text) & offsetStr & (linefeed & systemTime) & (" seconds since " & epoch & " UTC")
- Output:
"Tuesday 30 June 2020 at 11:34:31 +0100
6.15206071E+8 seconds since Monday 1 January 2001 at 00:00:00 UTC"
With AppleScriptObjC, it's more direct and fractions of a second are included:
use AppleScript version "2.4" -- Mac OS 10.10 (Yosemite) or later.
use framework "Foundation"
set now to current application's class "NSDate"'s |date|()
set systemTime to now's timeIntervalSinceReferenceDate()
-- Or, since timeIntervalSinceReferenceDate() is both an instance method and a class method:
-- set systemTime to current application's class "NSDate"'s timeIntervalSinceReferenceDate()
-- Format output:
set currentLocale to current application's class "NSLocale"'s currentLocale()
set nowAsText to (now's descriptionWithLocale:(currentLocale)) as text
set epoch to now's dateByAddingTimeInterval:(-systemTime)
-- Or:
-- set epoch to current application's class "NSDate"'s dateWithTimeIntervalSinceReferenceDate:(0)
set epochAsText to epoch's |description|() as text
return nowAsText & (linefeed & systemTime) & (" seconds since " & epochAsText)
- Output:
"Tuesday 30 June 2020 at 11:34:34 British Summer Time
6.152060746444E+8 seconds since 2001-01-01 00:00:00 +0000"
ARM Assembly
/* ARM assembly Raspberry PI */
/* program sysTime.s */
/* REMARK 1 : this program use routines in a include file
see task Include a file language arm assembly
for the routine affichageMess conversion10
see at end of this program the instruction include */
/*******************************************/
/* Constantes */
/*******************************************/
.equ STDOUT, 1 @ Linux output console
.equ EXIT, 1 @ Linux syscall
.equ WRITE, 4 @ Linux syscall
.equ BRK, 0x2d @ Linux syscall
.equ CHARPOS, '@'
.equ GETTIME, 0x4e @ call system linux gettimeofday
/*******************************************/
/* Structures */
/********************************************/
/* example structure time */
.struct 0
timeval_sec: @
.struct timeval_sec + 4
timeval_usec: @
.struct timeval_usec + 4
timeval_end:
.struct 0
timezone_min: @
.struct timezone_min + 4
timezone_dsttime: @
.struct timezone_dsttime + 4
timezone_end:
/*********************************/
/* Initialized data */
/*********************************/
.data
szMessError: .asciz "Error detected !!!!. \n"
szMessResult: .asciz "GMT: @/@/@ @:@:@ @ms\n" @ message result
szCarriageReturn: .asciz "\n"
.align 4
tbDayMonthYear: .int 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
.int 366, 397, 425, 456, 486, 517, 547, 578, 609, 639, 670, 700
.int 731, 762, 790, 821, 851, 882, 912, 943, 974,1004,1035,1065
.int 1096,1127,1155,1186,1216,1247,1277,1308,1339,1369,1400,1430
/*********************************/
/* UnInitialized data */
/*********************************/
.bss
.align 4
stTVal: .skip timeval_end
stTZone: .skip timezone_end
sZoneConv: .skip 100
/*********************************/
/* code section */
/*********************************/
.text
.global main
main: @ entry of program
ldr r0,iAdrstTVal
ldr r1,iAdrstTZone
mov r7,#GETTIME
svc 0
cmp r0,#-1 @ error ?
beq 99f
ldr r0,iAdrstTVal
ldr r1,[r0,#timeval_sec] @ timestemp in second
//ldr r1,iTStest1
//ldr r1,iTStest2
//ldr r1,iTStest3
ldr r2,iSecJan2020
sub r0,r1,r2 @ total secondes to 01/01/2020
mov r1,#60
bl division
mov r0,r2
mov r6,r3 @ compute secondes
mov r1,#60
bl division
mov r7,r3 @ compute minutes
mov r0,r2
mov r1,#24
bl division
mov r8,r3 @ compute hours
mov r0,r2
mov r11,r0
mov r1,#(365 * 4 + 1)
bl division
lsl r9,r2,#2 @ multiply by 4 = year1
mov r1,#(365 * 4 + 1)
mov r0,r11
bl division
mov r10,r3
ldr r1,iAdrtbDayMonthYear
mov r2,#3
mov r3,#12
1:
mul r11,r3,r2
ldr r12,[r1,r11,lsl #2] @ load days by year
cmp r10,r12
bge 2f
sub r2,r2,#1
cmp r2,#0
bne 1b
2: @ r2 = year2
mov r5,#11
mul r4,r3,r2
lsl r4,#2
add r4,r1
3:
ldr r12,[r4,r5,lsl #2] @ load days by month
cmp r10,r12
bge 4f
subs r5,r5,#1
bne 3b
4: @ r5 = month - 1
mul r11,r3,r2
add r11,r5
ldr r1,iAdrtbDayMonthYear
ldr r3,[r1,r11,lsl #2]
sub r0,r10,r3
add r0,r0,#1 @ final compute day
ldr r1,iAdrsZoneConv
bl conversion10 @ this function do not zero final
mov r4,#0 @ store zero final
strb r4,[r1,r0]
ldr r0,iAdrszMessResult
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at first @ character
mov r3,r0
add r0,r5,#1 @ final compute month
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r11,iYearStart
add r0,r9,r11
add r0,r0,r2 @ final compute year = 2020 + year1 + year2
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r8 @ hours
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r7 @ minutes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
mov r0,r6 @ secondes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
mov r3,r0
ldr r1,iAdrstTVal
ldr r0,[r1,#timeval_usec] @ millisecondes
ldr r1,iAdrsZoneConv
bl conversion10
mov r4,#0 @ store zero final
strb r4,[r1,r0]
mov r0,r3
ldr r1,iAdrsZoneConv
bl strInsertAtCharInc @ insert result at next @ character
bl affichageMess
b 100f
99:
ldr r0,iAdrszMessError
bl affichageMess
100: @ standard end of the program
mov r0,#0 @ return code
mov r7,#EXIT @ request to exit program
svc 0 @ perform the system call
iAdrszMessError: .int szMessError
iAdrstTVal: .int stTVal
iAdrstTZone: .int stTZone
iAdrszMessResult: .int szMessResult
iAdrszCarriageReturn: .int szCarriageReturn
iAdrsZoneConv: .int sZoneConv
iSecJan2020: .int 1577836800
iAdrtbDayMonthYear: .int tbDayMonthYear
iYearStart: .int 2020
iTStest1: .int 1609508339 @ 01/01/2021
iTStest2: .int 1657805939 @ 14/07/2022
iTStest3: .int 1767221999 @ 31/12/2025
/***************************************************/
/* ROUTINES INCLUDE */
/***************************************************/
.include "../affichage.inc"
- Output:
GMT: 29/3/2020 18:39:13 717877ms
Arturo
print now
- Output:
2021-02-20T11:10:08+01:00
Asymptote
time();
time("%a %b %d %H:%M:%S %Z %Y");
//are equivalent ways of returning the current time in the default format used by the UNIX date command.
See time() in the Asymptote manual.
AutoHotkey
FormatTime, t
MsgBox,% t
- Output:
4:18 PM Saturday, May 30, 2009
AutoIt
MsgBox(0,"Time", "Year: "&@YEAR&",Day: " &@MDAY& ",Hours: "& @HOUR & ", Minutes: "& @MIN &", Seconds: "& @SEC)
- Output:
Year: 2011,Day: 05,Hour: 09, Minutes: 15, Seconds: 25
Avail
The method now
retrieves the current timestamp.
Print: “now”;
AWK
One-liner:
$ awk 'BEGIN{print systime(),strftime()}'
- Output:
1242401632 Fri May 15 17:33:52 2009
Solution for other awk-versions:
function dos_date( cmd,d,t,x) { # under MS Windows
# cmd = "DATE /T"
# cmd | getline d # Format depends on locale, e.g. MM/DD/YYYY or YYYY-MM-DD
# close(cmd) # close pipe
# ##print d
# cmd = "TIME /T"
# cmd | getline t # 13:59
# close(cmd)
# ##print t
# return d t
cmd = "echo %DATE% %TIME%" # this gives better time-resolution
cmd | getline x # 2014-10-31 20:57:36.84
close(cmd)
return x
}
BEGIN {
print "Date and time:", dos_date()
#print systime(), strftime() # gawk only
}
- Output:
2014-10-31 20:57:36.84
See also: System_time#Batch, Discordian_date
BaCon
' BaCon time
n = NOW
PRINT n, " seconds since January 1st, 1970"
PRINT YEAR(n), MONTH(n), DAY(n) FORMAT "%04d/%02d/%02d "
PRINT HOUR(n), MINUTE(n), SECOND(n) FORMAT "%02d:%02d:%02d\n"
- Output:
1503869183 seconds since January 1st, 1970 2017/08/27 17:26:23
BASIC
This shows the system time in seconds since midnight.
PRINT TIMER
This shows the time in human-readable format (using a 24-hour clock):
PRINT TIME$
Commodore BASIC
TI$ and TI
Commodore BASIC maintains both a 24-hour clock as TI$
and a jiffy clock (1 jiffy = 1/60 seconds) as the variable TIME
. Since Commodore BASIC recognizes only the first two letters of a variable identifier, TIME$
, TIMPANI$
, and TIMBUKTU$
would all refer to the time keeping variable of TI$
.
Notes about the two variables:
TI$
counts in standard time format of HHMMSS from 00:00:00 to 23:59:59 after which it will reset back to 00:00:00. On certain CBM/PET computers, TI$ is seven digits to include 1/10 seconds at the end.TI$
is both read and write capable. The user can initialize the clock to any valid time within the 24 hour range by assigning it a string value of the time, e.g.TI$ = "111530"
for 11:15:30. Assigning improper values (e.g. "089900" as 99 minutes after 8 o'clock) will result in automatic correction for the true time (09:39:00). Unfortunately there is no tracking of overflow in the hours to keep track of days, etc.TI
is read only, but always reflects the jiffy equivalent to the value inTI$
, that is: TI = (HH × 216,000) + (MM × 3600) + (SS × 60) + JIFFIES.TI
can be set or reset to a value by settingTI$
to the equivalent HHMMSS time, although resolution to specific jiffies is not possible with this method.- Particularly on the Commodore 64, the timer handler is driven off of a CIA chip interrupt, but is in no way tied to any of the time-of-day clocks built into the CIA (see below.)
- Because the clock is managed by the KERNAL operating system, the clock will loose time during certain I/O processes, such as disk access, etc. when the interrupt is unable to be processed on time.
Code Examples
1 rem time since last reset
5 print chr$(147);chr$(14);
10 t$=ti$
20 h$=left$(t$,2)
30 m$=mid$(t$,3,2)
40 s$=right$(t$,2)
50 print chr$(19);"Roughly ";tab(9);h$;" hours "
51 print tab(9);m$;" minutes"
52 print tab(9);s$; " seconds":print
60 print "has elapsed since TI$ was last reset or"
65 print "the system was powered on.":print
70 print "Press any key to quit."
80 get k$:if k$="" then goto 10
5 rem set time to current time of day
10 print chr$(147);
20 input "Enter hour of day (0-23)";h$
25 if val(h$)<0 or val(h$)>23 then goto 20
30 input "Enter minutes (0-59)";m$
35 if val(m$)<0 or val(m$)>99 then goto 30
40 input "Enter seconds (0-59)";s$
45 if val(s$)<0 or val(s$)>99 then goto 40
60 ti$=h$+m$+s$
70 print chr$(147);
80 print chr$(19);"The time is now: ";ti$
85 print:print "Press any key to end."
90 get k$:if k$="" then 80
100 end
Time of Day Clocks
The Commodore 64 and 128 models each have two MOS 6526 Complex Interface Adapters (CIA) that each have Time of Day (TOD) clocks. Interestingly, these clocks are not used to drive the internal variables TI
and TI$
. The advantage of these clocks is that they will continue to count time independent of the operating system, and therefore do not lose time during the same I/O operations that affect TI
and TI$
.
The time is represented in Binary Coded Decimal, and a separate register is used to access hours, minutes, seconds, and 1/10 seconds.
Reading the HOURS register will suspend further updates to all of the TOD registers to allow the program to accurately read the complete time. The clock itself does not stop. Once the 1/10 register is read, updates to the registers will continue. If the programmer intends to read only the hours of a running clock, a subsequent read of the 1/10 register must be performed to resume updating of the registers.
Writing to the HOURS register will stop the clock completely. The clock will start only when the 1/10 register is written to, even with a zero.
Code Example - Commodore 64/128 Only
1 rem read and set cia time of day clock
2 rem rosetta code commodore 64/128 example
10 print chr$(147);chr$(14)
15 hr=56331:mr=56330:sr=56329:tr=56328:gosub 300
20 print spc(11);"CIA #1 Time of Day"
21 print:print "Press S to start or stop the clock."
22 print "Press T to change the time."
23 print:print "Press Q to quit.":print
25 h=peek(hr):m=peek(mr):s=peek(sr):th=peek(tr):t=h:gosub 200
35 print chr$(19);:for q=1 to 8:print chr$(17);:next q
36 print "Clock is:";tab(12);cl$(b):print
40 print "Hours:";tab(12);h;". "
45 print "Minutes:";tab(12);m;". "
50 print "Seconds:";tab(12);s;". "
55 print "1/10 Sec.:";tab(12);th;". "
60 print "AM or PM? ";tab(13);ap$
65 get k$:if k$="" then goto 25
70 if k$="s" and b=0 then poke tr,0:b=1:goto 25
75 if k$="s" and b=1 then poke hr,t:b=0:goto 25
80 if k$="t" then gosub 400:goto 20
90 if k$="q" then end
100 goto 25
200 rem decode bcd
210 ap$="AM":if (h and 128)=128 then ap$="PM"
220 s=int((s and 112)/16)*10+(s and 15)
230 m=int((m and 112)/16)*10+(m and 15)
240 h=int((h and 48)/16)*10+(h and 15)
250 return
300 rem decide if clock is running
305 cl$(0)="Stopped":cl$(1)="Running":b=0
301 rem latch, read/resume
310 z=peek(hr):t1=peek(tr)
315 for i=1 to 100:next i
320 z=peek(hr):t2=peek(tr)
325 if t1<>t2 then b=1
330 return
400 rem change clock value
405 print chr$(147)
410 input "Hour";nh$
415 if val(nh$)<1 or val(nh$)>12 then goto 410
416 if val(nh$)<10 then nh$="0"+nh$
420 input "Minutes";nm$
425 if val(nm$)<0 or val(nm$)>59 then goto 420
426 if val(nm$)<10 then nm$="0"+nm$
430 input "Seconds";ns$
435 if val(ns$)<0 or val(ns$)>59 then goto 430
436 if val(ns$)<10 then ns$="0"+ns$
440 print "AM or PM (a,p)? ";
445 get ap$:if ap$<>"a" and ap$<>"p" then 445
446 print ap$
450 ap=0:if ap$="p" then ap=128
455 rem convert input to bcd
457 ns=val(mid$(ns$,1,1))*16+val(mid$(ns$,2,1))
460 nm=val(mid$(nm$,1,1))*16+val(mid$(nm$,2,1))
465 nh=val(mid$(nh$,1,1))*16+val(mid$(nh$,2,1))
470 nh=nh+ap
475 rem now set values into clock
480 poke hr,nh:rem set hour stops clock
485 poke mr,nm:rem set minute
490 poke sr,ns:rem set second
495 poke tr,0 :rem set 1/10 starts clock
497 b=1
499 print chr$(147):return
BASIC256
print month+1; "-"; day; "-"; year
# returns system date in format: mm-dd-yyyy
print hour; ":"; minute; ":"; second
# returns system time in format: hh:mm:ss
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.
date /t
time /t
Furthermore there are two pseudo-variables %DATE% and %TIME%:
echo %DATE% %TIME%
BBC BASIC
PRINT TIME$
Outputs the date and time. To output only the time:
PRINT RIGHT$(TIME$,8)
BQN
The system value •UnixTime
whenever called, gives time between the unix epoch the time the function was called, where the Unix epoch is 1970-01-01 00:00:00 UTC. bqn-libs/datetime.bqn has some functions for the manipulation of the given timestamp.
•Show •UnixTime @
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.
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
int main(){
time_t my_time = time(NULL);
printf("%s", ctime(&my_time));
return 0;
}
C#
Console.WriteLine(DateTime.Now);
C++
to be compiled under linux with g++ -lboost_date_time systemtime.cpp -o systemtime( or whatever you like)
#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 ;
}
C++ 11
#include <chrono>
#include <ctime> //for conversion std::ctime()
#include <iostream>
int main() {
auto timenow = std::chrono::system_clock::to_time_t(std::chrono::system_clock::now());
std::cout << std::ctime(&timenow) << std::endl;
}
- Output:
Thu Dec 26 13:51:00 2013
Clojure
(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))
CLU
start_up = proc ()
stream$putl(stream$primary_output(), date$unparse(now()))
end start_up
- Output:
19 December 2021 01:50:11
COBOL
WORKING-STORAGE SECTION.
01 WS-CURRENT-DATE-FIELDS.
05 WS-CURRENT-DATE.
10 WS-CURRENT-YEAR PIC 9(4).
10 WS-CURRENT-MONTH PIC 9(2).
10 WS-CURRENT-DAY PIC 9(2).
05 WS-CURRENT-TIME.
10 WS-CURRENT-HOUR PIC 9(2).
10 WS-CURRENT-MINUTE PIC 9(2).
10 WS-CURRENT-SECOND PIC 9(2).
10 WS-CURRENT-MS PIC 9(2).
05 WS-DIFF-FROM-GMT PIC S9(4).
PROCEDURE DIVISION.
MOVE FUNCTION CURRENT-DATE TO WS-CURRENT-DATE-FIELDS.
ColdFusion
Script Based CFML
<cfscript>
// Date Time
currentTime = Now();
writeOutput( currentTime );
// Epoch
// Credit for Epoch time should go to Ben Nadel
// bennadel.com is his blog
utcDate = dateConvert( "local2utc", currentTime );
writeOutput( utcDate.getTime() );
</cfscript>
- Output:
Current DateTime: {ts '2017-06-06 10:36:28'} Epoch: 1496763388434
Common 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))
Crystal
# current time in system's time zone:
Time.local
# current time in UTC
Time.utc
# monotonic time (useful for measuring elapsed time)
Time.monotonic
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).
Stdout(Clock.now.span.days / 365).newline;
DBL
XCALL TIME (D6) ;D6=hhmmss
DCL
$ start_time = f$time()
$ wait 0::10
$ end_time = f$time()
$ write sys$output "start time was ", start_time
$ write sys$output "end time was ", end_time
$ write sys$output "delta time is ", f$delta_time( start_time, end_time )
- Output:
$ @system_time start time was 4-JUN-2015 15:38:09.60 end time was 4-JUN-2015 15:38:19.60 delta time is 0 00:00:10.00
The alternative below doesn't facilitate the calculation of the delta time;
- Output:
$ show time 4-JUN-2015 15:33:33
Delphi
lblDateTime.Caption := FormatDateTime('dd mmmm yyyy hh:mm:ss', Now);
This populates a label with the date
DWScript
PrintLn(FormatDateTime('dd mmmm yyyy hh:mm:ss', Now));
E
println(timer.now())
The value is the number of milliseconds since 1970.
EasyLang
print timestr systime
Ecstasy
module WhatTimeIsIt {
@Inject Clock clock;
@Inject Console console;
void run() {
console.print($"current time: {clock.now}");
}
}
- Output:
current time: 2024-04-30 19:40:57.124
Elena
ELENA 4.x :
import extensions;
import system'calendar;
public program()
{
console.printLine(Date.Now);
}
- Output:
01.10.2017 18:02:43
Elixir
:os.timestamp # => {MegaSecs, Secs, MicroSecs}
:erlang.time # => {Hour, Minute, Second}
:erlang.date # => {Year, Month, Day}
:erlang.localtime # => {{Year, Month, Day}, {Hour, Minute, Second}}
:erlang.universaltime # => {{Year, Month, Day}, {Hour, Minute, Second}}
:calendar.local_time # => {{Year, Month, Day}, {Hour, Minute, Second}}
:calendar.universal_time # => {{Year, Month, Day}, {Hour, Minute, Second}}
It is also guaranteed that subsequent calls to this BIF returns continuously increasing values. Hence, the return value from :erlang.now()
can be used to generate unique time-stamps, and if it is called in a tight loop on a fast machine the time of the node can become skewed.
:random.seed(:erlang.now)
Emacs Lisp
(message "%s" (current-time-string))
;; => "Wed Oct 14 22:21:05 1987"
current-time
is the main programmatic interface, with various functions available to format or operate on the time values list it gives.
Erlang
By default, Erlang timestamps are turned in the {megasecs, secs, microsecs} format.
1> os:timestamp().
{1250,222584,635452}
These can be changed with the calendar module:
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}}
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.
Excel
NOW() returns the date and time to the minute.
Type in a cell :
=NOW()
- Output:
9-8-2013 17:33
F#
printfn "%s" (System.DateTime.Now.ToString("u"))
- Output:
2013-09-19 23:56:50Z
Factor
USE: calendar
now .
Falcon
/* Added by Aykayayciti Earl Lamont Montgomery
April 10th, 2018 */
> CurrentTime().toString()
- Output:
2018-04-10 09:40:35.798 [Finished in 0.2s]
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.
fansh> DateTime.nowTicks
351823905158000000
fansh> DateTime.now
2011-02-24T00:51:47.066Z London
fansh> DateTime.now.toJava
1298508885979
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:
[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
Fortran
In ISO Fortran 90 or later, use the SYSTEM_CLOCK intrinsic subroutine:
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)
In ISO Fortran 95 or later, use the CPU_TIME intrinsic subroutine:
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
FreeBASIC
' FB 1.05.0 Win64
Print Date + " " + Time '' returns system date/time in format : mm-dd-yyyy hh:mm:ss
Sleep
Frink
println[now[]]
- Output:
AD 2020-06-24 PM 06:37:01.326 (Wed) Mountain Daylight Time
FutureBasic
Time can be configured from simple to specialized in FB. Here's the simplest way.
window 1
print time
print time(@"hh:mm:ss" )
print time(@"h:mm a" )
print time(@"h:mm a zzz")
HandleEvents
- Output:
19:30:58 07:30:58 7:30 PM 7:30 PM EDT
More accurate timing...
window 1
print fn CFAbsoluteTimeGetCurrent
print fn CACurrentMediaTime
print fn ProcessInfoSystemUptime
HandleEvents
Gambas
Click this link to run this code
Public Sub Main()
Print Format(Now, "dddd dd mmmm yyyy hh:nn:ss")
End
Output:
Thursday 08 June 2017 15:58:41
Genie
[indent=4]
init
var now = new DateTime.now_local()
print now.to_string()
- Output:
prompt$ valac systemTime.gs prompt$ ./systemTime 2019-06-01T13:07:54-0400
Go
package main
import "time"
import "fmt"
func main() {
t := time.Now()
fmt.Println(t) // default format
fmt.Println(t.Format("Mon Jan 2 15:04:05 2006")) // some custom format
}
Groovy
Solution (based on Java solution).
def nowMillis = new Date().time
println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis
- 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:
Taskbar
Haskell
import System.Time
(getClockTime, toCalendarTime, formatCalendarTime)
import System.Locale (defaultTimeLocale)
main :: IO ()
main = do
ct <- getClockTime
print ct -- print default format, or
cal <- toCalendarTime ct
putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal
or with the time library:
import Data.Time (getZonedTime, formatTime, defaultTimeLocale)
main :: IO ()
main = do
zt <- getZonedTime
print zt -- print default format, or
putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt
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)
HolyC
CDateStruct ds;
Date2Struct(&ds, Now + local_time_offset);
Print("%04d-%02d-%02d %02d:%02d:%02d\n", ds.year, ds.mon, ds.day_of_mon, ds.hour, ds.min, ds.sec);
Hoon
The time of the current system event is made available on the subject in most contexts as now.
now
- Output:
~2016.7.24..01.25.02..0f8e
Absolute times have 64-bit subsecond precision, which is used to ensure that no two system events have the same timestamp.
Icon and 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
- 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
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
Date now println
- Output:
2008-08-26 00:15:52 EDT
IS-BASIC
100 PRINT TIME$
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.
6!:0 ''
2008 1 23 12 52 10.341
A formatted string representation of the current time can also be returned:
6!:0 'YYYY-MM-DD hh:mm:ss.sss'
2009-08-26 10:38:53.171
Java
public class SystemTime{
public static void main(String[] args){
System.out.format("%tc%n", System.currentTimeMillis());
}
}
- Output:
Mon Jun 21 13:02:19 BST 2010
Or using ZonedDateTime
object:
import java.time.ZonedDateTime;
public class SystemTime{
public static void main(String[] args){
var now = ZonedDateTime.now();
System.out.println(now);
}
}
JavaScript
console.log(new Date()) // => Sat, 28 May 2011 08:22:53 GMT
console.log(Date.now()) // => 1306571005417 // Unix epoch
Joy
time localtime "%T\n" strftime putchars.
jq
$ jq -n 'now | [., todate]'
[
1437619000.970498,
"2015-07-23T02:36:40Z"
]
"now" reports the number of seconds since the beginning of the Unix epoch.
Jsish
Jsish does not implement the standard ECMAScript Date module but provides strftime and strptime.
console.log(strftime());
- Output:
using interactive echo of results
prompt$ jsish # strftime(); "2019-02-20 19:43:20"
Julia
ts = time()
println("The system time is (in ISO 8601 format):")
println(strftime(" %F %T %Z", ts))
- Output:
The system time is (in ISO 8601 format): 2015-04-08 14:19:38 CDT
Kotlin
// version 1.0.6
fun main(args: Array<String>) {
println("%tc".format(System.currentTimeMillis()))
}
Lambdatalk
{date}
-> 2021 02 22 07 23 12
Lasso
date->format('%Q %T')
date->asInteger
- Output:
2013-11-02 11:47:27 1383407747
LFE
By default, LFE timestamps are turned in the #(megasecs secs microsecs)
format.
> (os:timestamp)
#(1423 786308 145798)
These can be changed to the more common date/time stamp with the calendar
module:
> (calendar:now_to_datetime (os:timestamp))
#(#(2015 2 13) #(0 12 18))
Locale taken into account:
> (calendar:now_to_universal_time (os:timestamp))
#(#(2015 2 13) #(0 13 51))
> (calendar:now_to_local_time (os:timestamp))
#(#(2015 2 12) #(16 14 26))
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 ensure that receive
clauses which are millisecond-sensitive do not get false timeouts.
Liberty BASIC
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
LIL
The system command is provided in the lil shell. On GNU/Linux:
print [system date]; print [system date +%s.%N]
Fri Aug 23 20:50:08 EDT 2019 1566607808.225126400
Lingo
put time()
-- "03:45"
put date()
-- "01.10.2016"
put the systemdate
-- date( 2016, 10, 1 )
put the systemdate.seconds
-- 13950
-- milliseconds since last boot, due to higher resolution better suited for random number seeding
put _system.milliseconds
-- 41746442
LiveCode
put the system time
Locomotive Basic
The variable "time" contains the time elapsed since last system start or reset. Each unit equals 1/300 s.
print time
print time/300;"s since last reboot"
Logo
Other Logo variants might have a built-in command, but UCB Logo must access the Unix shell to get time.
to time
output first first shell [date +%s]
end
make "start time
wait 300 ; 60ths of a second
print time - :start ; 5
Lua
print(os.date())
M2000 Interpreter
print str$(now,"long time"), time$(now)
Mathematica /Wolfram Language
Different ways of doing this, here are 2 most common:
Print[DateList[]]
Print[AbsoluteTime[]]
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 / Octave
datestr(now)
ans = 13-Aug-2010 12:59:56
clock
ans = 2010 8 13 12 59 56.52
Maxima
/* Time and date in a formatted string */
timedate();
"2012-08-27 20:26:23+10:00"
/* Time in seconds elapsed since 1900/1/1 0:0:0 */
absolute_real_time();
/* Time in seconds since Maxima was started */
elapsed_real_time();
elapsed_run_time();
Microsoft Small Basic
Date and time follows the user's locale.
TextWindow.WriteLine(Clock.Date + " " + Clock.Time)
- Output:
02/12/2022 8:27:15 PM Press any key to continue...
min
now datetime puts!
- Output:
2021-01-09T17:41:59Z
Modula-2
MODULE Mytime;
FROM SysClock IMPORT
GetClock, DateTime;
FROM STextIO IMPORT
WriteString, WriteLn;
FROM FormatDT IMPORT
DateTimeToString;
VAR
CurrentTime: DateTime;
DateStr, TimeStr: ARRAY [0 .. 20] OF CHAR;
BEGIN
GetClock(CurrentTime);
DateTimeToString(CurrentTime, DateStr, TimeStr);
WriteString("Current time: ");
WriteString(DateStr);
WriteString(" ");
WriteString(TimeStr);
WriteLn;
END Mytime.
Modula-3
MODULE MyTime EXPORTS Main;
IMPORT IO, FmtTime, Time;
BEGIN
IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n");
END MyTime.
- 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.
SYSTIME
NEW PH
SET PH=$PIECE($HOROLOG,",",2)
WRITE "The system time is ",PH\3600,":",PH\60#60,":",PH#60
KILL PH
QUIT
Usage:
USER>D SYSTIME^ROSETTA The system time is 22:55:44
Nanoquery
import Nanoquery.Util
println new(Date).getTime()
Neko
/**
<doc>
<h2>System time</h2>
<p>Neko uses Int32 to store system date/time values.
And lib C strftime style formatting for converting to string form</p>
</doc>
*/
var date_now = $loader.loadprim("std@date_now", 0)
var date_format = $loader.loadprim("std@date_format", 2)
var now = date_now()
$print(now, " ", date_format(now, "%T"), "\n")
- Output:
prompt$ nekoc system-time.neko prompt$ neko system-time.n 1542158592 20:23:12
Nemerle
System.Console.Write(System.DateTime.Now);
NetRexx
import java.text.SimpleDateFormat
say SimpleDateFormat("yyyy-MM-dd-HH.mm.ss.SSS").format(Date())
NewLISP
> (date)
"Sun Sep 28 20:17:55 2014"
Nim
import times
echo getDateStr()
echo getClockStr()
echo getTime()
echo now() # shorthand for "getTime().local"
- Output:
2021-04-21 00:28:01 2021-04-21T00:28:01+02:00 2021-04-21T00:28:01+02:00
Objeck
function : Time() ~ Nil {
t := Time->New();
IO.Console->GetInstance()->Print(t->GetHours())->Print(":")->Print(t->GetMinutes())->Print(":")->PrintLine(t->GetSeconds());
}
Objective-C
NSLog(@"%@", [NSDate date]);
or (deprecated)
NSLog(@"%@", [NSCalendarDate calendarDate]);
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;
Oforth
System.tick is used to retrieve a tick from the system in order to compute small intervals of time. It is used by #bench method to compute duration of a runnable (unit is micro second).
System.tick println
#[ #sqrt 1000000 seq map sum println ] bench
- Output:
707095319487 666667166.458841 259819
System.localTime returns number of micro seconds since 01/01/1970:00:00:00 Integer returned by System.localTime allows to create a Date object.
import: date
System.localTime dup println asDate println drop drop
- Output:
1421095428478000 2015-01-12 21:43:48,478
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}}
- 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
system("date")
Direct access to the C library time()
function can be had by an install()
, and it should be faster than running the date program.
install(time, "lf");
t = time();
print(t); \\ integer seconds since the epoch (usually 1 Jan 1970)
install()
can't give the higher resolution C library time functions like gettimeofday()
or clock_gettime()
but some further C code could put their results into a Pari integer or rational suitable for install()
in GP.
Pascal
Extended Pascal, as defined by the ISO standard 10206, defines a record data type that at least identifies the following members:
type
timeStamp = packed record
dateValid: Boolean;
year: integer;
month: 1..12;
day: 1..31;
timeValid: Boolean;
hour: 0..23;
minute: 0..59;
second: 0..59;
end;
A variable of this built-in data type can be populated with the getTimeStamp procedure as demostrated below:
program systemTime(output);
var
ts: timeStamp;
begin
getTimeStamp(ts);
{
If `getTimeStamp` is unable to obtain the time, it will
set `timeValid` to `false` and `hour`, `minute` and
`second` are set to a time representing midnight (0:00:00).
}
if ts.timeValid then
begin
writeLn(time(ts));
end;
end.
- Output:
19:13:42
The string representation generated by the standard function time is implementation-defined. The shown output was generated by a program compiled with the GPC, the GNU Pascal Compiler. A different processor might generate different output, for instance in an “AM”/“PM” format.
PascalABC.NET
##
Print(DateTime.Now)
Perl
Simple localtime use in scalar context.
print scalar localtime, "\n";
- Output:
Thu Jan 24 11:23:30 2008
localtime use in array context.
($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
- Output:
2008-01-24 11:23:30
The same using DateTime:
use DateTime;
my $dt = DateTime->now;
my $d = $dt->ymd;
my $t = $dt->hms;
print "$d $t\n";
- Output:
2010-03-29 19:46:26
localtime use in array context with POSIX strftime:
use POSIX qw(strftime);
$now_string = strftime "%a %b %e %H:%M:%S %Y", localtime;
print "$now_string\n";
Output (with cs_CZ.UTF-8 locale):
Čt led 24 11:23:30 2008
Using the DateTime module:
use DateTime;
my $dt = DateTime->now;
say $dt->iso8601();
say $dt->year_with_christian_era();
say $dt->year_with_secular_era();
# etc.
Unix epoch:
print time;
- Output:
1280473609
Phix
include timedate.e ?format_timedate(date(),"Dddd, Mmmm dth, YYYY, h:mm:ss pm") atom t0 = time() sleep(0.9) ?time()-t0
- Output:
"Tuesday, July 12th, 2016, 11:30:07 am" 0.906
Note the system clock tick rate mean times can be out by ~0.0155s; it is not unusual to see total elapsed times of 0,0,0,0.016,0.016,0.016,0.031,0.031,0.031, etc.
Phixmonti
def printList len for get print endfor enddef
time
"Actual time is " swap 1 get " hour, " rot 2 get " minutes, " rot 3 get nip " seconds, "
"and elapsed " msec " seconds of running time." 10 tolist printList
PHP
Seconds since the Unix epoch:
echo time(), "\n";
Microseconds since the Unix epoch:
echo microtime(), "\n";
Formatted time:
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
PicoLisp
(stamp)
- Output:
-> "2010-02-19 15:14:06
Pike
write( ctime(time()) );
- Output:
Thu Jan 2 23:58:19 2020
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. */
PowerShell
Using a cmdlet:
Get-Date
or using .NET classes and properties:
[DateTime]::Now
Prolog
GNU_Prolog
date_time(H).
- Output:
H = dt(2022,1,23,21,37,16)
B-Prolog
time(H,M,S)
- Output:
H = 21 M = 37 S = 16
date(Y,M,D)
- Output:
Y = 2022 M = 1 D = 23
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
Python
import time
print time.ctime()
Q
Date & time are accessible via the virtual .z namespace. lowercase names are UTC, uppercase are local:
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
Quackery
time 1000000 / echo say " seconds since the Unix epoch."
Output
1610201941 seconds since the Unix epoch.
R
Note that this is output as a standard style string.
Sys.time()
- Output:
[1] "2009-07-27 15:27:04 PDT"
Racket
The system time as a date string:
#lang racket
(require racket/date)
(date->string (current-date))
Or, as seconds after midnight UTC, January 1, 1970:
#lang racket
(current-seconds)
Raku
(formerly Perl 6)
say DateTime.now;
dd DateTime.now.Instant;
- Output:
2015-11-02T13:34:09+01:00 Instant $var = Instant.new(<2159577143734/1493>)
Raven
Note the use of single quotation marks for the date specifier.
time dup print "\n" print int '%a %b %e %H:%M:%S %Y' date
- Output:
1353352623.511231 Tue Nov 20 05:17:03 2012
REBOL
now
print rejoin [now/year "-" now/month "-" now/day " " now/time]
- 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:
time putn
REXX
Note that REXX only examines the first character of the option and can be in upper or lower case.
/*REXX program shows various ways to display the system time, including other options. */
say '════════════ Normal format of time'
say 'hh:mm:ss ◄─────────────── hh= is 00 ──► 23'
say 'hh:mm:ss ◄─────────────── hh= hour mm= minute ss= second'
say time()
say time('n') /* (same as the previous example.) */
say time('N') /* " " " " " */
say time('Normal') /* " " " " " */
say time('nitPick') /* " " " " " */
say
say '════════════ Civil format of time'
say 'hh:mmcc ◄─────────────── hh= is 1 ──► 12'
say 'hh:mmam ◄─────────────── hh= hour mm= minute am= ante meridiem'
say 'hh:mmpm ◄─────────────── pm= post meridiem'
say time('C')
say time('civil') /* (same as the previous example.) */
/*ante meridiem≡Latin for before midday*/
/*post " " " after " */
say
say '════════════ long format of time'
say 'hh:mm:ss ◄─────────────── hh= is 0 ──► 23'
say 'hh:mm:ss.ffffff ◄─────────────── hh= hour mm= minute fffff= fractional seconds'
say time('L')
say time('long') /* (same as the previous example.) */
say time('long time no see') /* " " " " " */
say
say '════════════ complete hours since midnight'
say 'hh ◄─────────────── hh = 0 ───► 23'
say time('H')
say time('hours') /* (same as the previous example.) */
say
say '════════════ complete minutes since midnight'
say 'mmmm ◄─────────────── mmmm = 0 ───► 1439'
say time('M')
say time('minutes') /* (same as the previous example.) */
say
say '════════════ complete seconds since midnight'
say 'sssss ◄─────────────── sssss = 0 ───► 86399'
say time('S')
say time('seconds') /* (same as the previous example.) */
/*stick a fork in it, we're all done. */
- output:
════════════ Normal format of time hh:mm:ss ◄─────────────── hh= is 00 ──► 23 hh:mm:ss ◄─────────────── hh= hour mm= minute ss= second 19:59:40 19:59:40 19:59:40 19:59:40 19:59:40 ════════════ Civil format of time hh:mmcc ◄─────────────── hh= is 1 ──► 12 hh:mmam ◄─────────────── hh= hour mm= minute am= ante meridiem hh:mmpm ◄─────────────── pm= post meridiem 7:59pm 7:59pm ════════════ long format of time hh:mm:ss ◄─────────────── hh= is 0 ──► 23 hh:mm:ss.ffffff ◄─────────────── hh= hour mm= minute fffff= fractional seconds 19:59:40.250000 19:59:40.250000 19:59:40.250000 ════════════ complete hours since midnight hh ◄─────────────── hh = 0 ───► 23 19 19 ════════════ complete minutes since midnight mmmm ◄─────────────── mmmm = 0 ───► 1439 1199 1199 ════════════ complete seconds since midnight sssss ◄─────────────── sssss = 0 ───► 86399 71980 71980
Ring
/* Output:
** Sun abbreviated weekday name
** Sunday full weekday name
** May abbreviated month name
** May full month name
** 05/24/15 09:58:38 Date & Time
** 24 Day of the month
** 09 Hour (24)
** 09 Hour (12)
** 144 Day of the year
** 05 Month of the year
** 58 Minutes after hour
** AM AM or PM
** 38 Seconds after the hour
** 21 Week of the year (sun-sat)
** 0 day of the week
** 05/24/15 date
** 09:58:38 time
** 15 year of the century
** 2015 year
** Arab Standard Time time zone
** % percent sign
*/
See TimeList()
RPL
Since 1990, there is a command named TICKS
which returns the system time in 1/8192ths of a second, using a 64-bit unsigned integer:
- Output:
1: #1DBC0D1698BE0h
There is also a TIME
command, returning the system time in a hh.mmss format:
Output:
1: 20.4526471679 @ 8:45:26 PM
Ruby
version 1.9+
t = Time.now
# textual
puts t # => 2013-12-27 18:00:23 +0900
# epoch time
puts t.to_i # => 1388134823
# epoch time with fractional seconds
puts t.to_f # => 1388134823.9801579
# epoch time as a rational (more precision):
puts Time.now.to_r # 1424900671883862959/1000000000
Rust
// 20210210 Rust programming solution
extern crate chrono;
use chrono::prelude::*;
fn main() {
let utc: DateTime<Utc> = Utc::now();
println!("{}", utc.format("%d/%m/%Y %T"));
}
- Output:
10/02/2021 16:26:23
Scala
Ad hoc solution as REPL scripts:
JDK < 8
println(new java.util.Date)
- Output:
Sun Aug 14 22:47:42 EDT 2011
JDK >= 8 (recommended)
println(java.time.LocalTime.now())
- Output:
11:32:39.002
Scheme
(use posix)
(seconds->string (current-seconds))
- Output:
"Sat May 16 21:42:47 2009"
(display (date-and-time)) (newline)
- Output:
Mon Jun 27 19:51:09 2022
Seed7
$ include "seed7_05.s7i";
include "time.s7i";
const proc: main is func
begin
writeln(time(NOW));
end func;
- Output:
2009-12-07 17:09:44.687500 UTC+1
SETL
$ Unix time
print(tod);
$ Human readable time and date
print(date);
- Output:
1447628158908
Sun Nov 15 22:55:58 2015
Sidef
# textual
say Time.local.ctime; # => Thu Mar 19 15:10:41 2015
# epoch time
say Time.sec; # => 1426770641
# epoch time with fractional seconds
say Time.micro_sec; # => 1426770641.68409
Smalltalk
DateTime now displayNl.
- Output:
2011-08-10T00:43:36-0-7:00
DateAndTime now
- Output:
2011-08-16T19:40:37-03:00
SNOBOL4
OUTPUT = DATE()
END
- Output:
03/30/2010 20:58:09
SPL
hour,min,sec = #.now()
day,month,year = #.today()
#.output(#.str(hour,"00:"),#.str(min,"00:"),#.str(sec,"00.000"))
#.output(day,".",#.str(month,"00"),".",year)
- Output:
03:15:34.068 24.08.2017
SQL PL
SELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1;
Output:
db2 -t db2 => SELECT CURRENT DATE, CURRENT TIME, CURRENT TIMESTAMP FROM SYSIBM.SYSDUMMY1; 1 2 3 ---------- -------- -------------------------- 04/29/2018 14:27:10 2018-04-29-14.27.10.674182 1 record(s) selected.
Standard ML
print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n")
Stata
di c(current_date)
di c(current_time)
Swift
import Foundation
var ⌚️ = NSDate()
println(⌚️)
- Output:
2014-06-22 20:43:42 +0000
Tcl
This uses a timestamp that is a number of seconds since the start of the UNIX Epoch.
puts [clock seconds]
More readable forms may be created by formatting the time:
puts [clock format [clock seconds]]
TI-89 BASIC
■ getTime() {13 28 55}
■ getDate() {2009 8 13}
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.
True BASIC
PRINT DATE$
! returns system date in format: “YYYYMMDD”.
! Here YYYY is the year, MM is the month number, and DD is the day number.
PRINT TIME$
! returns system time in format: “HH:MM:SS”.
END
TUSCRIPT
$$ MODE TUSCRIPT
time=time()
PRINT time
- Output:
2011-04-05 13:45:44
UNIX Shell
date # Thu Dec 3 15:38:06 PST 2009
date +%s # 1259883518, seconds since the epoch, like C stdlib time(0)
Ursa
# outputs time in milliseconds
import "time"
out (time.getcurrent) endl console
Ursala
A library function, now, ignores its argument and returns the system time as a character string.
#import cli
#cast %s
main = now 0
- 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.
Vala
var now = new DateTime.now_local();
string now_string = now.to_string();
- Output:
2011-11-12T20:23:24-0800
VBA
Debug.Print Now()
- Output:
12/12/2013 16:16:16
VBScript
WScript.Echo Now
V (Vlang)
import time
fn main() {
t := time.Now()
println(t) // default format YYYY-MM-DD HH:MM:SS
println(t.custom_format("ddd MMM d HH:mm:ss YYYY")) // some custom format
}
Wren
Although Wren CLI can tell how much time has elapsed since the script started, it currently has no way of knowing what the time was then or what the time is now (in the current locale) unless the user passes the former as a command line argument.
import "os" for Process
import "./date" for Date
var args = Process.arguments
if (args.count != 1) Fiber.abort("Please pass the current time in hh:mm:ss format.")
var startTime = Date.parse(args[0], Date.isoTime)
for (i in 0..1e8) {} // do something which takes a bit of time
var now = startTime.addMillisecs((System.clock * 1000).round)
Date.default = Date.isoTime + "|.|ttt"
System.print("Time now is %(now)")
- Output:
Sample session.
$ wren systemTime.wren 19:00:00 Time now is 19:00:01.992
XPL0
The intrinsics GetReg and SoftInt are used to access DOS and BIOS routines. GetReg returns the address of an array where a copy of the processor's hardware registers are stored. Values (such as $2C00 in the example) can be stored into this array. When SoftInt is called, the values in the array are loaded into the processor's registers and the specified interrupt ($21 in the example) is called.
include c:\cxpl\codes; \include intrinsic 'code' declarations
proc NumOut(N); \Output a 2-digit number, including leading zero
int N;
[if N <= 9 then ChOut(0, ^0);
IntOut(0, N);
]; \NumOut
int Reg;
[Reg:= GetReg; \get address of array with copy of CPU registers
Reg(0):= $2C00; \call DOS function 2C (hex)
SoftInt($21); \DOS calls are interrupt 21 (hex)
NumOut(Reg(2) >> 8); \the high byte of register CX contains the hours
ChOut(0, ^:);
NumOut(Reg(2) & $00FF); \the low byte of CX contains the minutes
ChOut(0, ^:);
NumOut(Reg(3) >> 8); \the high byte of DX contains the seconds
ChOut(0, ^.);
NumOut(Reg(3) & $00FF); \the low byte of DX contains hundreths
CrLf(0);
]
- Output:
13:08:26.60
Yabasic
print time$
zkl
Time.Clock.time //-->seconds since the epoch (C/OS defined)
- Programming Tasks
- Programming environment operations
- Date and time
- Simple
- ML/I/Omit
- ZX Spectrum Basic/Omit
- 11l
- AArch64 Assembly
- ABAP
- Ada
- Aime
- ALGOL 68
- AmigaBASIC
- AppleScript
- ARM Assembly
- Arturo
- Asymptote
- AutoHotkey
- AutoIt
- Avail
- AWK
- BaCon
- BASIC
- Commodore BASIC
- BASIC256
- Batch File
- BBC BASIC
- BQN
- C
- C sharp
- C++
- Clojure
- CLU
- COBOL
- ColdFusion
- Common Lisp
- Crystal
- D
- DBL
- DCL
- Delphi
- DWScript
- E
- EasyLang
- Ecstasy
- Elena
- Elixir
- Emacs Lisp
- Erlang
- Excel
- F Sharp
- Factor
- Falcon
- Fantom
- Forth
- Fortran
- FreeBASIC
- Frink
- FutureBasic
- Gambas
- Genie
- Go
- Groovy
- GUISS
- Haskell
- HicEst
- HolyC
- Hoon
- Icon
- Unicon
- IDL
- Io
- IS-BASIC
- J
- Java
- JavaScript
- Joy
- Jq
- Jsish
- Julia
- Kotlin
- Lambdatalk
- Lasso
- LFE
- Liberty BASIC
- LIL
- Lingo
- LiveCode
- Locomotive Basic
- Logo
- Lua
- M2000 Interpreter
- Mathematica
- Wolfram Language
- MATLAB
- Octave
- Maxima
- Microsoft Small Basic
- Min
- Modula-2
- Modula-3
- MUMPS
- Nanoquery
- Neko
- Nemerle
- NetRexx
- NewLISP
- Nim
- Objeck
- Objective-C
- OCaml
- Oforth
- Oz
- PARI/GP
- Pascal
- PascalABC.NET
- Perl
- Phix
- Phix/basics
- Phixmonti
- PHP
- PicoLisp
- Pike
- PL/I
- PowerShell
- Prolog
- GNU Prolog
- B-Prolog
- PureBasic
- Python
- Q
- Quackery
- R
- Racket
- Raku
- Raven
- REBOL
- Retro
- REXX
- Ring
- RPL
- Ruby
- Rust
- Scala
- Scheme
- Seed7
- SETL
- Sidef
- Smalltalk
- SNOBOL4
- SPL
- SQL PL
- Standard ML
- Stata
- Swift
- Tcl
- TI-89 BASIC
- True BASIC
- TUSCRIPT
- UNIX Shell
- Ursa
- Ursala
- Vala
- VBA
- VBScript
- V (Vlang)
- Wren
- Wren-date
- XPL0
- Yabasic
- Zkl
- Axe/Omit
- Bc/Omit
- Dc/Omit
- Pages with too many expensive parser function calls