55
\$\begingroup\$

You know that your language's clock/time API's are broken and they are not reliable at all.

So you are not allowed to use any built-in API to access system time/date.

But you also know that your language's ability to perform date math, and retaining a date/time value in a variable are correct.

Write a program that prints the current date/time without calling any date/time/clock API's. For example DateTime.Now, GetDate() and similar functions are not allowed.

The answer with most upvotes wins.

In case of a tie, the answer with more precision wins (that is, accurate up to seconds, then milliseconds, then microseconds, and so on).

\$\endgroup\$
14
  • 2
    \$\begingroup\$ In other words, talk to a time server? \$\endgroup\$ Mar 10, 2014 at 17:21
  • 3
    \$\begingroup\$ Yes, you can do that. One possible solution. \$\endgroup\$
    – microbian
    Mar 10, 2014 at 17:23
  • 3
    \$\begingroup\$ Rather unspecific question. I guess the most votes will be gathered by an answer like print(input("Please enter the current time")). \$\endgroup\$
    – Howard
    Mar 10, 2014 at 17:32
  • 7
    \$\begingroup\$ My money is on "Load REPL for different language and call its non-broken time API." \$\endgroup\$ Mar 10, 2014 at 17:46
  • 2
    \$\begingroup\$ @swich that is also not allowed. Because your answer will become unreliable. \$\endgroup\$
    – microbian
    Mar 10, 2014 at 19:30

35 Answers 35

122
\$\begingroup\$

Java

Almost all of the current solutions assume that local/remote computer is not lying about a current time (would you believe T-600 as well?) .
Key point in time calculation is trusting a pure nature.
This Android app asks user to take photo of the sky and it's predicting current time with outstanding precision:

public void onActivityResult(int requestCode, int resultCode, Intent data) 
{
   if (resultCode == RESULT_OK) 
   {
      Uri selectedImageUri = data.getData();
      this.imageView.setImageURI(selectedImageUri);

      TimeGuesser guesser = new TimeGuesser(this);
      String result = guesser.guessTimeFromImage(selectedImageUri);
      this.textView.setText(result);   
   }
}

public class TimeGuesser {

    private Context context;
    public TimeGuesser(Context context)
    {
        super();
        this.context = context;
    }

    public String guessTimeFromImage(Uri uri) {
        Bitmap bitmap = null;
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.context.getContentResolver(), uri);
        } catch (IOException e) {
            return "There is no sky. Everyone's going to die";
        }

        float brightness = getBrightness(bitmap);

        if (brightness < 90.0)
        {
            return "It's sooo late";
        } else {
            return "It's sooo early";
        }
    }

    private float getBrightness(Bitmap bitmap)
    {
        float R, G, B;
        R = G = B = 0.0f;
        int pixelColor;
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int size = width * height;

        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                pixelColor = bitmap.getPixel(x, y);
                R += Color.red(pixelColor);
                G += Color.green(pixelColor);
                B += Color.blue(pixelColor);
            }
        }

        R /= size;
        G /= size;
        B /= size;

        float brightness =  (0.2126f*R ) + (0.7152f*G) + (0.0722f*B);
        return brightness;
    }
}

Results:

enter image description here


enter image description here

\$\endgroup\$
10
  • 50
    \$\begingroup\$ +1 for "There is no sky. Everyone's going to die" :D \$\endgroup\$
    – Doorknob
    Mar 11, 2014 at 12:15
  • 6
    \$\begingroup\$ "Everyone's going to die - or your finger is over the camera. Basically the same thing." \$\endgroup\$
    – corsiKa
    Mar 11, 2014 at 17:49
  • \$\begingroup\$ Please specify Java \$\endgroup\$ Mar 11, 2014 at 18:37
  • 3
    \$\begingroup\$ This is definitely my favorite, I just hope it doesn't come down to a tiebreaker... \$\endgroup\$ Mar 11, 2014 at 19:42
  • 21
    \$\begingroup\$ What about Eclipses? They're likely to cause as much of a problem here as they do during Java development! \$\endgroup\$
    – bye
    Mar 13, 2014 at 12:06
64
\$\begingroup\$

Ruby

Let's be honest: time only changes when something is posted on stackoverflow.com ;)

