Could you please tell me the time?

55

13

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).

microbian

Posted 2014-03-10T17:15:19.433

Reputation: 2 297

Question was closed 2016-06-23T18:48:20.150

2In other words, talk to a time server? – Peter Taylor – 2014-03-10T17:21:45.897

3Yes, you can do that. One possible solution. – microbian – 2014-03-10T17:23:12.520

3Rather unspecific question. I guess the most votes will be gathered by an answer like print(input("Please enter the current time")). – Howard – 2014-03-10T17:32:12.360

@Howard Is that banned by our standard loopholes? It should be. – Justin – 2014-03-10T17:39:24.120

7My money is on "Load REPL for different language and call its non-broken time API." – Jonathan Van Matre – 2014-03-10T17:46:23.063

Can I call library functions that call something like GetDate() in its definition? – swish – 2014-03-10T18:42:10.757

2@swich that is also not allowed. Because your answer will become unreliable. – microbian – 2014-03-10T19:30:56.107

To clarify - the system time is correct, but all the standard APIs are broken? Or is the machine time incorrect as well? – Allen Gould – 2014-03-10T19:35:16.680

System time is correct, it is only your language that when it tries to read system clock, it reads the wrong value. – microbian – 2014-03-10T19:40:17.013

Sorry for the unconstructive comment here, but: The time is 9:35 and it is the 11th of March 2014 :) Back to the Q = Nice question :) Are we allowed to open web pages? – George – 2014-03-11T21:36:26.183

Yes, you can do it. I want to see your solution. – microbian – 2014-03-11T21:40:05.617

Since i can't post an answer, I'll just leave it here: python: current_time = input("I know it sound's weird but my clock is broken. Could you tell me the accurate time please? I'm talking micro-seconds here. Thanks in advance.") – Yekhezkel Yovel – 2014-11-26T20:29:26.820

Another option (a bit more serious this time): constantly send GET request for which the response include the "Date" header. Parse the time from the "Date" header only the first time you receive it - but continue to request it. When the received "Date" changes you know you are a short time after a cycle, which get's you a bit more accurate. Continue to do so until you get banned for performing D.O.S attack on the site. – Yekhezkel Yovel – 2014-11-26T20:38:16.323

After that move to another site. This method is called para-site. – Yekhezkel Yovel – 2014-11-26T20:43:52.573

Answers

121

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

Piotr

Posted 2014-03-10T17:15:19.433

Reputation: 1 321

@DrEval "Eclipses" Was this an intended pun? – HyperNeutrino – 2017-02-24T01:53:50.410

49+1 for "There is no sky. Everyone's going to die" :D – Doorknob – 2014-03-11T12:15:28.833

6"Everyone's going to die - or your finger is over the camera. Basically the same thing." – corsiKa – 2014-03-11T17:49:37.627

Please specify Java – user1886419 – 2014-03-11T18:37:27.807

3This is definitely my favorite, I just hope it doesn't come down to a tiebreaker... – Dryden Long – 2014-03-11T19:42:17.190

@corsiKa: putting your finger over the camera probably won't raise an exception though. – marinus – 2014-03-12T16:56:20.333

What about sunsets? Will it say it is early? – None – 2014-03-12T22:05:32.707

Some places this app only works during spring and autumn. – Sylwester – 2014-03-12T22:59:18.450

21What about Eclipses? They're likely to cause as much of a problem here as they do during Java development! – bye – 2014-03-13T12:06:26.657

You sure live in a beautiful neighborhood. – magnattic – 2014-03-17T10:57:45.870

64

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

David Herrmann

Posted 2014-03-10T17:15:19.433

Reputation: 1 544

2Only accurate to the second...and the second that SO pings its ntp..shameful worship – David Wilkins – 2014-03-11T02:16:20.623

3THE <CENTER> CANNOT HOLD HE COMES – Doorknob – 2014-04-01T01:11:31.020

@Doorknob I really need to print out that post and hang it on my wall. – wchargin – 2014-06-13T05:16:04.313

