What's the time, chap?

18

3

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>

Daniel

Posted 2015-09-10T21:25:57.410

Reputation: 6 425

Are builtins allowed? – jrich – 2015-09-10T21:27:23.780

@UndefinedFunction - yes, you can use builtins – Daniel – 2015-09-10T21:29:09.027

1What is the output format? Does it matter? – mbomb007 – 2015-09-10T21:30:26.293

@mbomb007 - see edit – Daniel – 2015-09-10T21:32:06.353

1No, I mean, should it be yyyy-MM-dd hh:mm:ss UTC or does that date format not matter? – mbomb007 – 2015-09-10T21:34:18.797

@mbomb007 - it should be hh:mm a.m./p.m. – Daniel – 2015-09-10T21:35:16.087

in what way is this [tag:kolmogorov-complexity] – undergroundmonorail – 2015-09-10T22:21:37.287

8I really wanted to put up an answer that prints It's beer o'clock, but I resisted. – MickyT – 2015-09-11T02:18:57.510

I expect a Pyth or CodeJam answer of no more than one byte at some point! – CompuChip – 2015-09-11T07:43:19.037

4Can we use 12:32 PM or 12:32PM? Instead of 12:32p.m.? – Stewie Griffin – 2015-09-11T12:33:31.330

3Is it 02:32 or 2:32 if it's less than 10:00? – Stewie Griffin – 2015-09-11T12:38:37.287

@StewieGriffin - no. You must use p.m or a.m. For your second comment: it doesn't matter. Whichever you want – Daniel – 2015-09-11T19:53:01.663

Can we use 24 hour notation? e.g. 23:00p.m. – LukStorms – 2015-09-11T20:29:16.793

@LukStorms - no. It should be like 11:00p.m. not 23p.m. However, if many people already answered with 24 hour notation already, I might have to change the rule. Anyhow, that's no the case I think. – Daniel – 2015-09-11T23:47:46.847

This is one of the rare questions where a CJam answer is not on the top. – user41805 – 2015-09-14T07:43:18.237

Answers

18

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.'

Doorknob

Posted 2015-09-10T21:25:57.410

Reputation: 68 138

%P gives me uppercase AM or PM. I'm on a mac if it makes a difference. – flodel – 2015-09-10T23:35:48.993

@flodel Works On My Machine™. On Ubuntu 15.04, %P gives lowercase, and %p gives uppercase (which is a bit... unintuitive). – Doorknob – 2015-09-10T23:37:26.237

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.) – tripleee – 2015-09-11T04:52:30.653

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." – aditsu quit because SE is EVIL – 2015-09-11T08:18:51.573

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. – aragaer – 2015-09-11T11:22:10.323

@aragaer That's actually 36 bytes. You can shave off a char by using backticks instead of $(), but it's still longer than my version. Interesting idea though! – Doorknob – 2015-09-11T11:24:40.900

Aww, used flawed method to count characters... My bad. – aragaer – 2015-09-11T11:25:34.727

You can save a byte by using Bash + rs: date "+It's %I:%M%P."|rs.py m/.m (yes, this is a shameless plug to get an answer with rs that I didn't write).

– kirbyfan64sos – 2015-09-12T17:40:03.010

I find on my Debian system, that %P (or %p) gives the abbreviation with dots in, if LC_TIME is set to es_CR. So I've got LC_ALL=es_CR date "+It's %-I:%M%p" for 34, but if you can count the locale as part of the environment, then it goes down to 21 bytes. (Found using for i in $(locale -a); do LC_ALL=$i date "+$i: It's %-I:%M%P" | fgrep .m.; done, of course). – Toby Speight – 2018-09-05T15:30:27.463

13

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.

Digital Trauma

Posted 2015-09-10T21:25:57.410

Reputation: 64 644

18AppleScript is the new Java. – Doorknob – 2015-09-11T10:57:44.277

8

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.

Ismael Miguel

Posted 2015-09-10T21:25:57.410

Reputation: 6 797

Ah, clever! You beat my php answer – DankMemes – 2015-09-11T11:06:41.833

@DankMemes It took me quite a while. And lots of experimenting. – Ismael Miguel – 2015-09-11T11:07:28.170

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)? – DankMemes – 2015-09-11T12:45:07.620

