Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

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

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

38 Answers 38

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

share|improve this answer
46  
+1 for "There is no sky. Everyone's going to die" :D –  Doorknob Mar 11 at 12:15
4  
"Everyone's going to die - or your finger is over the camera. Basically the same thing." –  corsiKa Mar 11 at 17:49
    
Please specify Java –  user1886419 Mar 11 at 18:37
3  
This is definitely my favorite, I just hope it doesn't come down to a tiebreaker... –  Dryden Long Mar 11 at 19:42
19  
What about Eclipses? They're likely to cause as much of a problem here as they do during Java development! –  Poldie Mar 13 at 12:06

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
share|improve this answer
2  
Only accurate to the second...and the second that SO pings its ntp..shameful worship –  David Wilkins Mar 11 at 2:16
2  
+1 for sheer unadulterated brilliance... –  WallyWest Mar 11 at 6:00
1  
THE <CENTER> CANNOT HOLD HE COMES –  Doorknob Apr 1 at 1:11
    
@Doorknob I really need to print out that post and hang it on my wall. –  WChargin Jun 13 at 5:16

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.

share|improve this answer
1  
Doesn't work. It says permission denied :) –  devnull Mar 11 at 4:32
3  
@devnull your filesystem is terribly broken. Fix it with cd $(mktemp -d) –  mniip Mar 11 at 4:40
    
Meh, the dir time is set using a library function. –  Navin Mar 12 at 0:17
    
@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 Mar 12 at 3:42
    
@mniip Welll, alright. I still feel that touch is a library function/command since it has the desired side effect. –  Navin Mar 12 at 3:59

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

share|improve this answer
    
@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. –  ace Mar 10 at 22:16
9  
I only just realised that the comic displayed changes depending on the time of day. That's awesome. –  RJFalconer Mar 11 at 14:34
2  
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. –  David Richerby Mar 11 at 14:55
16  
I say +1 to xkcd for not observing daylight saving time, and hope the rest of the world follows suit. –  hoosierEE Mar 12 at 0:19

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.

share|improve this answer
2  
I'm sure this is bending of the rules... uniqid is still a part of your language... But still you get a +1 –  mniip Mar 10 at 18:14
    
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... –  Mig Mar 10 at 18:28
1  
I'm not speaking of time API calls here. I'm saying that it's still a part of the language. –  mniip Mar 10 at 18:30
2  
@mniip yes, but uniqid() was broken before this question was even asked. only the clock/time APIs are broken in this question –  Riking Mar 11 at 3:29

Bash

Just to be always absolutely precise and correct:

echo "Now"

or motivating:

echo "Now, do something useful today"
share|improve this answer
10  
toady, noun, plural toadies. An obsequious flatterer; sycophant. (Source) –  ace Mar 10 at 22:24
3  
Not absolutely precise, running the command will still take some teeny-weeny bit of time. –  user80551 Mar 11 at 6:28
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 Mar 11 at 10:15
10  
@user80551 echo "Then" works for that requirement. –  Taemyr Mar 11 at 14:38
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 Mar 11 at 23:18

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
share|improve this answer

curl - accurate to whatever your ping rate is

curl -s time.nist.gov:13
share|improve this answer
    
Nice, but it's in UTC, shouldn't it be in local time? –  orion Mar 10 at 20:48
24  
@orion Aren't we local to the universe? –  Pureferret Mar 10 at 21:56
    
This is one of the 2 default servers that windows uses to sync the time. –  Ismael Miguel Mar 10 at 23:09
    
@IsmaelMiguel it is also used by many non-standard systems.. –  David Wilkins Mar 11 at 2:13
    
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 Mar 11 at 9:15

Python

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

print "It's Adventure Time!"
share|improve this answer
6  
It's clobberin' time :) –  orion Mar 11 at 14:04
10  
+1 for an algebraic solution. –  Kevin Mar 12 at 4:30

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.

share|improve this answer
    
Should we check t.pyc or t.pyo instead? –  Kyle Kelley Mar 14 at 1:38
1  
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. –  alexis Mar 14 at 16:34
    
Noted and upvoted. Nicely done. –  Kyle Kelley Mar 14 at 19:11

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
share|improve this answer

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!

share|improve this answer

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

share|improve this answer

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.

share|improve this answer

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

share|improve this answer
    
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 ) –  manatwork Mar 11 at 10:11
    
@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. –  user80551 Mar 11 at 10:33
    
@manatwork It works here too –  user80551 Mar 11 at 10:39
1  
Broken on arch (systemd). Returns "still running". –  orion Mar 11 at 14:03
4  
Actually, "still running" is at least philosophically a correct time. –  orion Mar 11 at 14:35

Ruby

`date`

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

share|improve this answer
    
What exactly does this do? –  hosch250 Mar 12 at 21:27
1  
Executes the date command in the shell and returns the output. –  fearpi Mar 12 at 21:52

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.

share|improve this answer

Bash

echo "It's eight o'clock."

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

share|improve this answer
7  
More like eighty times a day :-D –  squeamish ossifrage Mar 10 at 21:18
1  
@squeamishossifrage Good point. So, if this comes to tie-break, I have 18-minute precision! ;-) –  David Richerby Mar 11 at 9:37
1  
not funny –  Mhmd Mar 23 at 19:24

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>";
share|improve this answer

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

share|improve this answer
    
// NO ERROR CHECKING - that's left as an exercise for the reader — I better not see this in production code –  WChargin Jun 13 at 5:19

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

share|improve this answer
4  
flare_points++; –  scunliffe Mar 13 at 2:48

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
share|improve this answer

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 ">"))))))
share|improve this answer

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));
}
share|improve this answer
1  
missed a few dependecies there. What Linux flavor is that? –  Not that Charles Mar 10 at 22:35
1  
What's missing, the /sys/class/rtc/rct0 directory? I'm on Arch Linux. –  Chris Mar 11 at 21:51
1  
yes, that's what's not there on all *nix systems, much less all systems! –  Not that Charles Mar 12 at 14:36

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.

share|improve this answer

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);
      }
    }
  }
}
share|improve this answer
    
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. –  insta Mar 13 at 18:24

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.

share|improve this answer
2  
Not sure if it fits the rules :) –  Oriol Mar 10 at 22:10
    
That API has a terrible support. –  Ismael Miguel Mar 10 at 23:12

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.

share|improve this answer
    
Isn't that still depending on your own system for time? –  Maurice Mar 11 at 18:05
2  
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. –  Ismael Miguel Mar 11 at 18:33

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());        
    }
}
share|improve this answer

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

share|improve this answer

protected by xfix Mar 13 at 13:39

Thank you for your interest in this question. Because it has attracted low-quality answers, posting an answer now requires 10 reputation on this site.

Would you like to answer one of these unanswered questions instead?

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