30

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

user12205

Posted 2014-03-10T17:15:19.433

Reputation: 8 752

@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. – user12205 – 2014-03-10T22:16:47.663

9I only just realised that the comic displayed changes depending on the time of day. That's awesome. – RJFalconer – 2014-03-11T14:34:34.670

2It'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. – David Richerby – 2014-03-11T14:55:48.923

16I say +1 to xkcd for not observing daylight saving time, and hope the rest of the world follows suit. – hoosierEE – 2014-03-12T00:19:46.667

29

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.

mniip

Posted 2014-03-10T17:15:19.433

Reputation: 9 396

1Doesn't work. It says permission denied :) – devnull – 2014-03-11T04:32:36.790

5@devnull your filesystem is terribly broken. Fix it with cd $(mktemp -d) – mniip – 2014-03-11T04:40:52.690

Meh, the dir time is set using a library function. – Navin – 2014-03-12T00:17:35.420

@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 – mniip – 2014-03-12T03:42:34.170

@mniip Welll, alright. I still feel that touch is a library function/command since it has the desired side effect. – Navin – 2014-03-12T03:59:05.987

25

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.

Michael M.

Posted 2014-03-10T17:15:19.433

Reputation: 12 173

2I'm sure this is bending of the rules... uniqid is still a part of your language... But still you get a +1 – mniip – 2014-03-10T18:14:58.350

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... – Michael M. – 2014-03-10T18:28:36.293

1I'm not speaking of time API calls here. I'm saying that it's still a part of the language. – mniip – 2014-03-10T18:30:37.100

2@mniip yes, but uniqid() was broken before this question was even asked. only the clock/time APIs are broken in this question – Riking – 2014-03-11T03:29:00.473

23

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

orion

Posted 2014-03-10T17:15:19.433

Reputation: 3 095

23

Bash

Just to be always absolutely precise and correct:

echo "Now"

or motivating:

echo "Now, do something useful today"

Master117

Posted 2014-03-10T17:15:19.433

Reputation: 389

10

toady, noun, plural toadies. An obsequious flatterer; sycophant. (Source)

– user12205 – 2014-03-10T22:24:48.100

3Not absolutely precise, running the command will still take some teeny-weeny bit of time. – user80551 – 2014-03-11T06:28:29.840

2@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. – Master117 – 2014-03-11T10:15:57.327

@ace Thank you for enlightening me. – Master117 – 2014-03-11T10:16:45.770

@Master117 Nope, I want the time *exactly* when I hit the enter key. Since echo Now is not instantaneous , there is some time lag between me hitting enter and bash echoing "Now". – user80551 – 2014-03-11T10:22:29.223

1@user80551 that means the time isnt there instantly but its result is still perfectly precise when it arrives – Master117 – 2014-03-11T10:32:01.447

@Master117 By that logic, all answers will be invalid one second later. – user80551 – 2014-03-11T10:38:48.677

10@user80551 echo "Then" works for that requirement. – Taemyr – 2014-03-11T14:38:04.070

2-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 – ilmale – 2014-03-11T23:18:57.193

The second solution is without doubts even better than my solution. – Antonio Ragagnin – 2014-03-12T09:02:53.653

@ace maybe the script wanted a new feature added to Dwarf Fortress – user253751 – 2014-03-17T05:52:47.463

20

curl - accurate to whatever your ping rate is

curl -s time.nist.gov:13

David Wilkins

Posted 2014-03-10T17:15:19.433

Reputation: 593

Nice, but it's in UTC, shouldn't it be in local time? – orion – 2014-03-10T20:48:57.187

24@orion Aren't we local to the universe? – Pureferret – 2014-03-10T21:56:56.333

This is one of the 2 default servers that windows uses to sync the time. – Ismael Miguel – 2014-03-10T23:09:27.363

@IsmaelMiguel it is also used by many non-standard systems.. – David Wilkins – 2014-03-11T02:13:56.690