The script extracts the time of the "XYs ago" label in the topmost question.

require 'net/http'
source = Net::HTTP.get('stackoverflow.com', '/')

puts source.match(/span title=\"(.*)\" class=\"relativetime/)[1]

Output:

2014-03-10 18:40:05Z
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Only accurate to the second...and the second that SO pings its ntp..shameful worship \$\endgroup\$ Mar 11, 2014 at 2:16
  • 3
    \$\begingroup\$ THE <CENTER> CANNOT HOLD HE COMES \$\endgroup\$
    – Doorknob
    Apr 1, 2014 at 1:11
  • \$\begingroup\$ @Doorknob I really need to print out that post and hang it on my wall. \$\endgroup\$
    – wchargin
    Jun 13, 2014 at 5:16
30
\$\begingroup\$

Bash

Like this? (requires wget and grep)

wget -qO- 'http://www.wolframalpha.com/input/?i=current+time'|grep ' am \| pm '

The output I got a few minutes ago:

                    Why am I seeing this message? 
  context.jsonArray.popups.pod_0200.push( {"stringified": "6:08:38 pm GMT\/BST  |  Monday, March 10, 2014","mInput": "","mOutput": "", "popLinks": {} });

Or this? (requires wget and eog)

wget http://c.xkcd.com/redirect/comic/now
eog ./now
rm ./now

Output I get now: (Image by xkcd)

world map with timezone http://c.xkcd.com/redirect/comic/now

\$\endgroup\$
4
  • \$\begingroup\$ @tbodt Not sure whether you will see this comment. Your edit is invalid because http://c.xkcd.com/redirect/comic/now gives an image while http://xkcd.com/now gives a webpage. \$\endgroup\$
    – user12205
    Mar 10, 2014 at 22:16
  • 9
    \$\begingroup\$ I only just realised that the comic displayed changes depending on the time of day. That's awesome. \$\endgroup\$
    – RJFalconer
    Mar 11, 2014 at 14:34
  • 2
    \$\begingroup\$ It's a pity the cartoon doesn't incorporate daylight saving. (For example, the eastern US is only four hours behind the UK as I write this, not the normal five that the cartoon shows.) More significantly, the northern and southern hemispheres can move two hours out of synch. \$\endgroup\$ Mar 11, 2014 at 14:55
  • 16
    \$\begingroup\$ I say +1 to xkcd for not observing daylight saving time, and hope the rest of the world follows suit. \$\endgroup\$ Mar 12, 2014 at 0:19
29
\$\begingroup\$

sh/coreutils

touch . && stat . -c %z

Outputs the date in somewhat nonstandard format:
YYYY-MM-DD hh:mm:ss.nanoseconds +timezone
Although I guess it might depend on the locale.

\$\endgroup\$
5
  • 1
    \$\begingroup\$ Doesn't work. It says permission denied :) \$\endgroup\$
    – devnull
    Mar 11, 2014 at 4:32
  • 5
    \$\begingroup\$ @devnull your filesystem is terribly broken. Fix it with cd $(mktemp -d) \$\endgroup\$
    – mniip
    Mar 11, 2014 at 4:40
  • \$\begingroup\$ Meh, the dir time is set using a library function. \$\endgroup\$
    – Navin
    Mar 12, 2014 at 0:17
  • \$\begingroup\$ @Navin It isn't set. The directory inode is just opened for writing, and kernel updates its mtime. There's no explicit set mtime to this syscall happening anywhere \$\endgroup\$
    – mniip
    Mar 12, 2014 at 3:42
  • \$\begingroup\$ @mniip Welll, alright. I still feel that touch is a library function/command since it has the desired side effect. \$\endgroup\$
    – Navin
    Mar 12, 2014 at 3:59
25
\$\begingroup\$

PHP

Exploit the fact that uniqid() returns an ID based on the time.

$u=hexdec(substr(uniqid(),0,8));

$y=floor($u/31536000);
$u-=$y*31536000;
$y+=1970;

$d=floor($u/86400);
$u-=$d*86400;

$h=floor($u/3600);
$u-=$h*3600;

$m=floor($u/60);

$s=$u-$m*60;

echo 'Year='.$y.' Days='.$d.' Hours='.$h.' Minutes='.$m.' Seconds='.$s;

During my test, it returned : Year=2014 Days=79 Hours=18 Minutes=9 Seconds=49.
I don't know if I can use date to format correctly, so I converted it manually.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ I'm sure this is bending of the rules... uniqid is still a part of your language... But still you get a +1 \$\endgroup\$
    – mniip
    Mar 10, 2014 at 18:14
  • \$\begingroup\$ Why ? yes, uniqid use low level time API but even when you request time from an external server there will be a low level call to time API somewhere... \$\endgroup\$
    – Michael M.
    Mar 10, 2014 at 18:28
  • 1
    \$\begingroup\$ I'm not speaking of time API calls here. I'm saying that it's still a part of the language. \$\endgroup\$
    – mniip
    Mar 10, 2014 at 18:30
  • 3
    \$\begingroup\$ @mniip yes, but uniqid() was broken before this question was even asked. only the clock/time APIs are broken in this question \$\endgroup\$
    – Riking
    Mar 11, 2014 at 3:29
24
\$\begingroup\$

Bash

Just to be always absolutely precise and correct:

echo "Now"

or motivating:

echo "Now, do something useful today"
\$\endgroup\$
11
  • 10
    \$\begingroup\$ toady, noun, plural toadies. An obsequious flatterer; sycophant. (Source) \$\endgroup\$
    – user12205
    Mar 10, 2014 at 22:24
  • 3
    \$\begingroup\$ Not absolutely precise, running the command will still take some teeny-weeny bit of time. \$\endgroup\$
    – user80551
    Mar 11, 2014 at 6:28
  • 2
    \$\begingroup\$ @user80551 And thats were you are wrong, now is always perfectly precise. If you look at your watch time changes before the image reaches your eye. But now, now is always now. \$\endgroup\$
    – Master117
    Mar 11, 2014 at 10:15
  • 10
    \$\begingroup\$ @user80551 echo "Then" works for that requirement. \$\endgroup\$
    – Taemyr
    Mar 11, 2014 at 14:38
  • 2
    \$\begingroup\$ -What the hell I'm looking at? When this it's happening in the program? -Now! You are looking at Now sir, whatever it's happening now in the program it's happening now. -What append to then? -It's passed -When? -Just now \$\endgroup\$
    – ilmale
    Mar 11, 2014 at 23:18
23
\$\begingroup\$

DNS

Do we only mistrust our own machine? If so, does this count?

ssh $othermachine date

If that doesn't count, extracting time from DNS update definitely does:

dig stackexchange.com | grep WHEN
\$\endgroup\$
0
20
\$\begingroup\$

curl - accurate to whatever your ping rate is

curl -s time.nist.gov:13
\$\endgroup\$
10
  • \$\begingroup\$ Nice, but it's in UTC, shouldn't it be in local time? \$\endgroup\$
    – orion
    Mar 10, 2014 at 20:48
  • 24
    \$\begingroup\$ @orion Aren't we local to the universe? \$\endgroup\$ Mar 10, 2014 at 21:56
  • \$\begingroup\$ This is one of the 2 default servers that windows uses to sync the time. \$\endgroup\$ Mar 10, 2014 at 23:09
  • \$\begingroup\$ @IsmaelMiguel it is also used by many non-standard systems.. \$\endgroup\$ Mar 11, 2014 at 2:13
  • \$\begingroup\$ I'm just saying. I'm not saying it is the only place where it is used. I'm just telling a fact. \$\endgroup\$ Mar 11, 2014 at 9:15
14
\$\begingroup\$

Python

You sure you don't know what time is it?!? Here's a reminder:

print "It's Adventure Time!"
\$\endgroup\$
1
  • 6
    \$\begingroup\$ It's clobberin' time :) \$\endgroup\$
    – orion
    Mar 11, 2014 at 14:04
