18
\$\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\$
  • 1
    \$\begingroup\$ What is the output format? Does it matter? \$\endgroup\$ – mbomb007 Sep 10 '15 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 Sep 10 '15 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 Sep 11 '15 at 2:18
  • 4
    \$\begingroup\$ Can we use 12:32 PM or 12:32PM? Instead of 12:32p.m.? \$\endgroup\$ – Stewie Griffin Sep 11 '15 at 12:33
  • 3
    \$\begingroup\$ Is it 02:32 or 2:32 if it's less than 10:00? \$\endgroup\$ – Stewie Griffin Sep 11 '15 at 12:38

46 Answers 46

1
\$\begingroup\$

AutoIt, 73 bytes

Even though AutoIt is generally a verbose language, this is quite short (converts time from 24h format):

$h=@HOUR>12
ConsoleWrite("It's "&@HOUR-12*$h&":"&@MIN&($h?"p":"a")&".m.")

ß, 56 bytes

H=@HOUR>12µ€"It's "&@HOUR-12*H&":"&@MIN&H?"p.m.":"a.m.")
\$\endgroup\$
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\$
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\$
  • \$\begingroup\$ This shoiws: ans = .... A lot of MATLAB / Octave answers could be a lot shorter if that was legal. \$\endgroup\$ – Stewie Griffin Sep 11 '15 at 12:46
  • \$\begingroup\$ @StewieGriffin Yes, that's true... \$\endgroup\$ – Tarod Sep 11 '15 at 12:54
  • \$\begingroup\$ @AlexA. Of course. Thanks! :) \$\endgroup\$ – Tarod Sep 11 '15 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\$
  • \$\begingroup\$ POSIX automatically exports everything, so you can shave off 13 bytes by dropping the qw(strftime). \$\endgroup\$ – ThisSuitIsBlackNot Sep 12 '15 at 3:53
  • \$\begingroup\$ @ThisSuitIsBlackNot Thank you! :D \$\endgroup\$ – Tarod Sep 13 '15 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\$
  • \$\begingroup\$ This doesn't output leading 0:s if any number is below 10. F.e It's 0:9a.m. \$\endgroup\$ – Jan Sep 11 '15 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 Sep 11 '15 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 Sep 11 '15 at 23:51
  • \$\begingroup\$ My first comment was from the console output of running your script. \$\endgroup\$ – Jan Sep 12 '15 at 0:00
  • \$\begingroup\$ @Jan Right. It's broken. Fixing it \$\endgroup\$ – edc65 Sep 12 '15 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
\$\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\$
  • 1
    \$\begingroup\$ This also depense on system setting. I don't get am or pm. (24:00 format) \$\endgroup\$ – dwana Sep 11 '15 at 11:00
  • \$\begingroup\$ Ouch. Ok I will fix it. \$\endgroup\$ – Jacob Sep 11 '15 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\$ – Danko Durbić Sep 11 '15 at 13:28
  • \$\begingroup\$ @DankoDurbić Indeed you're correct. Mea culpa. \$\endgroup\$ – AdmBorkBork Sep 11 '15 at 13:47
  • \$\begingroup\$ "It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m." works for me (62 bytes) \$\endgroup\$ – NeilD Sep 11 '15 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\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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