19
\$\begingroup\$

I honestly cannot believe that this is not a question yet on Code Golf, but....

Print the local time (with a.m. or p.m.) as a string to the console, preceded by "It's ".

Example:

Run code....

Output:

It's 12:32p.m.

Shortest code wins.

Code away!

Leaderboard

var QUESTION_ID=57552,OVERRIDE_USER=42854;function answersUrl(e){return"http://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"http://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>

\$\endgroup\$
15
  • 1
    \$\begingroup\$ What is the output format? Does it matter? \$\endgroup\$
    – mbomb007
    Commented Sep 10, 2015 at 21:30
  • 1
    \$\begingroup\$ No, I mean, should it be yyyy-MM-dd hh:mm:ss UTC or does that date format not matter? \$\endgroup\$
    – mbomb007
    Commented Sep 10, 2015 at 21:34
  • 8
    \$\begingroup\$ I really wanted to put up an answer that prints It's beer o'clock, but I resisted. \$\endgroup\$
    – MickyT
    Commented Sep 11, 2015 at 2:18
  • 4
    \$\begingroup\$ Can we use 12:32 PM or 12:32PM? Instead of 12:32p.m.? \$\endgroup\$ Commented Sep 11, 2015 at 12:33
  • 3
    \$\begingroup\$ Is it 02:32 or 2:32 if it's less than 10:00? \$\endgroup\$ Commented Sep 11, 2015 at 12:38

50 Answers 50

1
2
1
\$\begingroup\$

Excel VBA, 33 bytes

?"It's "format(now,"h:ma/p")".m."

Related to toothbrush's VBA6 solution, but written before I saw it, so I'm allowing myself to post it here.

Most of the code is perfectly explicit: now returns a system timestamp, format forces the timestamp to the desired format, whilst It's and .m. are just text strings.

I abused/took advantage of a few things here:

  • Implicit concatenation : VBA assumes that when something is put next to a string that a concatenation operation is desired.

  • Immediate window printing : This is why I don't claim this is a complete VBA solution, as it relies on being executed from inside an immediate window. The ? replaces debug.print for Excel VBA in an immediate window. This is an obvious gain for VBA where most of the byte cost comes from descriptive/user-friendly function and method names. Toothbrush's solution for example calls Msgbox which is 5 bytes more expensive.

  • Format abuse : based on Dopapp's comments in this puzzle, we don't need to have double-digit hours. I'm also not forcing double-digit minutes, which might be slightly against the rules of the game, but can easily be corrected by adding an extra m between : and m, but costs 1 byte more.

I might have missed some other tricks, but I think this is about as low as Excel VBA can go. From what I can see so far, I'm pretty surprised that it's scoring so well, but a lot of the very concise languages haven't been used yet...

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

x86-16 machine code, IBM PC DOS, 64 62 bytes

Binary:

00000000: bf34 01b4 2ccd 218a c5d4 0c75 02b0 0ce8  .4..,.!....u....
00000010: 1400 478a c1e8 0e00 b870 0980 fd0c 7c01  ..G......p....|.
00000020: aaba 2f01 cd21 d40a 86c4 0530 30ab c349  ../..!.....00..I
00000030: 7427 7320 3030 3a30 3061 2e6d 2e24       t's 00:00a.m.$

Build and test using xxd -r with above.

Listing:

BF 0134     MOV  DI, OFFSET HH      ; DI point to hours in output string
B4 2C       MOV  AH, 2CH            ; DOS get time function 
CD 21       INT  21H                ; CH = hour, CL = minute 
8A C5       MOV  AL, CH             ; put hour into AL 
D4 0C       AAM  12                 ; AL = AL mod 12, ZF = (AL == 0) 
75 02       JNZ  NOT_12             ; is hour 0? 
B0 0C       MOV  AL, 12             ; if so, make it 12 
        NOT_12: 
E8 0126     CALL ACONV              ; ASCII convert AL to [DI] 
47          INC  DI                 ; skip ':' in output string 
8A C1       MOV  AL, CL             ; put minutes into AL 
E8 0126     CALL ACONV              ; ASCII convert AL to [DI]
B8 0970     MOV  AX, 0970H          ; AL = 'p', AH = 9 (DOS write string)
80 FD 0C    CMP  CH, 12             ; set up compare for 12 
7C 01       JL   OUTPUT             ; is hours > 11?
AA          STOSB                   ; if so, write 'p' to output string 
        OUTPUT: 
BA 012F     MOV  DX, OFFSET IT      ; beginning of output string 
CD 21       INT  21H                ; display output 
        ACONV: 
D4 0A       AAM                     ; BCD base 10 convert
86 C4       XCHG AL, AH             ; endian convert
05 3030     ADD  AX, '00'           ; ASCII convert 
AB          STOSW                   ; write to output string buffer 
C3          RET                     ; return to caller/DOS

        IT  DB  'It',27H,'s '
        HH  DB  '00:'
        MM  DB  '00'
        AP  DB  'a.m.$'

I had imagined this being shorter in my head when I started it, but alas. No date "built-ins" at least!

Standalone PC DOS executable TIMECHAP.COM file. Output to STDOUT.

enter image description here

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

APL (Dyalog Extended), 58 bytes

-6 thanks to @ovs

⎕←∊'It is '(⍕h-12×12<h)':'(⍕5⌷⎕ts),'ap'[1+12<h←4⌷⎕ts]'.m.'

Try it online!

Original:

∊'It is '((':',⍕5⌷⎕ts){⍵>12:∊(⍕(⍵-12))⍺'p'⋄∊(⍕⍵)⍺'a'}4⌷⎕ts)'.m.'

Try it online!

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 58 bytes as a full program without any dfns \$\endgroup\$
    – ovs
    Commented Dec 20, 2020 at 19:06
1
\$\begingroup\$

05AB1E, 39 37 bytes

"It's "ža<12%>žb‚T‰J':ý„apža13@è….m.J

-2 bytes thanks to @ovs.

Try it online.

Explanation:

"It's "     # Push string "It's "
ža          # Push the current hours (24 format)
  <         # Decrease it by 1
   12%      # Modulo-12: (hours-1)%12
      >     # Increase it by 1: (hours-1)%12+1
            # (so if the hours was 0, it's now 12; the [1,11] remained the same)
žb‚         # Pair this with the current minutes
   T‰       # Get the divmod-10 of each
     J      # And join the two digits together to a single string
            # (`T‰J` is used to format the hours/minutes with a potential leading 0)
      ':ý  '# Join them together with ":" delimiter
„ap         # Push string "ap"
   ža       # Push the current hours again (24 format)
     13@    # Check if it's >= 13 (1 if truthy; 0 if falsey)
        è   # (0-based) index that into the "ap"
….m.        # Push string ".m."
J           # Join all strings on the stack together
            # (after which the result is output implicitly)
\$\endgroup\$
3
  • 1
    \$\begingroup\$ I'd never noticed before but TIO seems to cache the output in the link too, since when I clicked on your link the time was wrong until I re-ran. Guess that makes sense because for most cases the output only changes with a code change. Learn something new everyday. \$\endgroup\$
    – 640KB
    Commented Jul 2, 2020 at 14:14
  • 1
    \$\begingroup\$ @640KB Yep. It's actually pretty useful for programs that run let's say 40 seconds. When someone else visits the same link, they don't have to wait 40 seconds to see the result if someone else has already run it prior. :) \$\endgroup\$ Commented Jul 2, 2020 at 14:40
  • 1
    \$\begingroup\$ 37 bytes by using (hours-1)%12+1 for calculating 12-hour hours. \$\endgroup\$
    – ovs
    Commented Dec 20, 2020 at 19:22
0
\$\begingroup\$

Windows Batch, 113 bytes

@set h=%time:~0,2%&@set z=a&@if %h% gtr 11 set z=p&if %h% gtr 12 set /a h-=12
echo It's %h: =0%:%time:~3,2%%z%.m.
\$\endgroup\$
0
\$\begingroup\$

BASH, 50 bytes

date +"It's %I:%M%p"|sed s/AM/a.m./|sed s/PM/p.m./

Just date and two easy seds.

\$\endgroup\$
0
\$\begingroup\$

Octave, 75 bytes

disp(["It's " strrep(lower(strftime("%R%p",localtime(time()))),"m",".m.")])
\$\endgroup\$
3
  • \$\begingroup\$ This shoiws: ans = .... A lot of MATLAB / Octave answers could be a lot shorter if that was legal. \$\endgroup\$ Commented Sep 11, 2015 at 12:46
  • \$\begingroup\$ @StewieGriffin Yes, that's true... \$\endgroup\$
    – Tarod
    Commented Sep 11, 2015 at 12:54
  • \$\begingroup\$ @AlexA. Of course. Thanks! :) \$\endgroup\$
    – Tarod
    Commented Sep 11, 2015 at 23:17