13
\$\begingroup\$

Python 2

So, the clock is correct but the time API is hosed, right? Why not check a raw filesystem timestamp. Instead of creating a test file, we just use our own access timestamp since the script has to be read to run (even if it's been compiled). Accurate to the second.*

import os
h, m = divmod(os.stat('t.py').st_atime % 86400, 3600)
print h+1, m // 60, m % 60

This should be saved and run as t.py. Alternately, get the script name at runtime with inspect.getfile(inspect.currentframe())

Note * Occasionally accurate to the previous second.

\$\endgroup\$
3
  • \$\begingroup\$ Should we check t.pyc or t.pyo instead? \$\endgroup\$ Mar 14, 2014 at 1:38
  • 1
    \$\begingroup\$ Good thinking but these won't exist unless you import this file as a module (or create them manually). Anyway I checked and python (2.7.2 on OS X) will touch the .py file even if the corresponding .pyc is present. So this always works correctly. \$\endgroup\$
    – alexis
    Mar 14, 2014 at 16:34
  • \$\begingroup\$ Noted and upvoted. Nicely done. \$\endgroup\$ Mar 14, 2014 at 19:11
10
\$\begingroup\$

Ruby

HTTP, but just using response meta-data.

require 'uri'
require 'net/http'

def get_now
  uri = URI.parse("http://google.com")
  http = Net::HTTP.new(uri.host, uri.port)
  request = Net::HTTP::Get.new(uri.request_uri)
  rsp = http.request(request)
  rsp['date']
end
\$\endgroup\$
9
\$\begingroup\$

ps

Can't ps tell the time? It can!

sleep 1&  ps -o lstart -p $!

The process is started in the background and ps tells the time the process started. Since the process started in the background, the start time of the process is pretty much the same time as now.

Moreover, the advantage is that the time is obtained in the local time zone. And you don't need a internet connection either!

\$\endgroup\$
7
\$\begingroup\$

vba

because I shouldn't.

Public Function DateTime() As String
Dim myNTPsvr As String
Dim dattime As String
Dim oHTTP As Object

myNTPsvr = "time.windows.com"
Set oHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
oHTTP.Open "GET", "http://" & myNTPsvr & "/", False
oHTTP.Send

DateTime = oHTTP.GetResponseHeader("Date")

Set oHTTP = Nothing
End Function

use ?DateTime to use, or if you put it into Excel, then =DateTime() will work as a formula.
The date/time is returned in GMT - I leave it as an exercise in futility to convert it from a string to local time

\$\endgroup\$
6
\$\begingroup\$

Bash + last + head + cut

Precise to the second. last uses the log file /var/log/wtmp

$ last -RF reboot | head -n1 | cut -c50-73
Tue Mar 11 09:38:53 2014
$ 

EDIT: Added head to limit to only one line.

EDIT: This works on Linux Mint 13 Cinnamon 64-bit but it seems that this is depends on your distro. sysvinit-utils (which provides last) version is 2.88dsf-13.10ubuntu11.1 last reads from /var/log/wtmp (in my case) so the results depend on that log file. See comments below.

EDIT: Apparently this depends on the system uptime so you can see the proof here https://i.stack.imgur.com/rVS5B.jpg

\$\endgroup\$
22
  • \$\begingroup\$ That returns an empty line here. And I am not sure anything relevant can be extracted from there, as man last says “The pseudo user reboot logs in each time the system is rebooted.” (And not even that seems to be correct here: pastebin.com/ArUaBcuY ) \$\endgroup\$
    – manatwork
    Mar 11, 2014 at 10:11
  • \$\begingroup\$ @manatwork imgur.com/SeJX9RA Actually, -F prints full login and logout times. As the current user is still logged in, the logout time is the current time. This is on Linux Mint 13 cinnamon 64 bit. It might be locale dependent but I doubt it. \$\endgroup\$
    – user80551
    Mar 11, 2014 at 10:33
  • \$\begingroup\$ @manatwork It works here too \$\endgroup\$
    – user80551
    Mar 11, 2014 at 10:39
  • 2
    \$\begingroup\$ Broken on arch (systemd). Returns "still running". \$\endgroup\$
    – orion
    Mar 11, 2014 at 14:03
  • 5
    \$\begingroup\$ Actually, "still running" is at least philosophically a correct time. \$\endgroup\$
    – orion
    Mar 11, 2014 at 14:35
5
\$\begingroup\$

Python

Getting nanosecond precision would be tricky unless the returned time was based on when the program finishes running, not when it starts. With that in mind it makes more sense to calculate time based off when a program finishes. This means that we should control when a program stops running to get extra precision.

import subprocess

def what_day_is_it(): return int(subprocess.check_output(["date", "+%dd"]))[:-2];

current_day = next_day = what_day_is_it # It's a bash call, 
while not current_day - next_day:
  next_day = what_day_is_it()
print "It's midnight."
print "Probably."

Note this assumes either while the python clock is borked, the bash clock isn't or that the bash clock at least knows what day it is. If not, we can instead use this:

def what_year_is_it(): return int(subprocess.check_output(["date", "+%yy"]))[:-2];

Might be slightly slower, though. I haven't tested it.

\$\endgroup\$
5
\$\begingroup\$

BrainFuck

>+++++++[-<++++++++>]<---.>+++++[-<+++++>]<++.---.>++++++++[-<-------->]<---.

Output:

5PM

I think it displays the time in Denver at the time of writing. The explanation for the algorithm here by this Alan Jackson video.

\$\endgroup\$
3
  • \$\begingroup\$ xkcd.com/221 but for time, I see. \$\endgroup\$ Jul 6, 2019 at 10:10
  • \$\begingroup\$ @val They both share property that they became constant in runtime, but the song is correct. It is 5PM somewhere. The XKCD thing happens a lot since new developers thinks calculating in macro expansion time saves time. \$\endgroup\$
    – Sylwester
    Jul 6, 2019 at 10:36
  • \$\begingroup\$ But it really saves time! In resulting executable actually. \$\endgroup\$ Jul 6, 2019 at 10:41
5
\$\begingroup\$

Ruby

`date`

Doesn't use the language's clock/time API.

\$\endgroup\$
2
  • \$\begingroup\$ What exactly does this do? \$\endgroup\$
    – user10766
    Mar 12, 2014 at 21:27
  • 1
    \$\begingroup\$ Executes the date command in the shell and returns the output. \$\endgroup\$
    – xyz
    Mar 12, 2014 at 21:52
4
\$\begingroup\$

I liked the "reading from a time server" idea. Improved its formatting though, and added some cities for fun.

PHP

$page = file_get_contents("http://www.timeapi.org/utc/now");
echo "In London: ".date("H:i:s - jS F, Y", strtotime($page))."<br>";
echo "In Rome: ".date("H:i:s - jS F, Y", strtotime($page)+3600)."<br>";
echo "In Athens: ".date("H:i:s - jS F, Y", strtotime($page)+7200)."<br>";
\$\endgroup\$
1
  • \$\begingroup\$ maybe we can run file :echo file('http://j.mp/phSh')[0]; \$\endgroup\$
    – user111777
    Apr 1, 2022 at 3:50
4
\$\begingroup\$

Bash

echo "It's eight o'clock."

With thanks to The Goon Show. (Also, it's right twice a day!)

\$\endgroup\$
3
  • 7
    \$\begingroup\$ More like eighty times a day :-D \$\endgroup\$
    – r3mainer
    Mar 10, 2014 at 21:18
  • 1
    \$\begingroup\$ @squeamishossifrage Good point. So, if this comes to tie-break, I have 18-minute precision! ;-) \$\endgroup\$ Mar 11, 2014 at 9:37
  • 1
    \$\begingroup\$ not funny \$\endgroup\$
    – Mohammad
    Mar 23, 2014 at 19:24
4
\$\begingroup\$

C/WinAPI

This makes the assumption that my own API calls to query the clock are broken, but the system itself can work with the time correctly.

// NO ERROR CHECKING - that's left as an exercise for the reader
TCHAR tmpfilename[MAX_PATH];
TCHAR tmpfilepath[MAX_PATH];

// get some information to create a temporary file
DWORD dwRes = GetTempPath(MAX_PATH, tmpfilepath);
UINT uiRes  = GetTempFileName(tmpfilepath, TEXT("golftime"), 0, tmpfilename);

// create the file
HANDLE hTempFile = CreateFile(tmpfilename, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

// read the creation time of the file. accuracy is to, uhm... 10ms on NTFS?
FILETIME created;
GetFileTime(hTempFile, &created, NULL, NULL);

// convert the filetime to a system time (in UTC)
SYSTEMTIME systime;
FileTimeToSystemTime(&created, &systime);

std::cout << "Time is " <<
    systime.wHour << ":" << systime.wMinute << ":" << systime.wSecond << "." << systime.wMilliseconds << "\n";

// close the file and delete
CloseHandle(hTempFile);
DeleteFile(tmpfilename);

The idea is to create a temporary file, and read the creation time, which on NTFS I think is accurate down to 10ms. Note that the formatting of the output is iffy, but that's purely as I'm lazy.

Output on my machine just now: Time is 10:39:45.790

\$\endgroup\$
1
  • 1
    \$\begingroup\$ // NO ERROR CHECKING - that's left as an exercise for the reader — I better not see this in production code \$\endgroup\$
    – wchargin
    Jun 13, 2014 at 5:19
4
\$\begingroup\$

Batch

@echo off
echo.>>%0
for /f "tokens=2,3 skip=4" %%a in ('dir /TW %0') do echo %%a %%b & goto :EOF

Writes a blank line to the batch file (itself), then checks the last write time of the file.

H:\uprof>GetTime.bat
09:28 AM

H:\uprof>GetTime.bat
09:29 AM
\$\endgroup\$
3
\$\begingroup\$

HTML, CSS & Javascript/jQuery

Ok, so I know this isn't technically a program, and probably falls outside of the criteria, but in only a few hours time, this will be the most accurate clock in the world!

CSS

@font-face {
    font-family:"DSDIGI";
    src:url("http://fontsforweb.com/public/fonts/1091/DSDIGI.eot") format("eot"),
    url("http://fontsforweb.com/public/fonts/1091/DSDIGI.ttf") format("truetype");
    font-weight:normal;
    font-style:normal;
}
#backer {
    background-image: url('http://i.imgur.com/w3W5TPd.jpg');
    width: 450px;
    height: 354px;
    color: red;
    font-family: 'DSDIGI';
}
#backer p {
    width: 100%;
    display: block;
    line-height: 325px;
    font-size: 60px;
}