@DankMemes You can indirectly assume that error reporting is disabled. Here's a good read: http://meta.codegolf.stackexchange.com/a/1655/14732

– Ismael Miguel – 2015-09-11T13:17:45.870

5

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).

Toothbrush

Posted 2015-09-10T21:25:57.410

Reputation: 3 197

3Why don't you just replace m by .m.? i.e. Debug.Print Replace(Format(Now,"hh:mm am/pm"),"m",".m.") – CompuChip – 2015-09-11T07:41:28.090

Nice @toothbrush, I sort of expected this to be a one-byte solution in CJam ;) – CompuChip – 2015-09-12T11:55:08.650

4

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!

Alex A.

Posted 2015-09-10T21:25:57.410

Reputation: 23 761

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. – Glen O – 2015-09-11T02:46:05.370

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()) – Glen O – 2015-09-11T05:14:32.213

1@GlenO If you get enjoyment out of squeezing every last byte out of code, PPCG is certainly the right place for you! – Alex A. – 2015-09-11T05:26:36.987

Incidentally, I've found a way to squeeze a few more bytes out: print(strftime("It's %I:%M%P",time())[1:11],".m.") – Glen O – 2015-09-11T06:29:23.853

Actually, even better: print(strftime("It's %I:%M%P\b.m.",time())) – Glen O – 2015-09-11T07:26:14.980

@GlenO That's a great solution, thanks! – Alex A. – 2015-09-11T16:17:13.433

4

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..

David Arenburg

Posted 2015-09-10T21:25:57.410

Reputation: 531

3

Pyth, 38 36 bytes

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

Saved 2 bytes thanks to @Jakube!

kirbyfan64sos

Posted 2015-09-10T21:25:57.410

Reputation: 8 730

@Sp3000 On the online interpreter or locally? – kirbyfan64sos – 2015-09-11T00:17:42.247

@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... – kirbyfan64sos – 2015-09-11T00:39:13.520

@Sp3000 Fixed!!! – kirbyfan64sos – 2015-09-11T00:45:41.370

You're almost beating my PHP answer and Doorknob's Bash answer! – Ismael Miguel – 2015-09-11T16:56:59.603

3

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‌ .")

DavidC

Posted 2015-09-10T21:25:57.410

Reputation: 24 524

(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." – user202729 – 2017-06-09T14:10:04.617

3

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/"

Lynn

Posted 2015-09-10T21:25:57.410

Reputation: 55 648

3

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.

LukStorms

Posted 2015-09-10T21:25:57.410

Reputation: 1 776

1

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!

– ThisSuitIsBlackNot – 2015-09-12T15:05:10.070

Thanks. I used your advice for the shortest POSIX solution. – LukStorms – 2015-09-12T17:46:39.537

1You 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! – ThisSuitIsBlackNot – 2015-09-12T19:52:47.063

Heh, thanks again for rescuing a few bytes. – LukStorms – 2015-09-12T21:39:04.683

3

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.

slvrbld

Posted 2015-09-10T21:25:57.410

Reputation: 619

I think the output must be 05:38p.m. – Ismael Miguel – 2015-09-12T16:14:21.943

According to OP's comment, the leading zero doesn't matter. – slvrbld – 2015-09-12T16:52:14.010

You're right. Here, have my upvote! – Ismael Miguel – 2015-09-12T16:58:14.217

Nice! Didn't know I could use \b like that... You need an extra space btw. – Stewie Griffin – 2015-09-16T16:10:44.780

3

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).

ThisSuitIsBlackNot

Posted 2015-09-10T21:25:57.410

Reputation: 1 050

3

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.".

Dennis

Posted 2015-09-10T21:25:57.410

Reputation: 196 637

2

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,'.'))+'.'

MickyT

Posted 2015-09-10T21:25:57.410

Reputation: 11 735

2

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"));

DankMemes

Posted 2015-09-10T21:25:57.410

Reputation: 2 769

2

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

MickyT

Posted 2015-09-10T21:25:57.410

Reputation: 11 735

So you need to adjust am/pm it manually? – David Arenburg – 2015-09-11T07:00:06.417

@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. – MickyT – 2015-09-11T07:18:14.480