I'm just saying. I'm not saying it is the only place where it is used. I'm just telling a fact. – Ismael Miguel – 2014-03-11T09:15:03.390

Some of these timeservers don't respond on IPv6, so this may fail. – Michael Hampton – 2014-03-12T23:02:53.160

curl: (56) Recv failure: Connection reset by peer – kirb – 2014-03-15T01:58:24.857

Some “non-standard systems” have their kernel run in UTC since it makes more sense for logfiles. How about your “standard system”? – Martin Ueding – 2014-03-17T14:22:27.903

Where in the OP does the challenge mention "Local" time? I'm befuddled as to why I am getting these comments from @orion and queueoverflow – David Wilkins – 2014-03-17T14:29:31.223

I just commented because the returned time may differ from what you would get from date and since you are replacing it, it needs postprocessing. However, I absolutely agree that UTC is the only sensible option of internal timekeeping for an OS&hardware. Otherwise you fly to a different timezone and everything becomes crippled. – orion – 2014-03-17T14:37:27.733

14

Python

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

print "It's Adventure Time!"

Antonio Ragagnin

Posted 2014-03-10T17:15:19.433

Reputation: 1 109

6It's clobberin' time :) – orion – 2014-03-11T14:04:52.577

13

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.

alexis

Posted 2014-03-10T17:15:19.433

Reputation: 432

Should we check t.pyc or t.pyo instead? – Kyle Kelley – 2014-03-14T01:38:58.183

1Good 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. – alexis – 2014-03-14T16:34:35.083

Noted and upvoted. Nicely done. – Kyle Kelley – 2014-03-14T19:11:50.053

10

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

Not that Charles

Posted 2014-03-10T17:15:19.433

Reputation: 1 905

9

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!

devnull

Posted 2014-03-10T17:15:19.433

Reputation: 1 591

7

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

SeanC

Posted 2014-03-10T17:15:19.433

Reputation: 1 117

6

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 http://imgur.com/pqGGPmE

user80551

Posted 2014-03-10T17:15:19.433

Reputation: 2 520

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: http://pastebin.com/ArUaBcuY )

– manatwork – 2014-03-11T10:11:10.297

@manatwork http://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.

– user80551 – 2014-03-11T10:33:47.987

@manatwork It works here too

– user80551 – 2014-03-11T10:39:34.260

I see. So the relevant lines are completely missing here on a Frugalware 1.9 and an Ubuntu 12.04. But almost worked on an ancient Sorcerer: last output the log lines, but had no -F switch. Anyway, it confirmed your code is correct. – manatwork – 2014-03-11T11:15:43.733

Er, this should work on 12.04, LM13 uses it as its base. btw what do you mean by ancient Sorcerer – user80551 – 2014-03-11T11:16:41.830

This is my man page http://pastebin.com/TW2Qm0jH

– user80551 – 2014-03-11T11:20:36.423

No idea. By the way, the Ubuntu machine I can access only through ssh, not sure whether that affects last. http://pastebin.com/DFTd2cTq

– manatwork – 2014-03-11T11:20:56.530

@manatwork Mine has 12.04. 4 What's the version of sysvinit-utils? http://pastebin.com/krMeYv9u

– user80551 – 2014-03-11T11:30:47.070

Exactly the same: 2.88dsf-13.10ubuntu11 – manatwork – 2014-03-11T11:53:28.967

2Broken on arch (systemd). Returns "still running". – orion – 2014-03-11T14:03:57.910

@orion No idea about other distros, added that to the answer. Works for me :). – user80551 – 2014-03-11T14:29:51.967

5Actually, "still running" is at least philosophically a correct time. – orion – 2014-03-11T14:35:15.560

Depends on more than the distro. I'm also using Mint 13 Cinnamon 64 and I have to use last | cut -c40-56 | head -n1 – Comintern – 2014-03-12T04:45:12.950

@Comintern that would give you the login time. What does my code output on your system? – user80551 – 2014-03-12T09:39:51.373