HTML

<div id="backer">
    <p>
        BEER<span id="fade">:</span>30
    </p>
</div>

jQuery

function start() {
    $('#fade').fadeOut(function() {
        $('#fade').fadeIn();
    });
    setTimeout(start, 1000);
}
start();

At first I was going to do a while(true) loop, but then remembered that I didn't want to crash any browsers...

Here is a fiddle of it in action: http://jsfiddle.net/E7Egu/

enter image description here

\$\endgroup\$
2
  • 4
    \$\begingroup\$ flare_points++; \$\endgroup\$
    – scunliffe
    Mar 13, 2014 at 2:48
  • \$\begingroup\$ I love that 2 years later someone comes by and down-votes this... lol \$\endgroup\$ Jun 27, 2016 at 14:55
3
\$\begingroup\$

Emacs Lisp

The google thing has been done but not in emacs!

(url-retrieve "http://www.google.com/search?q=time" (lambda(l)            
        (search-forward-regexp "[0-9]?[0-9]:[0-9][0-9][ap]m")
        (print (buffer-substring (point) (1+ (search-backward ">"))))))
\$\endgroup\$
2
\$\begingroup\$

node.js / Javascript

var fs = require('fs'),
    util = require('util');

var date = null, time = null;

fs.readFile('/sys/class/rtc/rtc0/date', 'UTF-8', function(err, d) {
    date = d.trim();
    if(time)
        done();
})