1 character shorter: select to_char(now(),'"It''s" HH:MIa.m.') – manatwork – 2015-09-11T10:10:52.433

@manatwork, very nice thanks. I wouldn't have thought of trying that. – MickyT – 2015-09-11T10:16:04.580

2

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.";

DaveMorganTexas

Posted 2015-09-10T21:25:57.410

Reputation: 121

Also runs as F# ;) – Stachu – 2015-09-11T15:18:00.120

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. – Jan – 2015-09-11T21:26:28.737

And if the answer needs to be locale-independent (as some have posted), just use toLocaleTimeString("en-US") 86 bytes. – Jan – 2015-09-11T21:48:08.483

2

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);
}

Zongor

Posted 2015-09-10T21:25:57.410

Reputation: 51

2

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...

fisharebest

Posted 2015-09-10T21:25:57.410

Reputation: 121

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! – Ismael Miguel – 2015-09-11T09:50:42.010

By the way, you can write [m=>'.m.'], which saves 2 bytes. (Warnings can be ignored, so, don't worry about them.) – Ismael Miguel – 2015-09-11T10:21:30.750

2

CJam, 43 bytes

Having to pad the numbers with zeroes makes this larger than I'd like. In the end, string formatting was the shortest way.

4Z]etf=~Cmd@@'p'a?]"It's %02d:%02d%c.m."\e%

Try it online.

Explanation

   et                                       e# Push local time
4Z]  f=                                     e# Get [minutes hours]
       ~Cmd                                 e# Unwrap array, div+mod hours by 12
           @@'p'a?                          e# Select 'p' or 'a' based on remainder
                  ]"It's %02d:%02d%c.m."\e% e# Print

Andrea Biondo

Posted 2015-09-10T21:25:57.410

Reputation: 1 452

1This fails for both the 12's. Instead of 12:37 it outputs 00:37. – Zach Gates – 2015-09-16T18:30:37.240

2

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?

mindriot

Posted 2015-09-10T21:25:57.410

Reputation: 121

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. – mindriot – 2015-09-14T07:34:29.673

2

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.

manatwork

Posted 2015-09-10T21:25:57.410

Reputation: 17 865

2

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.

Danko Durbić

Posted 2015-09-10T21:25:57.410

Reputation: 10 241

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." – AdmBorkBork – 2015-09-11T13:56:40.450

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." – AdmBorkBork – 2015-09-11T15:57:36.220

My bad. I've fixed it. Anyway, this version is more "correct", as it only makes a single call to date – Danko Durbić – 2015-09-12T05:19:07.800

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.

– AdmBorkBork – 2015-09-23T19:54:02.743

@TimmyD Interesting, but it seems it's only casting to DateTime that's en-US, not formatting.

– Danko Durbić – 2015-09-24T09:32:45.280

2

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."

rink.attendant.6

Posted 2015-09-10T21:25:57.410

Reputation: 2 776

The javascript answer gave me: It's 2:59: m.m. – Mwr247 – 2015-09-16T18:59:48.100

@Mwr247 Which locale is your browser in? – rink.attendant.6 – 2015-09-16T19:29:02.557

@rinkattendant6 My locale is en-US – Mwr247 – 2015-09-16T19:55:51.367

2

Swift - 124 102 bytes

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

Błażej

Posted 2015-09-10T21:25:57.410

Reputation: 121

1

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!

Alex A.

Posted 2015-09-10T21:25:57.410

Reputation: 23 761

1As you're only using datetime once, it's 6 bytes shorter to use from datetime import*; h=datetime.now() ... – Ruth Franklin – 2015-09-11T08:08:33.637

@RuthFranklin Thanks for the suggestion! I also found a few other ways to shorten it. – Alex A. – 2015-09-11T16:31:34.030

1

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.

Ryan Russell

Posted 2015-09-10T21:25:57.410

Reputation: 131

1

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.

Brian

Posted 2015-09-10T21:25:57.410

Reputation: 1 209

1

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.")

Max

Posted 2015-09-10T21:25:57.410

Reputation: 501

@AlexA. Not working in Python 2 time.strftime at least under windows gives "ValueError: Invalid format string"

– Max – 2015-09-11T16:48:07.887