@user80551 It gives me the top line of the wtmp log, which is the last time I opened a terminal. It will obviously only give the "current" time in a new terminal. – Comintern – 2014-03-12T12:13:01.397

@Comintern I think you forgot reboot. – user80551 – 2014-03-12T12:26:15.300

@user80551 Your code gives me an empty line. When I open a new terminal and run last, it outputs: http://pastebin.com/TPV4z5iG - no reboot.

– Comintern – 2014-03-12T12:34:15.087

@Comintern run last -RF reboot http://imgur.com/pqGGPmE

– user80551 – 2014-03-12T12:36:29.420

@user80551 wtmp begins Mon Mar 3 07:32:47 2014 Note that isn't the last reboot either, it's the last time that the wtmp log was rolled. Uptime has been months. – Comintern – 2014-03-12T16:57:39.527

@Comintern If it depends on uptime, I honestly had no idea and I have no way to test so I'm going to stick with "works for me". – user80551 – 2014-03-12T17:04:12.410

I think there's something wrong with the cut command. Your program gives me still logged in. If I change the last part to cut -c23-46, I get Wed Mar 12 22:00:54 2014. Note that, even if it is precise to the second, it is not accurate to the second. I tried several times and every time it outputs the time when I opened the terminal. – user12205 – 2014-03-12T22:08:28.727

@ace See the link to the image in the question. Wrapping it in a while true with sleep 2 gives the correct answer. – user80551 – 2014-03-13T03:50:32.140

5

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.

Hovercouch

Posted 2014-03-10T17:15:19.433

Reputation: 659

5

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.

Sylwester

Posted 2014-03-10T17:15:19.433

Reputation: 3 678

https://xkcd.com/221/ but for time, I see. – val says Reinstate Monica – 2019-07-06T10:10:33.217

@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. – Sylwester – 2019-07-06T10:36:52.473

But it really saves time! In resulting executable actually. – val says Reinstate Monica – 2019-07-06T10:41:55.967

5

Ruby

`date`

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

bblack

Posted 2014-03-10T17:15:19.433

Reputation: 158

What exactly does this do? – None – 2014-03-12T21:27:00.177

1Executes the date command in the shell and returns the output. – bblack – 2014-03-12T21:52:47.643

4

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>";

Vereos

Posted 2014-03-10T17:15:19.433

Reputation: 4 079

4

Bash

echo "It's eight o'clock."

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

David Richerby

Posted 2014-03-10T17:15:19.433

Reputation: 193

7

More like eighty times a day :-D

– r3mainer – 2014-03-10T21:18:27.047

1@squeamishossifrage Good point. So, if this comes to tie-break, I have 18-minute precision! ;-) – David Richerby – 2014-03-11T09:37:53.987

1not funny – Mhmd – 2014-03-23T19:24:39.283

4

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

icabod

Posted 2014-03-10T17:15:19.433

Reputation: 191

1// NO ERROR CHECKING - that's left as an exercise for the reader — I better not see this in production code – wchargin – 2014-06-13T05:19:49.030

4

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

unclemeat

Posted 2014-03-10T17:15:19.433

Reputation: 2 302

3

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

Dryden Long

Posted 2014-03-10T17:15:19.433

Reputation: 217

I love that 2 years later someone comes by and down-votes this... lol – Dryden Long – 2016-06-27T14:55:11.393

4flare_points++; – scunliffe – 2014-03-13T02:48:40.147

3

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 ">"))))))

Jordon Biondo

Posted 2014-03-10T17:15:19.433

Reputation: 1 030

2

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));
}

Chris

Posted 2014-03-10T17:15:19.433

Reputation: 21

1missed a few dependecies there. What Linux flavor is that? – Not that Charles – 2014-03-10T22:35:54.577

1What's missing, the /sys/class/rtc/rct0 directory? I'm on Arch Linux. – Chris – 2014-03-11T21:51:21.310