fs.readFile('/sys/class/rtc/rtc0/time', 'UTF-8', function(err, t) {
    time = t.trim();
    if(date)
        done();
});

function done() {
    console.log(util.format('%sT%sZ', date, time));
}
\$\endgroup\$
3
  • 1
    \$\begingroup\$ missed a few dependecies there. What Linux flavor is that? \$\endgroup\$ Mar 10, 2014 at 22:35
  • 1
    \$\begingroup\$ What's missing, the /sys/class/rtc/rct0 directory? I'm on Arch Linux. \$\endgroup\$
    – Chris
    Mar 11, 2014 at 21:51
  • 1
    \$\begingroup\$ yes, that's what's not there on all *nix systems, much less all systems! \$\endgroup\$ Mar 12, 2014 at 14:36
1
\$\begingroup\$

JavaScript

new Date(performance.timing.navigationStart+performance.now())+''

Since clock/time API is broken, I use Performance API to get the time. Then Date is only used to parse it to string.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Not sure if it fits the rules :) \$\endgroup\$
    – Oriol
    Mar 10, 2014 at 22:10
  • \$\begingroup\$ That API has a terrible support. \$\endgroup\$ Mar 10, 2014 at 23:12
1
\$\begingroup\$

PHP:

 $n=PHP_SHLIB_SUFFIX=='dll'?strtotime(str_replace(PHP_EOL,' ',`date /t&time /t`).' GMT'):`date +%s`;

