System time: Difference between revisions

From Rosetta Code
Content added Content deleted
(Powershell added)
No edit summary
Line 61: Line 61:
}</lang>
}</lang>


=={{header|C++}}==
to be compiled under linux with g++ -lboost_date_time systemtime.cpp -o systemtime( or whatever you like)
<lang c++>#include <iostream>
#include <boost/date_time/posix_time/posix_time.hpp>

int main( ) {
boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
std::cout << to_simple_string( t ) << std::endl ;
return 0 ;
}</lang>
=={{header|C sharp|C#}}==
=={{header|C sharp|C#}}==



Revision as of 20:38, 10 October 2009

Task
System time
You are encouraged to solve this task according to the task description, using any language you may know.

Output the system time (any units will do as long as they are noted) either by a system command or one built into the language. The system time can be used for debugging, network information, random number seeds, or something as simple as program performance.

See Also

Ada

The following example displays a date-time stamp. The time zone value is the number of minutes offset from the prime meridian. <lang ada>with Ada.Calendar; use Ada.Calendar; with Ada.Calendar.Formatting; use Ada.Calendar.Formatting; with Ada.Calendar.Time_Zones; use Ada.Calendar.Time_Zones; with Ada.Text_Io; use Ada.Text_Io;

procedure System_Time is

  Now : Time := Clock;

begin

  Put_line(Image(Date => Now, Time_Zone => -7*60));

end System_Time;</lang>

Output:

2008-01-23 19:14:19

ALGOL 68

Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

<lang algol>FORMAT time repr = $"year="4d,", month="2d,", day="2d,", hours="2d,", minutes="2d,", seconds="2d,", day of week="d,", daylight-saving-time flag="dl$; printf((time repr, local time)); printf((time repr, utc time))</lang>

Sample output:

year=2009, month=03, day=12, hours=11, minutes=53, seconds=32, day of week=5, daylight-saving-time flag=0
year=2009, month=03, day=12, hours=01, minutes=53, seconds=32, day of week=5, daylight-saving-time flag=0

AutoHotkey

<lang autohotkey>FormatTime, t MsgBox,% t</lang>

Sample output:

4:18 PM Saturday, May 30, 2009

AWK

$ awk 'BEGIN{print systime(),strftime()}'
1242401632 Fri May 15 17:33:52  2009

BASIC

Works with: QuickBasic version 4.5

This shows the system time in seconds since midnight.

PRINT TIMER

C

This probably isn't the best way to do this, but it works. It shows system time as "Www Mmm dd hh:mm:ss yyyy", where Www is the weekday, Mmm the month in letters, dd the day of the month, hh:mm:ss the time, and yyyy the year. <lang c>#include<time.h>

  1. include<stdio.h>
  2. include<stdlib.h>

int main(){

 time_t my_time = time(NULL);
 printf("%s", ctime(&my_time));
 return 0;

}</lang>

C++

to be compiled under linux with g++ -lboost_date_time systemtime.cpp -o systemtime( or whatever you like) <lang c++>#include <iostream>

  1. include <boost/date_time/posix_time/posix_time.hpp>

int main( ) {

  boost::posix_time::ptime t ( boost::posix_time::second_clock::local_time( ) ) ;
  std::cout << to_simple_string( t ) << std::endl ;
  return 0 ;

}</lang>

C#

<lang csharp>Console.WriteLine(DateTime.Now);</lang>

Clojure

<lang 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)) </lang>

Common Lisp

<lang lisp>(multiple-value-bind (second minute hour day month year) (get-decoded-time)

	  (format t "~4,'0D-~2,'0D-~2,'0D ~2,'0D:~2,'0D:~2,'0D" year month day hour minute second))</lang>

D

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). <lang D> Stdout(Clock.now.span.days / 365).newline; </lang>

E

<lang e>println(timer.now())</lang>

The value is the number of milliseconds since 1970.

Erlang

By default, Erlang timestamps are turned in the {megasecs, secs, microsecs} format. <lang erlang> 1> os:timestamp(). {1250,222584,635452} </lang>

These can be changed with the calendar module: <lang erlang> 2> calendar:now_to_datetime(os:timestamp()). {{2009,8,14},{4,3,24}} 3> calendar:now_to_universal_time(os:timestamp()). {{2009,8,14},{4,3,40}} 4> calendar:now_to_local_time(os:timestamp()). {{2009,8,14},{0,7,01}} </lang>

Note that you will often encounter the function erlang:now/0 giving a time similar to the system time. However, erlang:now/0 may get delayed if the system time changes suddenly (i.e.: coming back from sleep mode). The delay is in place to make sure receive clauses that are millisecond-sensitive do not get false timeouts.

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:

Works with: Win32Forth
Works with: GNU Forth
Works with: bigFORTH
Works with: iForth
Works with: PFE
Works with: SwiftForth
Works with: VFX Forth
Works with: MacForth
[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: <lang fortran>integer :: start, stop, rate real :: result

! optional 1st integer argument (COUNT) is current raw system clock counter value (not UNIX epoch millis!!) ! optional 2nd integer argument (COUNT_RATE) is clock cycles per second ! optional 3rd integer argument (COUNT_MAX) is maximum clock counter value call system_clock( start, rate )

result = do_timed_work()

call system_clock( stop )

print *, "elapsed time: ", real(stop - start) / real(rate)</lang>

In ISO Fortran 95 or later, use the CPU_TIME intrinsic subroutine: <lang fortran>real :: start, stop real :: result

! System clock value interpreted as floating point seconds call cpu_time( start )

result = do_timed_work()

call cpu_time( stop )

print *, "elapsed time: ", stop - start</lang>

Groovy

Solution (based on Java solution. <lang groovy>def nowMillis = new Date().time println 'Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == ' + nowMillis</lang> Output:

Milliseconds since the start of the UNIX Epoch (Jan 1, 1970) == 1243395159250

Haskell

<lang haskell>import System.Time import System.Locale

main = do ct <- getClockTime

         print ct                 -- print default format, or
         cal <- toCalendarTime ct
         putStrLn $ formatCalendarTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" cal</lang>

or with the time library: <lang haskell>import Data.Time import System.Locale

main = do zt <- getZonedTime

         print zt             -- print default format, or
         putStrLn $ formatTime defaultTimeLocale "%a %b %e %H:%M:%S %Y" zt</lang>

Io

Date now println

Example output:

2008-08-26 00:15:52 EDT

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

<lang java>import java.util.Date;

public class SystemTime{
   public static void main(String[] args){
      Date now = new Date();
      System.out.println(now); // string representation
      System.out.println(now.getTime()); // Unix time (# of milliseconds since Jan 1 1970)
      //System.currentTimeMillis() returns the same value
   }
}</lang>

Other methods are available in the Date object such as: getDay(), getHours(), getMinutes(), getSeconds(), getYear(), etc.

JavaScript

<lang javascript>document.write(new Date());</lang>

Mathematica

Different ways of doing this, here are 2 most common: <lang Mathematica>

Print[DateList[]]
Print[AbsoluteTime[]]

</lang> DateList will return the list {year,month,day,hour,minute,second} where all of them are integers except for second; that is a float. AbsoluteTime gives the total number of seconds since january 1st 1900 in your time zone.

Modula-3

<lang modula3>MODULE MyTime EXPORTS Main;

IMPORT IO, FmtTime, Time;

BEGIN

 IO.Put("Current time: " & FmtTime.Long(Time.Now()) & "\n");

END MyTime.</lang>

Output:

Current time: Tue Dec 30 20:50:07 CST 2008

Objective-C

<lang ruby>NSLog(@"%@", [NSDate date]);</lang> or <lang ruby>NSLog(@"%@", [NSCalendarDate calendarDate]);</lang>

OCaml

<lang ocaml>#load "unix.cma";; open Unix;; let {tm_sec = sec;

    tm_min = min;
    tm_hour = hour;
    tm_mday = mday;
    tm_mon = mon;
    tm_year = year;
    tm_wday = wday;
    tm_yday = yday;
    tm_isdst = isdst} = localtime (time ());;

Printf.printf "%04d-%02d-%02d %02d:%02d:%02d\n" (year + 1900) (mon + 1) mday hour min sec;;</lang>

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

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

PHP

Seconds since the Unix epoch:

echo time(), "\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

PowerShell

Using a cmdlet: <lang powershell>Get-Date</lang> or using .NET classes and properties: <lang powershell>[DateTime]::Now</lang>

Python

<lang python>import time print time.ctime()</lang>

R

Works with: R version 2.8.1

Note that this is output as a standard style string.

<lang R> Sys.time() </lang> Output:

[1] "2009-07-27 15:27:04 PDT"

Ruby

<lang ruby>t = Time.now

  1. textual

puts t # => Wed Aug 05 20:14:50 -0400 2009

  1. epoch time

puts t.to_i # => 1249517690

  1. epoch time with fractional seconds

puts t.to_f # => 1249517690.74388</lang>

Scheme

Works with: Chicken Scheme

<lang scheme>(use posix) (seconds->string (current-seconds))</lang> Output:

"Sat May 16 21:42:47 2009"

Standard ML

<lang sml>print (Date.toString (Date.fromTimeLocal (Time.now ())) ^ "\n")</lang>

Tcl

<lang tcl>puts [clock seconds]</lang>

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.

Ursala

A library function, now, ignores its argument and returns the system time as a character string. <lang Ursala>#import cli

  1. cast %s

main = now 0</lang> output:

'Fri, 26 Jun 2009 20:31:49 +0100'

This string can be converted to seconds since 1970 (ignoring leap seconds) by the library function string_to_time.