@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.` – Max – 2015-09-18T11:33:10.487

1

MATLAB, 66 bytes

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

Displays:

It's 2:48p.m.

Stewie Griffin

Posted 2015-09-10T21:25:57.410

Reputation: 43 471

1

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.")

mınxomaτ

Posted 2015-09-10T21:25:57.410

Reputation: 7 398

1

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...

Shazback

Posted 2015-09-10T21:25:57.410

Reputation: 51

0

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"

nyuszika7h

Posted 2015-09-10T21:25:57.410

Reputation: 1 624

0

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

Jacob

Posted 2015-09-10T21:25:57.410

Reputation: 1 582

1This also depense on system setting. I don't get am or pm. (24:00 format) – dwana – 2015-09-11T11:00:23.293

Ouch. Ok I will fix it. – Jacob – 2015-09-11T11:19:44.437

@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. – Danko Durbić – 2015-09-11T13:28:37.547

@DankoDurbić Indeed you're correct. Mea culpa. – AdmBorkBork – 2015-09-11T13:47:20.213

"It's "+(Get-Date -Format HH:mmtt).ToLower()-replace"m",".m." works for me (62 bytes) – NeilD – 2015-09-11T14:09:02.463

That's 61 bytes. @NeilD – Zach Gates – 2015-09-16T18:39:00.890

0

Octave, 75 bytes

disp(["It's " strrep(lower(strftime("%R%p",localtime(time()))),"m",".m.")])

Tarod

Posted 2015-09-10T21:25:57.410

Reputation: 181

This shoiws: ans = .... A lot of MATLAB / Octave answers could be a lot shorter if that was legal. – Stewie Griffin – 2015-09-11T12:46:58.607

@StewieGriffin Yes, that's true... – Tarod – 2015-09-11T12:54:54.810

@AlexA. Of course. Thanks! :) – Tarod – 2015-09-11T23:17:29.700

0

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.

Max

Posted 2015-09-10T21:25:57.410

Reputation: 501

0

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.')

edc65

Posted 2015-09-10T21:25:57.410

Reputation: 31 086

This doesn't output leading 0:s if any number is below 10. F.e It's 0:9a.m. – Jan – 2015-09-11T22:10:29.527

@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 – edc65 – 2015-09-11T23:48:40.650

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. – Jan – 2015-09-11T23:51:10.610

My first comment was from the console output of running your script. – Jan – 2015-09-12T00:00:58.717

@Jan Right. It's broken. Fixing it – edc65 – 2015-09-12T00:03:47.063

Neat little trick with the a/p selector by the way. Nice. – Jan – 2015-09-12T00:09:07.407

I believe you need an alert (or similar output) in JavaScript for it to be considered valid by code golf conventions. – Mwr247 – 2015-09-16T19:32:19.350

@Mwr247 right, thanks for pointing it out – edc65 – 2015-09-16T19:35:31.137

0

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.

RK.

Posted 2015-09-10T21:25:57.410

Reputation: 497

0

Perl, 88 75 bytes

use POSIX;$d=lc strftime"%R%p",localtime;$d=~s/m/.m./;printf("It's %s",$d);

Tarod

Posted 2015-09-10T21:25:57.410

Reputation: 181

POSIX automatically exports everything, so you can shave off 13 bytes by dropping the qw(strftime). – ThisSuitIsBlackNot – 2015-09-12T03:53:19.610

@ThisSuitIsBlackNot Thank you! :D – Tarod – 2015-09-13T00:53:56.963

0

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."));
  }
}

Nayuki

Posted 2015-09-10T21:25:57.410

Reputation: 240

0

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.");}}

helencrump

Posted 2015-09-10T21:25:57.410

Reputation: 161

0

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.

Zach Gates

Posted 2015-09-10T21:25:57.410

Reputation: 6 152

0

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".)

lirtosiast

Posted 2015-09-10T21:25:57.410

Reputation: 20 331

0

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.')

Mwr247

Posted 2015-09-10T21:25:57.410

Reputation: 3 494

0

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

Jacob Misirian

Posted 2015-09-10T21:25:57.410

Reputation: 737

0

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.

Stewie Griffin

Posted 2015-09-10T21:25:57.410

Reputation: 43 471