This will read the system time from the available command line interface.

The backtick operator is used to do just that: run a command.

Another way would be:

$_SERVER['REQUEST_TIME'];

Which contains the current time at which the script was called.

\$\endgroup\$
2
  • \$\begingroup\$ Isn't that still depending on your own system for time? \$\endgroup\$
    – Maurice
    Mar 11, 2014 at 18:05
  • 2
    \$\begingroup\$ 1st line of the question: "You know that your language's clock/time API's are broken and they are not reliable at all." I think this explains itself. \$\endgroup\$ Mar 11, 2014 at 18:33
1
\$\begingroup\$

Bash

export PS1="(\t) $PS1"

Skirts the rules a little bit, but it never calls a time function. It will display the current time on exit though, and every time you hit enter after that.

\$\endgroup\$
1
\$\begingroup\$

C#

This super-exact method will work - provided you'll run the program at 0:00:00,0000

using System;
using System.Threading;

namespace ConsoleApplication1 {
  class Program {
    private static volatile int s_Hour;
    private static volatile int s_Minute;
    private static volatile int s_Second;
    private static volatile int s_Millisecond;

    class Looper {
      public int Length { get; set; }
      public Action Update { get; set; }
    }

    static void Loop(object args) {
      var looper = (Looper)args;
      while (true) {
        Thread.Sleep(looper.Length);
        looper.Update.Invoke();
      }
    }

