Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Display a Digital Clock

(I see there are many clock challenges, I have tried to read them all, I'm pretty sure this is unique)

Write some code that continuously updates a digital clock displayed in the format h:m:s where h, m, and s can occupy 1 or 2 characters each. The restrictions in simple terms as @BlueEyedBeast put it, I basically want it to replace the time shown.

  • Newlines are not allowed
  • Trailing spaces are allowed
  • Other trailing characters are not allowed
  • No seconds should be missed (57 -> 59 is not allowed)
  • Numbers beginning with "0" are allowed, as long as they don't occupy more than 2 characters
  • The code must not accept any input
  • If your language can't get the current time without input, you may use for input up to 8 bytes in a standardly allowed way
  • Output must be to stdout
  • This is codegolf so the shortest answer wins!

Example

I'm working on a language named *><> (starfish) because programs like this aren't possible in ><> (just wait for file i/o) . Here's a working digital clock program in it (ungolfed). This program is written in *><>:

s":"m":"hnonon"   "ooo88888888888ooooooooooo1S

Note: Everything is identical to ><> in this except, s = second, m = minute, h = hour, S = sleep(100ms*x)

This outputs:

14:44:31

Updating every 100ms until terminated.

Disallowed Examples

The following are not allowed:

1:

14:44:3114:44:32

2:

14:44:31 14:44:32

3:

14:44:31
14:44:32

The time must remain on the first line it was outputted with no visible trailing characters. Clearing the terminal though, would be allowed as that still wouldn't have any trailing characters.

share|improve this question
    
do we have to wait 100ms or can we just update constantly forever? – BlueEyedBeast yesterday
    
you don't have to wait, the wait is just what the example does. – redstarcoder yesterday
2  
The challenge requirements seem too strict to me. – mbomb007 yesterday
    
I just thought without restricting the output this would have been too easy. There are a multitude of ways to write the time to one line. Why is this too strict? – redstarcoder yesterday
    
@mbomb007 I removed "The program must be able to exit on user input that isn't a signal/interrupt" as the current answers didn't seem to follow it anyways. – redstarcoder yesterday

19 Answers 19

HTML + JS (ES6), 8 + 60 = 69 bytes

Tested in Chrome.

setInterval`a.innerHTML=new Date().toLocaleTimeString('fr')`
<a id=a>

-1 byte (@ETHProductions): Use French time format instead of .toTimeString().slice(0,8)


HTML + JS (ES6), 8 + 62 = 70 bytes

This will work in FireFox.

setInterval('a.innerHTML=new Date().toLocaleTimeString`fr`',0)
<a id=a>

-3 bytes (@ETHProductions): Use French time format instead of .toTimeString().slice(0,8)

share|improve this answer
2  
How does this work? I've never seen the backtick syntax before. I can't find anything on it either after some quick searching. – Carcigenicate yesterday
1  
Working for me in Inox (Chromium) – redstarcoder yesterday
1  
@Carcigenicate It's part of the latest JavaScript spec, ECMAScript6. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – darrylyeo yesterday
    
@darrylyeo Thanks. I could find things on the literal syntax, but I couldn't see how it was applied here. I need to read the spec again. I still don't understand how the function that precedes the backtick is used. – Carcigenicate yesterday
1  
You can save 3 bytes in the Firefox one with new Date().toLocaleTimeString`fr` (1 byte in the Chrome one with ...TimeString('fr')) – ETHproductions yesterday

Python 2, 50 bytes

(Python 2.1+ for ctime with no argument)

import time
while 1:print'\r'+time.ctime()[11:19],

time.ctime() yields a formatted string, from which the hh:mm:ss may be sliced using [11:19] (it remains in the same location whatever the date and time).

printing the carriage return '\r' before the text and making the text the first item of a tuple with , effectively suppresses the implicit trailing '\n' and overwrites the previously written output.

while 1 loops forever.

share|improve this answer
2  
I think this needs a , at the end to supress the newline otherwise in Python 2.7.12 I get newlines. – redstarcoder yesterday
    
Oops, yes you are correct... updated – Jonathan Allan yesterday

Pyke, 6 bytes

Ctr\ J

Try it here!

I think this is valid. Replace the space character with carriage return for valid output (does not work online)

share|improve this answer
    
Sorry it's not. No newlines are allowed or trailing characters after the time. I'll put 2 examples to be more explicit. – redstarcoder yesterday
    
I don't see that in the spec? – BlueEyedBeast yesterday
1  
The first line says newlines are not allowed, the third says no trailing characters. I'm sorry if that's unclear, I'd appreciate advice on fixing it. – redstarcoder yesterday
    
So you want it to replace the old time shown? – BlueEyedBeast yesterday
    
Yes exactly! Your current code seems perfect. – redstarcoder yesterday

QBIC, 6 bytes

{_C?_d

{      Starts a DO-loop
 _C    CLS
   ?   PRINT
    _d TIME$

Constantly clears the screen ansd prints the system time in the format 22:03:41.

share|improve this answer

Mathematica, 48 41 37 28 bytes

Do[s=Now[[2]],∞]~Monitor~s

The output will be a TimeObject, refreshing continuously.

Looks like this: enter image description here

Alternative versions

48 bytes:

Dynamic@Refresh[TimeObject[],UpdateInterval->.1]

53 bytes:

Dynamic@Refresh[DateString@"Time",UpdateInterval->.1]
share|improve this answer
1  
With it updating every second, did you ensure that it never skips seconds? (Ex: 11:11:11 -> 11:11:13) – redstarcoder yesterday
    
Dynamic@{DateString@TimeObject[], Clock[]}[[1]] – DavidC yesterday
1  
@redstarcoder it updates every ~1.002s, so I changed to updating every 100ms – JHM yesterday
    
Welp, I just realized I don't actually need Pause. – JHM yesterday

I see that the requirement for a non-signal UI input to stop the program has been removed. So now we can do:

Bash + coreutils, 28

yes now|date -f- +$'\e[2J'%T

yes continuously outputs the string "now", once per line, into a pipe.

date -f- reads interprets each "now" as the current time, then outputs in the required format. The format string includes the ANSI escape sequence to clear the screen. date does output a newline after the date - I'm not sure if this disqualifies, since the screen is cleared every time anyway.

If it disqualifies, then we can use tr instead:

Bash + coreutils, 31

yes now|date -f- +%T|tr \\n \\r

Previous Answers:

Bash + X, 32

xclock -d -update 1 -strftime %T

Unfortunately this can only update every second. If that disqualifies, then we can do this instead:

Bash + coreutils, 43

until read -t0
do printf `date +%T`\\r
done
share|improve this answer
    
Updating every second is fine, as long as it doesn't ever skip seconds (IE: 12-> 14). – redstarcoder yesterday
    
I'll allow your newline! I never expected this case to happen heh. – redstarcoder yesterday

MATL, 11 bytes

`XxZ'13XODT

Infinite loop that clears the screen and prints the time in the specified format.

You can try it at MATL Online!. This compiler is experimental; if it doesn't work refresh the page and press "Run" again.

share|improve this answer

C#, 82 bytes

()=>{for(;;)Console.Write(new string('\b',8)+DateTime.Now.ToString("HH:mm:ss"));};

Anonymous method which constantly overwrites 8 characters with new output. Can be made 1 byte shorter if modifying to accept a dummy parameter (z=>...).

Full program:

using System;

public class Program
{
    public static void Main()
    {
        Action a =
        () =>
        {
            for (;;)
                Console.Write(new string('\b', 8) + DateTime.Now.ToString("HH:mm:ss"));
        };

        a();
    }
}
share|improve this answer
1  
Is it allowed not to import System? Some people do it, and some people don't :/ – TuukkaX 13 hours ago
    
He didn't in his actual solution, just in the demo program, so yes, it is ok – Stefan 13 hours ago

Vim, 26 bytes

qqS<C-r>=strftime("%T")<CR><esc>@qq@q

This creates a recursive macro (e.g. an eternal loop) that deletes all the text on the current line and replaces it with the current time.

share|improve this answer

WinDbg, 73 bytes

.do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1

It continually updates a line with the current time until the user presses Ctrl+Break.

How it works:

.do                          * Start do-while loop
{
    r$t0 = 0;                * Set $t0 = 0
    .foreach(p {.echotime})  * Foreach space-delimited word in a sentence like "Debugger (not 
    {                        * debuggee) time: Mon Dec  5 14:08:10.138 2016 (UTC - 8:00)"
        r$t0 = @$t0+1;       * Increment $t0
        j 8==@$t0            * If $t0 is 8 (ie- p is the current time)
        '
            .printf"p \r"    * Print p (current time) and \r so the next print overwrites
        '
    }
} 1                          * Do-while condition: 1, loop forever

Sample output (well, you get the idea):

0:000> .do{r$t0=0;.foreach(p {.echotime}){r$t0=@$t0+1;j8==@$t0'.printf"p \r"'}}1
14:10:12.329
share|improve this answer

PHP, 28 bytes

for(;;)echo date("\rH:i:s");

The date function prints everything literally that it doesn´t recognize.

\r is the carriage return, sets the cursor to the first column.

Run with -r.

share|improve this answer

Pyth - 28 bytes

Kinda longish, because pyth has no strftime.

#p+"\r"j\:m.[`02`dP>4.d2.d.1
share|improve this answer

C, 134 116 89 80 bytes

Saved 9 more bytes thanks to @nmjcman101 again

n;main(){for(;;)n=time(0),printf("\r%02d:%02d:%02d",(n/3600)%24,(n/60)%60,n%60);}

Saved 27 bytes thanks to @nmjcman101

n,b[9];main(){for(;;){n=time(0);strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

Old versions:

#include<time.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}

I figured out I don't need to put #include<stdio.h> into the file :)

#include<time.h>
#include<stdio.h>
main(){for(;;){time_t n=time(0);char b[9];strftime(b,9,"%H:%M:%S",localtime(&n));printf("\r%s",b);}}
share|improve this answer
    
It looks like (for me) you can remove time.h as well. This removes the time_t type, so you need to make n an int instead. This can be done by declaring it outside of main (like n;main...), which removes the need for the int. You can also get rid of the char with the same trick: b[9];main.... They're both int type now, but it's flexible enough. – nmjcman101 14 hours ago
    
Wow, thanks a lot, I didn't know this would work. Thank you – Stefan 13 hours ago
    
Please stop me if you'd like to golf it yourself, but I also took out the strftime... and the b[9] and just made print into this: printf("\r%d:%d:%d",(n/3600)%60-29,(n/60)%60,n%60); I'm not sure if the parens are needed or not. Also you can take out a set of {} by putting commas between your statements so it's for(;;)a,b,c; – nmjcman101 13 hours ago
    
I'll just go try it, I've never golfed in C before so I don't know most of those tricks, thanks a lot :) – Stefan 13 hours ago
    
Could you please explain why you calculate hours that way ((n/3600)%60-29), the result is wrong for me but correct when I subtract 24 – Stefan 13 hours ago

Clojure, 150 136 141 bytes

V3: 141 bytes :(

+5 bytes to fix a bug. Since the times aren't zero padded, the clock can "shrink" and expand when the time changes. It was "smearing" when it shrunk because the last digit was no longer being cleared. Fixed it by adding some spaces at the end to ensure everything is being overwritten.

#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))"   "))(Thread/sleep 99))

V2: 136 bytes

#(while true(flush)(print(str(apply str(repeat 9"\b"))(.format(java.text.SimpleDateFormat."H:m:s")(java.util.Date.))))(Thread/sleep 99))

-14 bytes by switching to using SimpleDateFormat to format the date. Still huge.

V1: 150 bytes

#(while true(let[d(java.util.Date.)](flush)(print(str(apply str(repeat 9 "\b"))(.getHours d)":"(.getMinutes d)":"(.getSeconds d)))(Thread/sleep 100)))

I realized I'm probably using the worst way possible to get the date. Definitely room for improvement here.

Ungolfed:

(defn -main []
  (while true
    (let [d (java.util.Date.)]
      (flush)
      (print
        (str
          (apply str (repeat 9 "\b"))
          (.getHours d)":"(.getMinutes d)":"(.getSeconds d)))
      (Thread/sleep 100))))
share|improve this answer

Batch, 36 bytes

@set/p.=␈␈␈␈␈␈␈␈%time:~0,8%<nul
@%0

Where represents the ASCII BS character (code 8).

share|improve this answer

Racket, 71 bytes

(require srfi/19)(let l()(display(date->string(current-date)"↵~3"))(l))

Where the is actually a CR (hex 0d). Hex dump of the program for further clarification (notice byte at position hex 4d):

00000000  28 72 65 71 75 69 72 65  20 73 72 66 69 2f 31 39  |(require srfi/19|
00000010  29 28 6c 65 74 20 6c 28  29 28 64 69 73 70 6c 61  |)(let l()(displa|
00000020  79 28 64 61 74 65 2d 3e  73 74 72 69 6e 67 28 63  |y(date->string(c|
00000030  75 72 72 65 6e 74 2d 64  61 74 65 29 22 0d 7e 33  |urrent-date)".~3|
00000040  22 29 29 28 6c 29 29                              |"))(l))|
00000047

Uses SRFI/19 included with the Racket distribution. (current-date) gets the current local date & time. The date->string format ~3 is ISO-8601 hour-minute-second format. (let l () ... (l)) in an idiomatic infinite loop. (require srfi/19) loads the srfi/19 module.

share|improve this answer

C, 156 bytes

#include<stdio.h>
#include<time.h>
int main(){time_t a;struct tm *b;char c[9];for(;;){time(&a);b=localtime(&a);strftime(c,9,"%H:%M:%S",b);printf("%s\r",c);}}
share|improve this answer

C#, 65 bytes

()=>{for(;;)Console.Write("\r"+DateTime.Now.ToLongTimeString());};

Works by overwriting the same line within an endless loop

share|improve this answer

*><> (Starfish), 22 bytes

d"   ::"s@hm@nononoooo

Ungolfed

>s":"m":"hnonon"   "ooo1S\
\                 ;?+1iod/

Explanation

First, we build the initial stack with d" ::"s, giving us ["\r", " ", ":", ":", seconds], building the stack this way saves two bytes by removing 4 ", and adding two @. It's important to know what the @ instruction does here, it simply changes the end of the stack in such a way so [1,2,3,4] @ [1,4,2,3]. So we run @ giving us a stack of ["\r", " ", seconds, ":", ":"]. Then we run hm@, which adds the hours, then the minutes to the end of the stack and executes @, giving us ["\r", " ", seconds, ":", ":", hours, minutes] @ ["\r", " ", seconds, ":", minutes, ":", hours]. In nononoooo, n outputs a number from the end of the stack, o outputs a byte.

Then the ><> simply loops back around to the beginning!

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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