Show the epoch

From Rosetta Code
Task
Show the epoch
You are encouraged to solve this task according to the task description, using any language you may know.

Choose popular date libraries used by your language and show the epoch those libraries use. A demonstration is preferable (e.g. setting the internal representation of the date to 0 ms/ns/etc., or another way that will still show the epoch even if it is changed behind the scenes by the implementers), but text from (with links to) documentation is also acceptable where a demonstration is impossible/impractical. For consistency's sake, show the date in UTC time where possible.

See also: Date format

C

<lang c>#include <time.h>

  1. include <stdio.h>

int main() {

   time_t t = 0;
   printf("%s", asctime(gmtime(&t)));
   return 0;

}</lang>

Output:

Thu Jan  1 00:00:00 1970

Windows

FileTime, from the Win32 API, uses a different epoch.

Library: Win32

<lang c>#include <windows.h>

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

int main() { FILETIME ft = {dwLowDateTime: 0, dwHighDateTime: 0}; /* Epoch */ SYSTEMTIME st; wchar_t date[80], time[80];

/* * Convert FILETIME (which counts 100-nanosecond intervals since * the epoch) to SYSTEMTIME (which has year, month, and so on). * * The time is in UTC, because we never call * SystemTimeToTzSpecificLocalTime() to convert it to local time. */ FileTimeToSystemTime(&ft, &st);

/* * Format SYSTEMTIME as a string. */ if (GetDateFormatW(LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, date, sizeof date / sizeof date[0]) == 0 || GetTimeFormatW(LOCALE_USER_DEFAULT, 0, &st, NULL, time, sizeof time / sizeof time[0]) == 0) { fwprintf(stderr, L"Error!\n"); return 1; }

wprintf(L"FileTime epoch is %s at %s (UTC).\n", date, time); return 0; }</lang>

FileTime epoch is Monday, January 01, 1601 at 12:00:00 AM (UTC).

C#

<lang csharp>using System;

class Program {

   static void Main()
   {
       Console.WriteLine(new DateTime());
   }

}</lang> Output:

1-1-0001 0:00:00

C++

Works with: C++11
Works with: gcc version 4.5.3

Doesn't work with MSVC 10 SP1 <lang cpp>#include <iostream>

  1. include <chrono>
  2. include <ctime>

int main() {

   std::chrono::system_clock::time_point epoch;
   std::time_t t = std::chrono::system_clock::to_time_t(epoch);
   std::cout << std::asctime(std::gmtime(&t)) << '\n';
   return 0;

}</lang> Output:

Thu Jan  1 00:00:00 1970
Library: boost

<lang cpp>#include <iostream>

  1. include <boost/date_time.hpp>

int main() {

   std::cout << boost::posix_time::ptime( boost::posix_time::min_date_time ) << '\n';
   return 0;

}</lang>

Output:

1400-Jan-01 00:00:00

Common Lisp

<lang lisp>(multiple-value-bind (second minute hour day month year) (decode-universal-time 0 0)

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

Output:

1900-01-01 00:00:00

Dart

<lang dart>main() {

 print(new Date.fromEpoch(0,new TimeZone.utc()));

}</lang>

Output:

1970-01-01 00:00:00.000Z


Delphi

<lang Delphi>program ShowEpoch;

{$APPTYPE CONSOLE}

uses SysUtils;

begin

 Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0));

end. </lang>

Output:

1899-12-30 00:00:00.000

Forth

Works with: 4tH version 3.61.3

<lang forth>include lib/longjday.4th 0 posix>jday .longjday cr</lang> Output:

Thursday, January 1, 1970

Go

<lang go>package main import ("fmt"; "time")

func main() {

   fmt.Println(time.Time{})

}</lang> Output. This is UNIX format. The 1 on the end is the full year, not two or four digit year.

Mon Jan  1 00:00:00 +0000 UTC 1

Haskell

Old time library

The ClockTime type is abstract in Haskell 98, but is defined in GHC.

Works with: GHC

<lang haskell>import System.Time

main = putStrLn $ calendarTimeToString $ toUTCTime $ TOD 0 0</lang>

Output:

Thu Jan  1 00:00:00 UTC 1970

New time library

Works with: GHC

<lang haskell>import Data.Time

main = print $ UTCTime (ModifiedJulianDay 0) 0</lang>

Output:

1858-11-17 00:00:00 UTC

Icon and Unicon

Date and Time can be accessed via a number of keywords and functions

  • The following are available in both Icon and Unicon
    • &clock, &date, &dateline, and &time deal with current times and dates
  • The following are specific to Unicon
    • &now provides the number of seconds since the epoch, Jan 1, 1970 00:00:00
    • ctime(integer) takes the number of seconds since the epoch and returns the date and time as a string in the local timezone
    • gtime(integer) takes the number of seconds since the epoch and returns the date and time as a string in UTC
    • gettimeofday() returns a record with the current time since the epoch in seconds and microseconds
  • datetime routines use a global variable 'DateBaseYear' which defaults to Jan 1, 1970 00:00:00 but can be set if desired.
  • The example below uses only a couple of the datetime procedures

<lang Unicon>link printf,datetime

procedure main()

 # Unicon
 now := gettimeofday().sec
 if now = &now then printf("&now and gettimeofday().sec are equal\n") 
 printf("Now (UTC) %s, (local) %s\n",gtime(now),ctime(now))
 printf("Epoch %s\n",gtime(0))
 # Icon and Unicon
 now := DateToSec(&date) + ClockToSec(&clock)
 printf("Now is also %s and %s\n",SecToDate(now),SecToDateLine(now))  

end</lang>

Sample Output:

&now and gettimeofday().sec are equal
Now (UTC) Tue Aug 09 10:43:23 2011, (local) Tue Aug 09 06:43:23 2011
Epoch Thu Jan 01 00:00:00 1970
Now is also 2011/08/09 and Tuesday, August 9, 2011  6:43 am