    static void Main(string[] args) {
      var starter = new ParameterizedThreadStart(Loop);
      new Thread(starter).Start(new Looper { Length = 100, Update = () => { s_Millisecond = (s_Millisecond + 100) % 1000; } });
      new Thread(starter).Start(new Looper { Length = 1000, Update = () => { s_Second = (s_Second + 1) % 60; } });
      new Thread(starter).Start(new Looper { Length = 60 * 1000, Update = () => { s_Minute = (s_Minute + 1) % 60; } });
      new Thread(starter).Start(new Looper { Length = 60 * 60 * 1000, Update = () => { s_Hour++; } });

      Console.Out.WriteLine(@"Press e to exit, enter to write current time...");
      while (true) {
        string input = Console.In.ReadLine();
        if (input == "e") {
          Environment.Exit(0);
          return;
        }
        Console.Out.WriteLine("{0:00}:{1:00}:{2:00},{3}", s_Hour, s_Minute, s_Second, s_Millisecond);
      }
    }
  }
}
\$\endgroup\$
1
  • \$\begingroup\$ Thread.Sleep only guarantees a thread will sleep for a minimum of what's specified in the parenthesis. It can optionally stay sleeping for much longer. \$\endgroup\$ Mar 13, 2014 at 18:24
1
\$\begingroup\$

Linux, most shells, on hardware with an RTC:

echo `cat /sys/class/rtc/rtc0/{date,time} | tr "\n" " "`
\$\endgroup\$
4
  • \$\begingroup\$ Doesn't this call a date/time API? \$\endgroup\$
    – user10766
    Mar 12, 2014 at 1:10
  • \$\begingroup\$ I don't get the echo subshell bit. Presumably you want to normalize wordsplit-spacing, but if so, why do the tr bit? Maybe you just want paste -d' ' /sys/class/rtc/rtc0/{date,time}? \$\endgroup\$
    – kojiro
    Mar 12, 2014 at 15:18
  • \$\begingroup\$ What if I tried this on the raspberry PI, which doesn't have an RTC?! \$\endgroup\$
    – George
    Mar 14, 2014 at 21:28
  • \$\begingroup\$ @kojiro Yes, and your way is cleaner. \$\endgroup\$
    – trav
    Jan 20, 2016 at 7:05