0
\$\begingroup\$

Java, 182 bytes

These solutions are horrendously long. =(

Note: These print in local time, and suppresses leading zeros for the hour. java.util.Date has deprecated API.

// 183 bytes when linebreaks and indentation are removed
import java.util.Date;
class T{
  public static void main(String[]a){
    Date d=new Date();
    int h=d.getHours();
    System.out.printf("It's %d:%02d%c.m.%n",
      (h+11)%12+1,d.getMinutes(),97+h/12*15);
  }
}

Alternate solution:

// 182 bytes when linebreaks and indentation are removed
class T{
  public static void main(String[]a){
    System.out.println("It's "+new java.text.SimpleDateFormat("h:mma").format(
      new java.util.Date()).toLowerCase().replaceAll("[apm]","$0."));
  }
}
\$\endgroup\$
0
\$\begingroup\$

Perl, 88 75 bytes

use POSIX;$d=lc strftime"%R%p",localtime;$d=~s/m/.m./;printf("It's %s",$d);
\$\endgroup\$
2
  • \$\begingroup\$ POSIX automatically exports everything, so you can shave off 13 bytes by dropping the qw(strftime). \$\endgroup\$ Commented Sep 12, 2015 at 3:53
  • \$\begingroup\$ @ThisSuitIsBlackNot Thank you! :D \$\endgroup\$
    – Tarod
    Commented Sep 13, 2015 at 0:53
0
\$\begingroup\$

C# - 160 bytes

using System;class C{static void Main(string[] a){var n=DateTime.Now;int h=n.Hour,m=n.Minute;Console.Write("It's "+(h<13?h:h-12)+":"+m+(h<12?"a":"p")+".m.");}}
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 95 bytes

x=(new Date+"").substr(16,5).split(':')
alert(`It's ${x[0]%12||12}:`+x[1]+(x[0]<12?'a':'p')+'.m.')
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 88

Edit Missing "It's"
Edit 2 Fixed 0 instead of 12
Edit 3 Added an output statement. I was trying to be in line with other JavaScript answers that I felt ugly, but rules are rules

Test in any EcmaScript 6 compliant browser console (works in Chrome and Firefox).

alert(`It's ${1+((h=(d=new Date).getHours())+11)%12}:${d.getMinutes()+'ap'[h>11|0]}.m.`)

// With no ES6 features : 92

alert("It's "+(1+((h=(d=new Date).getHours())+11)%12)+':'+d.getMinutes()+'ap'[h>11|0]+'.m.')
\$\endgroup\$
8
  • \$\begingroup\$ This doesn't output leading 0:s if any number is below 10. F.e It's 0:9a.m. \$\endgroup\$
    – Jan
    Commented Sep 11, 2015 at 22:10
  • \$\begingroup\$ @Jan indeed. That's not requested: see answer to @StewieGriffin's question: You must use p.m or a.m. For your second comment: it doesn't matter. Whichever you want \$\endgroup\$
    – edc65
    Commented Sep 11, 2015 at 23:48
  • \$\begingroup\$ Talking about hours, yes. Regarding minutes, looking at another reply It should be like 11:00p.m. not 23p.m. I'd very much suspect it's required, but you could ask. Also noted another thing: It's 12:32p.m., so not 0:32p.m. \$\endgroup\$
    – Jan
    Commented Sep 11, 2015 at 23:51
  • \$\begingroup\$ My first comment was from the console output of running your script. \$\endgroup\$
    – Jan
    Commented Sep 12, 2015 at 0:00
  • \$\begingroup\$ @Jan Right. It's broken. Fixing it \$\endgroup\$
    – edc65
    Commented Sep 12, 2015 at 0:03
0
\$\begingroup\$

TI-BASIC, 58 bytes

getTimeStr(12
"It's "+sub(Ans,1,length(Ans)-2)+sub("ap",2-not(inString(Ans,"P")),1)+".m.

An ugly hack to build the correct output from the built-in getTimeStr(, which gives something like "8:59 PM". (By the way, the 12 means "12-hour format".)

\$\endgroup\$
0
0
\$\begingroup\$

PowerShell, 61 bytes

"It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m."

My very first PowerShell experiecne // because my linux machine is in the other room.

EDITED to be culture-settings robust. Thanks to all commenters below, credit goes to @NeilD

\$\endgroup\$
6
  • 1
    \$\begingroup\$ This also depense on system setting. I don't get am or pm. (24:00 format) \$\endgroup\$
    – dwana
    Commented Sep 11, 2015 at 11:00
  • \$\begingroup\$ Ouch. Ok I will fix it. \$\endgroup\$
    – Jacob
    Commented Sep 11, 2015 at 11:19
  • \$\begingroup\$ @TimmyD Format string t is culture-dependent and may return other characters than a or p, or an empty string for cultures that do not use am/pm designators. \$\endgroup\$ Commented Sep 11, 2015 at 13:28
  • \$\begingroup\$ @DankoDurbić Indeed you're correct. Mea culpa. \$\endgroup\$ Commented Sep 11, 2015 at 13:47
  • \$\begingroup\$ "It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m." works for me (62 bytes) \$\endgroup\$
    – NeilD
    Commented Sep 11, 2015 at 14:09
0
\$\begingroup\$

CJam, 60 58 bytes

"It's "3et=Cmd\'p'a?".m."+\_0>{}{;C}?\":"\4et=_A<{0\@}{\}?

Explanation

"It's "                                                         e# Print the string "It's ".
        et                                                      e# Push the local time to the stack.
       3  =                                                     e# Select the third item. (hours)
           C                                                    e# Push 12 to the stack.
            md                                                  e# Push the top stack item modulo the second stack item.
              \                                                 e# Swap the top two stack items.
               'p'a?                                            e# Push "p" or "a" to the stack.
                    ".m."+                                      e# Tack on ".m." to the above.
                          \                                     e# Swap the top two stack items.
                           _                                    e# Duplicate the top stack item.
                            0>                                  e# Determine if the top item is > 0.
                              {}{  }                            e# An if-then statement.
                                    ?                           e# If the top stack item is true.
                                 ;                              e# Remove the top stack item.
                                  C                             e# Push 12 to the stack.
                                     \                          e# Swap the top two stack items.
                                      ":"                       e# Push ":" to the stack.
                                         4  =                   e# Select the fourth item. (minutes)
                                          et                    e# Push the local time to the stack.
                                             _                  e# Duplicate the top stack item.
                                              A<                e# Determine if the top item is < 10.
                                                {   }{ }        e# An if-then statement.
                                                        ?       e# If the top stack item is true.
                                                 0              e# Push 0 to the stack.
                                                  \             e# Swap the top two stack items.
                                                   @            e# Rotate the top three stack items.
                                                      \         e# Swap the top two stack items.

You can test it online, here.

\$\endgroup\$
0
\$\begingroup\$

Hassium, 125 Bytes

func main(){print("It's "+date().hour%12+":"+date().minute);if(date().hour%12!=date().hour)print("p.m.");else print("a.m.");}

Run it (and for expanded) here

\$\endgroup\$
0
\$\begingroup\$

Octave 54 bytes

5 bytes shorter than the shortest MATLAB submission and 21 bytes shorter than the shortest Octave submission. Uses Octave's "index everywhere" functionality.

disp(['It''s ',lower(datestr(now,16))([1:5,7]),'.m.'])
It's 12:34p.m.
\$\endgroup\$
0
\$\begingroup\$

Bash, 32 bytes

printf "%(It's %H:%M:%S%P^H.m.)T"

Where ^H is a literal backspace character. Here's a hex dump (use xxd -r to reverse it):

0000000: 7072 696e 7466 2022 2528 4974 2773 2025  printf "%(It's %
0000010: 483a 254d 3a25 5325 5008 2e6d 2e29 5422  H:%M:%S%P..m.)T"
\$\endgroup\$
0
0
\$\begingroup\$

Thunno 2 j, 36 bytes

ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's 

Try it online!

Explanation

ʋ.m.`apkL12®ikKkL⁻12%⁺,TȷḋẸ':s"It's    # Full program

                              "It's   "# Step 1 (get the prefix string):
                              "It's   "#  Push the string "It's "

             kKkL⁻12%⁺,TȷḋẸ':s        '# Step 2 (get the time):
               kL                      #  Push the current hours (24-hour format)
                 ⁻                     #  Decrement it
                  12%                  #  Modulo by 12
                     ⁺                 #  Increment it
             kK       ,                #  Pair with the current minutes
                        ȷ              #  And to each one:
                       T ḋ             #   Divmod it by 10
                          Ẹ            #  Dump both onto the stack
                           ':s        '#  Push a ":" between the two pairs

ʋ.m.`apkL12®i                          # Step 3 (get the suffix string):
       kL                              #  Push the current hours again
         12®                           #  Check if it's >= 12
    `ap     i                          #  Index this into the string "ap"
ʋ.m.                                   #  Push the string ".m."

                                       # Join the stack into a string, joining
                                       # lists on the stack implicitly as well

                                       # Implicit output
\$\endgroup\$
0
\$\begingroup\$

Pascal, 83 B (subject to implementation characteristics)

Extended Pascal, ISO standard 10206, furnishes Pascal with some time-related routines and a data type timeStamp. However, the specific behavior of getTimeStamp, whether it populates a timeStamp with the ”local time“, UTC, wall time or else, is implementation-defined. Similarly the format time returns is implementation-defined, too. For instance, it could depend on the value of the LC_TIME environment variable if the implementation says so. It is therefore not guaranteed that the following implementation meets all task specification requirements in all ISO-compliant Pascal implementations.

program t(output);var t:timeStamp;begin getTimeStamp(t);write('It''s ',time(t))end.

Note, it is not checked that t.timeValid is true but in a real-life application it is advisable.

\$\endgroup\$
1
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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