1yes, that's what's not there on all *nix systems, much less all systems! – Not that Charles – 2014-03-12T14:36:21.477

1

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.

Oriol

Posted 2014-03-10T17:15:19.433

Reputation: 792

2Not sure if it fits the rules :) – Oriol – 2014-03-10T22:10:26.913

That API has a terrible support. – Ismael Miguel – 2014-03-10T23:12:07.343

1

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.

Ismael Miguel

Posted 2014-03-10T17:15:19.433

Reputation: 6 797

Isn't that still depending on your own system for time? – Maurice – 2014-03-11T18:05:04.470

21st 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. – Ismael Miguel – 2014-03-11T18:33:35.823

1

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.

Comintern

Posted 2014-03-10T17:15:19.433

Reputation: 3 632

1

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);
      }
    }
  }
}

Ondrej Svejdar

Posted 2014-03-10T17:15:19.433

Reputation: 119

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. – Bryan Boettcher – 2014-03-13T18:24:10.470

1

Linux, most shells, on hardware with an RTC:

echo `cat /sys/class/rtc/rtc0/{date,time} | tr "\n" " "`

trav

Posted 2014-03-10T17:15:19.433

Reputation: 11

@kojiro Yes, and your way is cleaner. – trav – 2016-01-20T07:05:54.700

Doesn't this call a date/time API? – None – 2014-03-12T01:10:11.293

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}? – kojiro – 2014-03-12T15:18:29.167

What if I tried this on the raspberry PI, which doesn't have an RTC?! – George – 2014-03-14T21:28:23.350

1

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());        
    }
}

Mick Mnemonic

Posted 2014-03-10T17:15:19.433

Reputation: 189

1

HTML

Pure HTML, no Javascript or anything. Less is more.

<title>Time</title>
<iframe src="http://wwp.greenwichmeantime.com/time/scripts/clock-8/runner.php"></iframe>

jsFiddle

Mr Lister

Posted 2014-03-10T17:15:19.433

Reputation: 3 668

1

Python in a linux xterm

import os
n=os.stat('/dev/ptmx')[7]
n,s=divmod(n,60)
n,m=divmod(n,60)
n,h=divmod(n,24)
y,d=divmod(n,365)
print "It is {}:{}:{} GMT on the {}th day of {}".format(
    h,m,s,d-(y/4-1),y+1970)

/dev/ptmx/ has its timestamp updated every time the xterm is written to, which includes the command invocation.

AShelly

Posted 2014-03-10T17:15:19.433

Reputation: 4 281

0

CPython

gettime.py:

import struct
import gettime

if __name__ == '__main__':
    print struct.unpack('i', open('gettime.pyc').read()[4:8])[0], 'seconds after Unix epoch'

The self-import statement compiles it to a .pyc file, which contains the timestamp as the second 4-byte word.

Doesn't work multiple times in a row unless you change the .py file or delete the .pyc file.

Fraxtil

Posted 2014-03-10T17:15:19.433

Reputation: 2 495

0

Groovy

def latLong = "http://www.ipligence.com/geolocation".toURL().text =~ /GLatLng\(([^)]*)/
def lat= latLong[0][1].tokenize(",")[0].trim()
def lng = latLong[0][1].tokenize(",")[1].trim()
def xml = "http://www.earthtools.org/timezone/${lat}/${lng}".toURL().text
println new XmlSlurper().parseText(xml).localtime

Get latitude and longitude by IP address, then make a Http request to a time server via the latitude and longitude.

md_rasler

Posted 2014-03-10T17:15:19.433

Reputation: 201

-2

Wolfram Language

WolframAlpha["now", {{"Result", 1}, "Plaintext"}]

> 11:15:35 pm MSK  |  Monday, March 10, 2014

swish

Posted 2014-03-10T17:15:19.433

Reputation: 7 484

8Isn't "now" a built in function for time? – Milo – 2014-03-11T04:31:40.140

@Milo No, it's online query to wolframalpha.com. – swish – 2014-03-12T05:36:12.047