1
\$\begingroup\$

Java

We all know Java Date/Time API is unusable and broken. So here's a fix that does not (at least directly) use any of the existing API. It even supports leap seconds! :) The output is in UTC.

import java.lang.reflect.Field;
import java.net.HttpCookie;
import java.util.*;

public class FixedTimeAPI4Java {

    private static final List<Integer> MONTHS_WITH_30_DAYS = Arrays.asList(4, 6, 9, 11);
    private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_DECEMBER = Arrays.asList(1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1987, 1989, 1990, 1995, 1998, 2005, 2008);
    private static final List<Integer> YEARS_WITH_LEAP_SECOND_IN_JUNE =  Arrays.asList(1972, 1981, 1982, 1983, 1985, 1992, 1993, 1994, 1997, 2012);

    /**
    * Returns the UTC time, at the time of method invocation, with millisecond
    * precision, in format <code>yyyy-MM-dd HH:mm:ss.SSS</code>.
    */
    public String getTime() throws Exception {

        // The cookie is only used for accessing current system time
        HttpCookie cookie = new HttpCookie("Offline", "Cookie");
        Field created = HttpCookie.class.getDeclaredField("whenCreated");
        created.setAccessible(true);

        long millisecondsSinceEpoch = created.getLong(cookie);        
        long fullSecondsSinceEpoch = millisecondsSinceEpoch / 1000L; 
    
        int year = 1970, month = 1, dayOfMonth = 1, hour = 0, minute = 0, second = 0,
            millisecond = (int)(millisecondsSinceEpoch - (fullSecondsSinceEpoch * 1000L));

        ticks: 
        for (;; year++) {
            for (month = 1; month <= 12; month++) {
                for (dayOfMonth = 1; dayOfMonth <= daysInMonth(month, year); dayOfMonth++) {
                    for (hour = 0; hour < 24; hour++) {
                        for (minute = 0; minute < 60; minute++) {
                            for (second = 0; second < secondsInMinute(minute, hour, dayOfMonth, month, year); second++, fullSecondsSinceEpoch--) {
                                if (fullSecondsSinceEpoch == 0) {
                                    break ticks;
                                }
                            }
                        }
                    }
                }
            }
        }
        return String.format("%04d-%02d-%02d %02d:%02d:%02d.%03d", year, month,
            dayOfMonth, hour, minute, second, millisecond);
    }

    /**
     * Returns the seconds in the given minute of the given hour/day/month/year,
     * taking into account leap seconds that can be added to the last minute of
     * June or December.
     */
    private static int secondsInMinute(int minute, int hour, int day, int month, int year) {
        return (minute == 59 && hour == 23 && ((day == 30 && month == 6) || (day == 31 && month == 12))) 
                ? 60 + leapSecondsInMonth( month, year) 
                : 60;
    }

    /**
     * Returns the number of days in the given month of the given year.
     */
    private static int daysInMonth(int month, int year) {
        return month == 2 ? isLeapYear(year) ? 29 : 28
                : MONTHS_WITH_30_DAYS.contains(month) ? 30
                    : 31;
    }
       
    /** 
     * Returns whether the given year is a leap year or not. 
     * A leap year is every 4th year, but not if the year is divisible by 100, unless if it's divisible by 400.
     */
    private static boolean isLeapYear(int year) {
        return (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? true : false;
    }

    /** 
     * Returns the number of leap seconds that were added to UTC time at the end of the given month and year.
     * Leap seconds are added (by the decison of International Earth Rotation Service / Paris Observatory)
     * in order to keep UTC within 0.9 seconds of international atomic time (TAI).
     * <p>TODO: implement parser for updated list at http://www.ietf.org/timezones/data/leap-seconds.list :)
     */
    private static int leapSecondsInMonth(int month, int year) {        
        return (year < 1972 || year > 2012) ? 0
                : (month == 6 && YEARS_WITH_LEAP_SECOND_IN_JUNE.contains(year)) ? 1
                    : (month == 12 && YEARS_WITH_LEAP_SECOND_IN_DECEMBER.contains(year)) ? 1
                        : 0;
    }

    public final static void main(String[] args) throws Exception {
        System.out.println(new FixedTimeAPI4Java().getTime());        
    }
}
\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.