J

J does not have an epoch. J's native representation of date and time is a six element list: year, month, day, hour, minute, second. For example:

<lang j> 6!:0 2011 8 8 20 25 44.725</lang>

(August 8, 2011, 8:25:44 pm)

That said, the 'dates' library does have an epoch:

<lang j> require'dates'

  todate 0

1800 1 1</lang>

Java

DateFormat is needed to set the timezone. Printing date alone would show this date in the timezone/locale of the machine that the program is running on. The epoch used in java.util.Date (as well as java.sql.Date, which can be subbed into this example) is actually in GMT, but there isn't a significant difference between that and UTC for lots of applications (documentation for java.util.Date). <lang java>import java.text.DateFormat; import java.util.Date; import java.util.TimeZone;

public class DateTest{

   public static void main(String[] args) {
       Date date = new Date(0);
       DateFormat format = DateFormat.getDateTimeInstance();
       format.setTimeZone(TimeZone.getTimeZone("UTC"));
       System.out.println(format.format(date));
   }

}</lang> Output:

Jan 1, 1970 12:00:00 AM

JavaScript

<lang javascript>document.write(new Date(0).toUTCString());</lang> Output:

Thu, 01 Jan 1970 00:00:00 GMT

NewLISP

<lang NewLISP>(date 0) ->"Thu Jan 01 01:00:00 1970"</lang>

Objective-C

<lang objc>#import <Foundation/Foundation.h>

int main(int argc, const char *argv[]) {

 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
 NSDate *t = [NSDate dateWithTimeIntervalSinceReferenceDate:0];
 NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
 [dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
 [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZ"];
 NSLog(@"%@", [dateFormatter stringFromDate:t]);
 [pool release];
 return 0;

}</lang>

Log:

2001-01-01 00:00:00 +0000

OCaml

<lang ocaml>open Unix

let months = [| "January"; "February"; "March"; "April"; "May"; "June";

     "July"; "August"; "September"; "October"; "November"; "December" |]

let () =

 let t = Unix.gmtime 0.0 in
 Printf.printf "%s %d, %d\n" months.(t.tm_mon) t.tm_mday (1900 + t.tm_year)</lang>

Execution:

$ ocaml unix.cma epoch.ml
January 1, 1970

Pascal

This works with Free Pascal: <lang pascal>Program ShowEpoch;

uses

 SysUtils;

begin

 Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', Now));
 Writeln(FormatDateTime('yyyy-mm-dd hh:nn:ss.zzz', 0));

end.</lang> Output:

:> ./SelfDescribingNumber
2011-12-13 00:57:41.378
1899-12-30 00:00:00.000

Perl

<lang perl>print scalar gmtime 0, "\n";</lang>

Output:

Thu Jan  1 00:00:00 1970

Perl 6

<lang perl6>say DateTime.new(0)</lang>

1970-01-01T00:00:00Z

PHP

<lang php><?php echo gmdate('r', 0), "\n"; ?></lang>

Output:

Thu, 01 Jan 1970 00:00:00 +0000

PicoLisp

The 'date' function in PicoLisp returns a day number, starting first of March of the year zero. Calculated according to the gregorian calendar (despite that that calendar wasn't used in 0 AD yet). <lang PicoLisp>: (date 1) -> (0 3 1) # Year zero, March 1st</lang>

PowerShell

PowerShell uses .NET's DateTime structure and an integer can simply be casted appropriately:

<lang powershell>[datetime] 0</lang>

Output:

Monday, January 01, 0001 12:00:00 AM

PureBasic

<lang purebasic>If OpenConsole()

 PrintN(FormatDate("Y = %yyyy  M = %mm  D = %dd, %hh:%ii:%ss", 0))
 
 Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
 CloseConsole()

EndIf</lang> Sample output:

Y = 1970  M = 01  D = 01, 00:00:00

Python

<lang python>>>> import time >>> time.asctime(time.gmtime(0)) 'Thu Jan 1 00:00:00 1970' >>></lang>

Ruby

<lang ruby>irb(main):001:0> Time.at(0).utc => 1970-01-01 00:00:00 UTC</lang>

Scala

<lang scala>import java.util.{Date, TimeZone, Locale} import java.text.DateFormat

val df=DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, Locale.ENGLISH) df.setTimeZone(TimeZone.getTimeZone("UTC")) println(df.format(new Date(0)))</lang> Output:

January 1, 1970 12:00:00 AM UTC

Standard ML

<lang sml>- Date.toString (Date.fromTimeUniv Time.zeroTime); val it = "Thu Jan 1 00:00:00 1970" : string</lang>

Tcl

<lang tcl>% clock format 0 -gmt 1 Thu Jan 01 00:00:00 GMT 1970</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT - epoch number=1 dayofweeknr=DATE (date,day,month,year,number) epoch=JOIN(year,"-",month,day) PRINT "epoch: ", epoch," (daynumber ",number,")" - today's daynumber dayofweeknr=DATE (today,day,month,year,number) date=JOIN (year,"-",month,day) PRINT "today's date: ", date," (daynumber ", number,")" </lang> Output:

epoch: 1-1-1 (daynumber 1)
today's date: 2011-12-14 (daynumber 734487) 

UNIX Shell

The nonstandard option date -r takes seconds from the epoch, and prints date and time. See date(1) manual.

Works with: OpenBSD

<lang bash>$ date -ur 0 Thu Jan 1 00:00:00 UTC 1970</lang>

Visual Basic

<lang vb>Sub Main()

   Debug.Print Format(0, "dd mmm yyyy hh:mm")

End Sub</lang>

Output (in debug window):

30 Dec 1899 00:00