[Question]
  [
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
 
 
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/23662/edit).
Closed 7 years ago.
[Improve this question](/posts/23662/edit) 
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).
  
[Answer]
# 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](https://i.stack.imgur.com/H41tQ.png)
---
![enter image description here](https://i.stack.imgur.com/tAz6N.png)
[Answer]
# Ruby
Let's be honest: time only changes when something is posted on [stackoverflow.com](http://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
```
[Answer]
## 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](http://xkcd.com/1335/))
[world map with timezone http://c.xkcd.com/redirect/comic/now](http://c.xkcd.com/redirect/comic/now)
[Answer]
# 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.
[Answer]
## 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.
[Answer]
**Bash**
Just to be always absolutely precise and correct:
```
echo "Now"
```
or motivating:
```
echo "Now, do something useful today"
```
[Answer]
# 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
```
[Answer]
# curl - accurate to whatever your ping rate is
```
curl -s time.nist.gov:13
```
[Answer]
# Python
You sure you don't know what time is it?!? Here's a reminder:
```
print "It's Adventure Time!"
```
[Answer]
# 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.
[Answer]
## 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
```
[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!
[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
[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 <https://i.stack.imgur.com/rVS5B.jpg>
[Answer]
## 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.
[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](http://youtu.be/BPCjC543llU).
[Answer]
# Ruby
```
`date`
```
Doesn't use the language's clock/time API.
[Answer]
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>";
```
[Answer]
# Bash
```
echo "It's eight o'clock."
```
With thanks to [The Goon Show](https://www.youtube.com/watch?v=ctM_Rvgjfpo). (Also, it's right twice a day!)
[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`
[Answer]
### 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
```
[Answer]
**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](https://i.stack.imgur.com/NXPO1.gif)
[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 ">"))))))
```
[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));
}
```
[Answer]
# JavaScript
```
new Date(performance.timing.navigationStart+performance.now())+''
```
Since clock/time API is broken, I use [Performance API](https://developer.mozilla.org/en-US/docs/Web/API/Performance) to get the time. Then `Date` is only used to parse it to string.
[Answer]
# 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.
[Answer]
## 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.
[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);
      }
    }
  }
}
```
[Answer]
Linux, most shells, on hardware with an RTC:
```
echo `cat /sys/class/rtc/rtc0/{date,time} | tr "\n" " "`
```
[Answer]
## 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());        
    }
}
```
]