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

17
\$\begingroup\$

Bash, 39 33 bytes

date "+It's %I:%M%P."|sed s/m/.m/

Wasted a bunch of chars because the spec requires a.m. or p.m. while date outputs am or pm. Thanks to @DigitalTrauma for saving 6 bytes!

This might not be very portable. It works on Ubuntu 15.04.

A solution that uses essentially the same method in Ruby, which is surprisingly the exact same length:

Ruby, 39 bytes

$><<`date "+It's %I:%M%P"`[0..-3]+'.m.'
\$\endgroup\$
9
  • \$\begingroup\$ %P gives me uppercase AM or PM. I'm on a mac if it makes a difference. \$\endgroup\$
    – flodel
    Commented Sep 10, 2015 at 23:35
  • \$\begingroup\$ @flodel Works On My Machine™. On Ubuntu 15.04, %P gives lowercase, and %p gives uppercase (which is a bit... unintuitive). \$\endgroup\$
    – Doorknob
    Commented Sep 10, 2015 at 23:37
  • \$\begingroup\$ GNU date (on Linux et al.) and *BSD date (where OSX is one BSD variant) have wildly different options and behaviors when you venture outside of the feature set specified by POSIX. So perhaps this answer should specifically mention Bash on Linux. (That goes for sed too; but this particular invocation is firmly within the safe and portable feature set.) \$\endgroup\$
    – tripleee
    Commented Sep 11, 2015 at 4:52
  • \$\begingroup\$ On my machine (zsh or bash on Linux) it prints "It's 04:17." when the time is 16:17. No "a.m." or "p.m." \$\endgroup\$ Commented Sep 11, 2015 at 8:18
  • \$\begingroup\$ echo -e "It's $(date +%I:%M%P)\b.m." - instead of sed uses backspace. Doesn't look like a separate answer to me. Also I don't have any am/pm but I think it's because of locale. \$\endgroup\$
    – aragaer
    Commented Sep 11, 2015 at 11:22
12
\$\begingroup\$

AppleScript, 198

Because AppleScript. Because why not:

set AppleScript's text item delimiters to {":"," "}
set d to (current date)'s time string's every text item
"It's "&d's item 1&":"&d's item 2&string id ((d's item 4's first character's id)+32)&".m."

That was painful.

\$\endgroup\$
1
  • 19
    \$\begingroup\$ AppleScript is the new Java. \$\endgroup\$
    – Doorknob
    Commented Sep 11, 2015 at 10:57
8
\$\begingroup\$

PHP, 35 33 bytes

Using the wrong tool for the job!

It's <?=trim(date('h:ia'),m)?>.m.

It simply removes the m at the end of am or pm, to allow to add the dots. The date comes as 00:00am, and with trim it becomes 00:00a.


Old answer (PHP 5.4+ only):

It's <?=date('h:i'),date(a)[0]?>.m.

This works because you can de-reference a value returned from a function. This isn't possible in PHP5.3 or older.

\$\endgroup\$
4
  • \$\begingroup\$ Ah, clever! You beat my php answer \$\endgroup\$
    – DankMemes
    Commented Sep 11, 2015 at 11:06
  • \$\begingroup\$ @DankMemes It took me quite a while. And lots of experimenting. \$\endgroup\$ Commented Sep 11, 2015 at 11:07
  • \$\begingroup\$ You used a string literal without quotes. Is it OK to use those without the @ operator and assume people will run it with error_reporting(0)? \$\endgroup\$
    – DankMemes
    Commented Sep 11, 2015 at 12:45
  • \$\begingroup\$ @DankMemes You can indirectly assume that error reporting is disabled. Here's a good read: meta.codegolf.stackexchange.com/a/1655/14732 \$\endgroup\$ Commented Sep 11, 2015 at 13:17
5
\$\begingroup\$

Visual Basic 6 / VBA, 42 41 bytes

MsgBox"It's "&Format(Now,"h:mma/p")&".m."

Using MsgBox, as VB6 does not have a console (unless you intercept the linking, link as a console executable, use some Windows API hacks, and do some other dodgy stuff).

\$\endgroup\$
2
  • 3
    \$\begingroup\$ Why don't you just replace m by .m.? i.e. Debug.Print Replace(Format(Now,"hh:mm am/pm"),"m",".m.") \$\endgroup\$
    – CompuChip
    Commented Sep 11, 2015 at 7:41
  • \$\begingroup\$ Nice @toothbrush, I sort of expected this to be a one-byte solution in CJam ;) \$\endgroup\$
    – CompuChip
    Commented Sep 12, 2015 at 11:55
4
\$\begingroup\$

R, 68 ,59 62 60 55

cat("It's",sub("m",".m",format(Sys.time(),"%I:%M%P.")))

(Thanks to @Alex.A. and @flodel for the comments) Takes the current system time (Sys.time()), formats it correctly using %I:%M%P combination, adds a dot at the end, and replaces the m with .m..

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

Julia, 74 54 43 bytes

print(strftime("It's %I:%M%P\b.m.",time()))

You can try it online!

The time() function returns the current time. When passed to strftime with the format %I:%M%P, this results in HH:MMam/pm, where the hours are per a 12-hour clock. We back up one character with \b to remove the m, leaving a trailing a or p, then tack .m. onto the end.

Saved 31 bytes thanks to Glen O!

\$\endgroup\$
6
  • \$\begingroup\$ Might I suggest this? print("It's ",strftime("%r%P",time())[[1:5,12]],".m.") - uses %P to add the lowercase am/pm, to avoid the comparison and the split command. \$\endgroup\$
    – Glen O
    Commented Sep 11, 2015 at 2:46
  • \$\begingroup\$ No problems regarding the help. And don't talk yourself down - you do fine. I just get enjoyment out of trying to squeeze every last byte out of the code. In this case, I just figured that trying to bypass the split command and the conditional statement would be beneficial, and then went looking at the functions you used. I probably wouldn't have found strftime myself (I'd have tried to extract the time directly from time()) \$\endgroup\$
    – Glen O
    Commented Sep 11, 2015 at 5:14
  • 1
    \$\begingroup\$ @GlenO If you get enjoyment out of squeezing every last byte out of code, PPCG is certainly the right place for you! \$\endgroup\$
    – Alex A.
    Commented Sep 11, 2015 at 5:26
  • \$\begingroup\$ Incidentally, I've found a way to squeeze a few more bytes out: print(strftime("It's %I:%M%P",time())[1:11],".m.") \$\endgroup\$
    – Glen O
    Commented Sep 11, 2015 at 6:29
  • \$\begingroup\$ Actually, even better: print(strftime("It's %I:%M%P\b.m.",time())) \$\endgroup\$
    – Glen O
    Commented Sep 11, 2015 at 7:26
3
\$\begingroup\$

Haskell, 135 bytes

import Data.Time.Format
import Data.Time.LocalTime
main=getZonedTime>>=putStr.(++".m.").init.formatTime defaultTimeLocale"It's %I:%M%P"

I found a much more amusing main that's five bytes longer:

getZonedTime>>=putStr.formatTime(TimeLocale[][]("a","p")""""""""[])"It's %I:%M%P.m."

Or 66 bytes on Unix:

import System.Cmd;main=system"date \"+It's %I:%M%P.\"|sed s/m/.m/"
\$\endgroup\$
3
\$\begingroup\$

Pyth, 38 36 bytes

s["It's "|%J.d6K12K\:.d7?gJK\p\a".m.

Saved 2 bytes thanks to @Jakube!

\$\endgroup\$
4
  • \$\begingroup\$ @Sp3000 On the online interpreter or locally? \$\endgroup\$ Commented Sep 11, 2015 at 0:17
  • \$\begingroup\$ @Sp3000 I think I know the issue. It's giving the time of the location of the Pyth server, and I'm not handling midnight correctly. Hold on... \$\endgroup\$ Commented Sep 11, 2015 at 0:39
  • \$\begingroup\$ @Sp3000 Fixed!!! \$\endgroup\$ Commented Sep 11, 2015 at 0:45
  • \$\begingroup\$ You're almost beating my PHP answer and Doorknob's Bash answer! \$\endgroup\$ Commented Sep 11, 2015 at 16:56
3
\$\begingroup\$

MATLAB, 59 bytes

disp(sprintf('It''s%s\b.m.',lower(datestr(now,'HH:MMam'))))

It's 5:38p.m.

If it's allowed to have a whitespace between time and a.m./p.m., then it could be as low as 52 bytes:

disp(sprintf('It''s%s\b.m.',lower(datestr(now,16))))

It's 5:39 p.m.

\$\endgroup\$
4
  • \$\begingroup\$ I think the output must be 05:38p.m. \$\endgroup\$ Commented Sep 12, 2015 at 16:14
  • \$\begingroup\$ According to OP's comment, the leading zero doesn't matter. \$\endgroup\$
    – slvrbld
    Commented Sep 12, 2015 at 16:52
  • \$\begingroup\$ You're right. Here, have my upvote! \$\endgroup\$ Commented Sep 12, 2015 at 16:58
  • \$\begingroup\$ Nice! Didn't know I could use \b like that... You need an extra space btw. \$\endgroup\$ Commented Sep 16, 2015 at 16:10
3
\$\begingroup\$

Perl 5.10+, 58 62 bytes

localtime=~/(..)(:..)/;say"It's ",$1%12||12,$2,$1>11?p:a,".m."

Must be run with the -M5.010 command line flag to get say.

I didn't account for a couple of edge cases in my original solution (namely, 00:** and 12:**); fixed at a cost of 4 additional bytes.

How it works

In scalar context, localtime returns a string like this:

Sat Sep 12 03:13:22 2015

The minutes field is already zero-padded, which saves some bytes (in list context, localtime returns numbers instead of strings, so you have to pad them yourself).

Here it is ungolfed:

localtime=~/(..)(:..)/;  # Store hour in $1 and minutes in $2
say"It's ",              # Print "It's " followed by...
   $1%12||12,            # hour in 12-hour format
   $2,                   # minutes
   $1>11?p:a,            # "p" if hour > 11, otherwise "a"
   ".m."'                # ".m."

Perl 5.14+, 57 bytes

(Just for fun, since it stretches the rules a bit.)

say"It's ",(strftime"%l:%M%P",localtime)=~s/m/.m./r

51 bytes + 6 bytes for -MPOSIX. Must also be run with the -M5.010 command line flag to get say.

This solution is dependent on your locale, so will not work on all systems. It also uses the POSIX module, which might be stretching the definition of a "built-in", even though it is a core module.

Perl 5.14+ is required for the non-destructive r modifier to the substitution operator. An equivalent solution that works on 5.10+ is:

$_=strftime"%l:%M%P",localtime;chop;say"It's $_.m."

This is also 57 bytes (51 bytes + 6 bytes for -MPOSIX).

\$\endgroup\$
3
\$\begingroup\$

Perl 5, 74 bytes

A small showcase of how the variables are evaluated from right to left.

($s,$m,$h)=localtime;printf"It's %d:%02d%s.m.",$h<13?$h:$h%12,$m,$h<12?a:p

Using POSIX: 80 bytes

use POSIX;$_=strftime"It's %I:%Mx.m.",@_=localtime;$x=$_[1]<13?a:p;s/x/$x/;print

Using POSIX with time locale dependence & switches : 54 bytes (48 + 6)

$_=strftime"It's %I:%M%P",localtime;s/m/.m./;say

Test

$ export LC_TIME="en_DK.UTF-8"
$ perl -MPOSIX -M5.01 whatsthetimechap.pl
It's 3:09p.m.
\$\endgroup\$
4
  • 1
    \$\begingroup\$ You can save some bytes on your POSIX solutions by using -MPOSIX instead of use POSIX;, dropping the parens in your call to strftime, and replacing print with say (-M5.010 is free). Which brings your last solution down to 54 bytes! \$\endgroup\$ Commented Sep 12, 2015 at 15:05
  • \$\begingroup\$ Thanks. I used your advice for the shortest POSIX solution. \$\endgroup\$
    – LukStorms
    Commented Sep 12, 2015 at 17:46
  • 1
    \$\begingroup\$ You still have to count -MPOSIX (6 bytes), but you can save 2 bytes by dropping the parentheses: $_=strftime"It's %I:%M%P",localtime;. That gives 54 bytes total, which is still better than my 57-byte POSIX solution. Well done! \$\endgroup\$ Commented Sep 12, 2015 at 19:52
  • \$\begingroup\$ Heh, thanks again for rescuing a few bytes. \$\endgroup\$
    – LukStorms
    Commented Sep 12, 2015 at 21:39
3
\$\begingroup\$

CJam, 40 bytes

"It's "et3=CmdCe|\'p'a?':et4=s2Ue[@".m."

Try it online in the CJam interpreter.

How it works

"It's " e# Push that string.
et3=    e# Select the fourth element of the date/time array (hours).
Cmd     e# Push quotient and remainder of the hour divided by 12.
Ce|     e# Logical OR with 12 to map 0 to 12.
\'p'a?  e# Select 'p' if the quotient is 1 and 'a' if it is 0.
':      e# Push that character.
et4=    e# Select the fifth element of the date/time array (minutes).
s2Ue[   e# Cast to string and left-pad with zeroes to a length of 2.
@".m."  e# Rotate 'a' or 'p' on top of the stack and push ".m.".
\$\endgroup\$
3
\$\begingroup\$

Mathematica 49 90 92 90 84 bytes

-6 bytes thanks to user202729

The solution is straightforward, but a bit wordy, in Mathematica.

(d=DateString)@{"It's ","Hour12",":","Minute"}<>(d@"AMPM"/."AM"->"a.m."/."PM"->"p.m‌ .")
\$\endgroup\$
1
  • \$\begingroup\$ (Although this post is quite old) StringReplace can be eliminated, save 6 bytes. (d=DateString)@{"It's ","Hour12",":","Minute"}<>d@"AMPM"/."AM"->"a.m."/."PM"->"p.m." \$\endgroup\$
    – DELETE_ME
    Commented Jun 9, 2017 at 14:10
2
\$\begingroup\$

T-SQL (2012+), 67 65 bytes

SQL Server 2012 finally gave us a reasonable formatting function for dates. I still had to muck around with the AM/PM to get the format right though.

PRINT 'It''s '+LOWER(STUFF(FORMAT(GETDATE(),'hh:mmtt.'),7,0,'.'))

In previous versions it would have needed something like this (93 bytes)

PRINT'It''s'+LOWER(STUFF(STUFF(RIGHT(CONVERT(VARCHAR,GETDATE(),109),15),6,7,''),8,0,'.'))+'.'
\$\endgroup\$
2
\$\begingroup\$

PHP, 49 bytes

If only it were am/pm instead of a.m./p.m....

It's <?=@preg_replace(~Фž’¢Ð,~ÛÏÑ,date(~˜Å–ž));

I used a lot of nasty bytes to save a bit of length so here's the hex:

00000000: 49 74 27 73 20 3C 3F 3D - 40 70 72 65 67 5F 72 65 |It's <?=@preg_re|
00000010: 70 6C 61 63 65 28 7E D0 - A4 9E 92 8F A2 D0 2C 7E |place(~       ,~|
00000020: DB CF D1 2C 64 61 74 65 - 28 7E 98 C5 96 9E 29 29 |   ,date(~    ))|
00000030: 3B                      -                         |;|
00000031;

Readable version:

It's <?=preg_replace("/[amp]/", "$0.", date("g:ia"));
\$\endgroup\$
2
\$\begingroup\$

C, 103 94 bytes

int main(){time_t r;char b[80];time(&r);strftime(b,80,"It's %I:%M %p",localtime(&r));puts(b);}

Ungolfed

int main()
{
  time_t r;
  char b[80];  
  time(&r);
  strftime(b,80,"It's %I:%M %p",localtime(&r));
  puts(b);
}
\$\endgroup\$
2
\$\begingroup\$

PHP, 41 bytes

It's <?=strtr(date('g:ia'),['m'=>'.m.']);

First time I've played this. Not sure if I'm supposed to update/edit the previous PHP answer (49 bytes) or just add my own...

\$\endgroup\$
2
  • \$\begingroup\$ You should always add your own. You only comment on someone's answer if you see something that can save them a few bytes. But other than that, nice answer! \$\endgroup\$ Commented Sep 11, 2015 at 9:50
  • \$\begingroup\$ By the way, you can write [m=>'.m.'], which saves 2 bytes. (Warnings can be ignored, so, don't worry about them.) \$\endgroup\$ Commented Sep 11, 2015 at 10:21
2
\$\begingroup\$

SQL (PostgreSQL), 42 41 bytes

Another SQL variant, however this one is in a query.

select to_char(now(),'"It''s" HH:MIa.m.')

As a note either p.m. or a.m. works to get the am/pm part. The formatting options in PostgreSQL are really quite flexible. Thanks to @manatwork for the tip to move the it's into the format string.

SQLFiddle

\$\endgroup\$
4
  • \$\begingroup\$ So you need to adjust am/pm it manually? \$\endgroup\$ Commented Sep 11, 2015 at 7:00
  • \$\begingroup\$ @DavidArenburg, no it gets it right with either ... but I had to check it out, because it didn't seem right. If you add + time '12:00' after the now() in SQLFiddle it should change the am/pm. \$\endgroup\$
    – MickyT
    Commented Sep 11, 2015 at 7:18
  • \$\begingroup\$ 1 character shorter: select to_char(now(),'"It''s" HH:MIa.m.') \$\endgroup\$
    – manatwork
    Commented Sep 11, 2015 at 10:10
  • \$\begingroup\$ @manatwork, very nice thanks. I wouldn't have thought of trying that. \$\endgroup\$
    – MickyT
    Commented Sep 11, 2015 at 10:16
2
\$\begingroup\$

Javascript, 103 bytes

Javascript executed from the console.

d="It's "+new Date().toLocaleTimeString();l=d.length;d.slice(0,l-6)+d.slice(-2,l-1).toLowerCase()+'.m.'

C#, 63 bytes

C# executed from the immediate window.

?"It's "+System.DateTime.Now.ToString("h:MMt").ToLower()+".m.";
\$\endgroup\$
3
  • \$\begingroup\$ Also runs as F# ;) \$\endgroup\$
    – Stachu
    Commented Sep 11, 2015 at 15:18
  • \$\begingroup\$ You don't need to calculate d.length, you could just write -n and it will calculate from the end, just an FYI. d="It's "+new Date().toLocaleTimeString();d.slice(0,-6)+d.slice(-2,-1).toLowerCase()+'.m.' 90 bytes. And you can save one byte by moving the "It's " string. And a few bytes from a little string shortcut in there. d=new Date().toLocaleTimeString();"It's "+d.slice(0,5)+d[9].toLowerCase()+'.m.' 79 bytes. \$\endgroup\$
    – Jan
    Commented Sep 11, 2015 at 21:26
  • \$\begingroup\$ And if the answer needs to be locale-independent (as some have posted), just use toLocaleTimeString("en-US") 86 bytes. \$\endgroup\$
    – Jan
    Commented Sep 11, 2015 at 21:48
2
\$\begingroup\$

Bash, 44 characters

Pure Bash, just shell builtins, no ***utils.

printf -vt "It's %(%I:%M%P)T"
echo ${t%m}.m.

Sample run:

bash-4.3$ printf -vt "It's %(%I:%M%P)T";echo ${t%m}.m.
It's 01:04p.m.
\$\endgroup\$
2
\$\begingroup\$

Powershell, 49 bytes

"It's {0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d

(date).hour/23 seems to work as an index for "ap" because it rounds to 0 for hours less than 12 and 1 for 12 and above.

\$\endgroup\$
5
  • \$\begingroup\$ Should be able to golf off a few characters by instead treating the "p"/"a" as string turned into an implicit char-array -- 51 bytes -- "It's $(date -f hh:mm)$("pa"[(date).hour-lt12]).m." \$\endgroup\$ Commented Sep 11, 2015 at 13:56
  • \$\begingroup\$ Your latest "{0:hh:mm}$("ap"[($d=date).hour/23]).m."-f$d misses the It's at the beginning. If you tack that onto the front, it's the same 49 bytes as "It's $((date -f hh:mm)+"ap"[(date).hour/23]).m." \$\endgroup\$ Commented Sep 11, 2015 at 15:57
  • \$\begingroup\$ My bad. I've fixed it. Anyway, this version is more "correct", as it only makes a single call to date \$\endgroup\$ Commented Sep 12, 2015 at 5:19
  • \$\begingroup\$ For what it's worth, I stumbled across the following while researching something else. Apparently [datetime] casts are always en-US. That means something like this "It's $(("{0:h:mmt}"-f[datetime](date)).ToLower()).m." is possible ... which, granted, is 54 bytes and longer than your current solution, but still an interesting quirk of the language. \$\endgroup\$ Commented Sep 23, 2015 at 19:54
  • \$\begingroup\$ @TimmyD Interesting, but it seems it's only casting to DateTime that's en-US, not formatting. \$\endgroup\$ Commented Sep 24, 2015 at 9:32
2
\$\begingroup\$

Locale-dependent

For browser environments that have the locale set to en-CA or any locale that outputs a 12-hour time by default:

CoffeeScript, 81 bytes

alert "It's #{(x=(new Date).toLocaleTimeString().toLowerCase())[..4]} #{x[9]}.m."

JavaScript (ES5), 90 bytes

alert("It's "+(x=(new Date).toLocaleTimeString().toLowerCase()).slice(0,5)+' '+x[9]+".m.")

Locale-independent

CoffeeScript, 113 96 bytes

alert "It's #{(h=(d=new Date).getHours())%12}:#{('0'+d.getMinutes())[-2..]} #{'ap'[+(h>11)]}.m."

Previous:

This one works in all browser environments regardless of locale. Requires Chrome 24+, Firefox 29+, IE 11+, Opera 15+ or any derivatives of such. Does not work in Safari. See Intl.DateTimeFormat.

alert "It's #{new Intl.DateTimeFormat('en',{hour:f='2-digit',minute:f}).format(new Date).toLowerCase()[..-2]}.m."
\$\endgroup\$
3
  • \$\begingroup\$ The javascript answer gave me: It's 2:59: m.m. \$\endgroup\$
    – Mwr247
    Commented Sep 16, 2015 at 18:59
  • \$\begingroup\$ @Mwr247 Which locale is your browser in? \$\endgroup\$ Commented Sep 16, 2015 at 19:29
  • \$\begingroup\$ @rinkattendant6 My locale is en-US \$\endgroup\$
    – Mwr247
    Commented Sep 16, 2015 at 19:55
2
\$\begingroup\$

Swift - 124 102 bytes

import Cocoa
var f=NSDateFormatter()
f.dateFormat="hh:mma"
print("It's \(f.stringFromDate(NSDate()))")
\$\endgroup\$
2
\$\begingroup\$

C, 154 bytes

#include <time.h>
#define l localtime(&r)
main(){time_t r=time(0);printf("It's %02i:%02i%c.m.",(l->tm_hour+11)%12+1,l->tm_min,(l->tm_hour>=12)?'p':'a');}

In contrast to the other C answer, this one uses the correct "a.m."/"p.m." format. The other poster omitted #include <time.h> – if your compiler allows this, we get down to 136 bytes. Which one should we count?

\$\endgroup\$
1
  • \$\begingroup\$ You're right, in fact all I got was a warning – I got it confused with an error from trying to do without time.h. Editing. \$\endgroup\$
    – mindriot
    Commented Sep 14, 2015 at 7:34
1
\$\begingroup\$

Moonscript - 56 bytes

print "It's "..(os.date'%I:%M%p'\gsub 'M','.M.')\lower!

Unfortunately the Lua standard library only implements %p for uppercase AM/PM, so I have to call the method lower.

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

SpecBAS - 64 bytes

PRINT "It's ";LOW$(REPLACE$(TIME$(TIME,"h:mm p$"),"M",".M."))

The built-in p$ of the time function returns AM or PM, so this then has to be formatted with REPLACE$ to change it so it has a full stop before/after that letter.

Then the time output had to be converted to lowercase.

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

MATLAB, 66 bytes

['It''s' lower(datestr(now,'HH:MMam'))];disp([ans(1:end-1),'.m.'])

Displays:

It's 2:48p.m.
\$\endgroup\$
1
\$\begingroup\$

Python 2, 75 67 66 bytes

import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower()

old version, 75 bytes

import time
t=time.strftime("%I:%M%p")
print"It's",t[:5]+t[5].lower()+".m."

old version, 75 bytes

import time
print"It's",time.strftime("%I:%M%p").lower().replace("m",".m.")
\$\endgroup\$
2
  • \$\begingroup\$ @AlexA. Not working in Python 2 time.strftime at least under windows gives "ValueError: Invalid format string" \$\endgroup\$
    – Max
    Commented Sep 11, 2015 at 16:48
  • \$\begingroup\$ @AlexA Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import time;print"It's %s.m."%time.strftime("%I:%M%p")[:6].lower() It's 01:30p.m.` \$\endgroup\$
    – Max
    Commented Sep 18, 2015 at 11:33
1
\$\begingroup\$

Python 3, 117 87 79 bytes

from datetime import*
print(datetime.now().strftime("It's %I:%M%P")[:-1]+".m.")

This gets the hours and minutes from a 12-hour clock using the format %I:%M, plus am or pm using %P. We then select everything but the last m and append .m..

Saved a few bytes thanks to Ruth Franklin!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ As you're only using datetime once, it's 6 bytes shorter to use from datetime import*; h=datetime.now() ... \$\endgroup\$ Commented Sep 11, 2015 at 8:08
  • \$\begingroup\$ @RuthFranklin Thanks for the suggestion! I also found a few other ways to shorten it. \$\endgroup\$
    – Alex A.
    Commented Sep 11, 2015 at 16:31
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\$

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