15
\$\begingroup\$

You love lunch. However, you are on a diet and want to make sure you don't accidentally eat lunch twice in one day. So you need to make a program to help you make sure.

However, one complication is that you eat lunch on a very weird schedule. The time you eat lunch at is MONTH:DAY PM (you can use UTC or localized time zone). That's right, if the day is July 14, you eat lunch at 7:14 PM.

For your program, you need to use the current date and time (don't take input), and output a consistent truthy value if you have already eaten lunch for the day (or it is lunch time now), or a consistent falsy value if you haven't.

Examples: (Time you run program => output)

  • May 4th 11:35 AM => false (you will eat lunch at 5:04 PM)
  • June 3rd 5:45 PM => false (you will eat lunch at 6:03 PM)
  • July 28th 8:30 PM => true (you ate lunch at 7:28 PM)
  • December 15th 3:25 PM => true (you ate lunch at 12:15 PM)
  • February 29th 2:29 PM => true (it is exactly lunch time)
  • October 12th 12:00 AM => false (day just started)

Reference:

How a 12 hour clock works

\$\endgroup\$
9
  • \$\begingroup\$ Can't we use UTC instead? \$\endgroup\$
    – Mr. Xcoder
    Jul 14, 2017 at 20:16
  • \$\begingroup\$ @Mr.Xcoder Yeah, actually that's ok. I'll clarify. \$\endgroup\$
    – geokavel
    Jul 14, 2017 at 20:17
  • 5
    \$\begingroup\$ If you eat lunch only at one specific time of day, how could you eat it twice? =p \$\endgroup\$
    – jpmc26
    Jul 15, 2017 at 2:13
  • 1
    \$\begingroup\$ @MarkS. At least this century, let's say. \$\endgroup\$
    – geokavel
    Jul 15, 2017 at 17:11
  • 3
    \$\begingroup\$ Doesn't everyone eat their lunch like this? Is it really only me? \$\endgroup\$ Jul 15, 2017 at 18:06

23 Answers 23

7
\$\begingroup\$

Swift 3, 310 bytes

import Foundation;var n=String(describing:Date());var k=n.startIndex;print(Int(n[n.index(k,offsetBy:5)...n.index(k,offsetBy:6)])!*60+Int(n[n.index(k,offsetBy:8)...n.index(k,offsetBy:9)])!+720<=Int(n[n.index(k,offsetBy:11)...n.index(k,offsetBy:12)])!*60+Int(n[n.index(k,offsetBy:14)...n.index(k,offsetBy:15)])!)

Check it out!

This prints true and false, for truthy and falsy respectively.

NOTE: This only works until the year 9999, at 11:59:59 PM, because it uses Strings to compare the dates.

\$\endgroup\$
1
  • 2
    \$\begingroup\$ Swifts substringing always pains me to look at >_< :P \$\endgroup\$
    – Downgoat
    Jul 15, 2017 at 2:14
3
\$\begingroup\$

05AB1E, 15 18 bytes

žežb‚žf12+ža‚т*+`‹

Try it online!

Explanation

žežb‚žf12+ža‚т*+`‹
že                 # Push current day
  žb               # Push current minute
    ‚              # Wrap to array
     žf12+         # Push current month and add 12 to it
       ža          # Push current hour
         ‚         # Wrap these two to array as well
          т*       # Multiply each element in the second array by 100
            +      # Add both arrays together
             `     # Flatten the resulting array to stack
              ‹    # Is the first item smaller than the second one?
\$\endgroup\$
2
  • \$\begingroup\$ I don't think this works. Because it's 12:51 AM UTC right now, and it's outputting 1. \$\endgroup\$
    – geokavel
    Jul 31, 2017 at 0:53
  • \$\begingroup\$ Nvm just realized i was checking against am not pm. Fixed at the cost of 3 bytes. \$\endgroup\$
    – Datboi
    Jul 31, 2017 at 15:08
2
\$\begingroup\$

Octave, 61 bytes

diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200

Try it online!

Explanation:

First the functions:

  • now() returns the time on a decimal format. The parentheses are optional.
  • datestr converts a decimal number to a string on the format given in its second argument
  • str2num converts a string to a number
  • diff takes the difference between two numbers

Breakdown:

We take this from the middle:

diff(str2num([(d=datestr(now,'mmddHHMM'))(1:4);d(5:8)]))>1200

datestr(now,'mmddHHMM'): First we take the current time now as input to datestr and specifies the format mmddHHMM. The letters mean: mm = month, dd = day, HH = hour, MM = minutes and AM specifies that the hours should be on a 12-hour format. No separators are included, to keep it as short as possible. It outputs d = 07142117 on the time of writing this explanation. I'll refer to that part as x from now.

[(d=x)(1:4);d(5:8)]: Stores the string above, as d, then creates an array with two elements, the first four characters, then the 5-9 characters. This gives:

ans =
0714
2122

Where the numbers are stored as strings, not numbers. We'll call the result above for y below.

str2num(y) converts the array of characters to numbers, where each row turns into one number. This gives [714; 2122]. We'll call the result for z.

diff(z)>1200 takes the difference between the two numbers and checks if the current time is 1200 higher than the current date. This accounts for AM/PM. This gives us the desired result.

\$\endgroup\$
3
  • \$\begingroup\$ does this check if it's actually PM? \$\endgroup\$
    – michi7x7
    Jul 14, 2017 at 21:35
  • \$\begingroup\$ It does now. :) \$\endgroup\$ Jul 14, 2017 at 22:08
  • \$\begingroup\$ If "mmdd" is "1201" and "HHMM" is "1215" this should be trueish, no? I had to use mod 12 on the month to account for that somehow. \$\endgroup\$
    – michi7x7
    Jul 14, 2017 at 22:12
2
\$\begingroup\$

Pyth, 22 21 20 bytes

<0+g.d7.d5-.d6+12.d4

-1 byte thanks to @Mr.Xcoder

Try this!

old approach, 22 20 bytes

<+`+12.d4.d5+`.d6.d7

Try it!

explanation

<0+g.d7.d5-.d6+12.d4
              +12.d4   # Add 12 to the current month to make it PM
          -.d6         # subtract that from the current hour: negative it is too early,
                       # positive when it is past this hour, zero when its the same hour
   g.d7.d5             # Is the minute greater or equal than the day? True=1; False=0
  +                    # Add this to the hour result,
                       # so that 0 can turn positive if minutes are true
<0                     # Is the result larger than 0 ?
\$\endgroup\$
5
  • \$\begingroup\$ Wouldn't &g.d6+.d4 12g.d5.d7 work for 19 bytes? I am not sure and haven't really tested it yet but... \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 9:03
  • \$\begingroup\$ &g.d6+12.d4g.d5.d7 would be 18 actually. Also, in the old approach I don't think you need the `, and that would become 18 bytes long. I don't know, I might be wrong. \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 9:05
  • \$\begingroup\$ @Mr.Xcoder if you use & then both have to be true e.g. in your code 22:17 wouldn't count as after 19:15, because the minutes are false. I can remove some of the ```, but not all of them. Thank you for saving me a byte. \$\endgroup\$
    – KarlKastor
    Jul 15, 2017 at 10:23
  • \$\begingroup\$ Ok, I really didn't know if that was correct, I'm still learning Pyth :P \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 10:26
  • \$\begingroup\$ Then, I have found an alternative solution g++720.d5*60.d4+*60.d6.d7, but that is longer unfortunately (25 bytes). However, it might be a source of inspiration and I figured I should mention it. \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 10:32
2
\$\begingroup\$

C#, 174 bytes

using System;public class Program{public static void Main(){Console.WriteLine(DateTime.Now>DateTime.Today.AddHours(DateTime.Today.Month+12).AddMinutes(DateTime.Today.Day));}}

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ I don't think you can add hours and minutes, you must set them. \$\endgroup\$
    – Winter
    Jul 15, 2017 at 17:34
  • 1
    \$\begingroup\$ Create an anonymous action (()=>...) as Action<bool> to save bytes. Use DateTime.Now when accessing the month and day. In general public is not needed and Program can be just one letter. Use using D=System.DateTime; to save bytes.Overall nice idea but could be golfed a lot. Welcome to PPCG! \$\endgroup\$ Jul 17, 2017 at 10:31
  • \$\begingroup\$ @TheLethalCoder thanks for the advice! This was my first go at code golf but I'll definitely be trying more! \$\endgroup\$
    – pritch90
    Jul 20, 2017 at 20:56
2
\$\begingroup\$

PHP and other languages with these common functions: about 28 to 29 bytes:

echo eval(date('Gi-1199>md')); 

or alternatively

<?=eval(date('Gi-1199>md'))?>

both of which will print.

possibly with ?1:0 depending on representation. Possibly bytes cut if a language is used that has implicit echo, or no final ';'.

Why would one get the values into variables and all the rest, when it's not needed :)
date() leaves anything as literals that isn't defined, so for example, 7 May 2017 17:22:43 passes the expression 1722 - 1200 >= 507 to eval(). Byte saved by changing it to the equivalent 1722 - 1199 > 507.

Who says eval is dead? ;-)

\$\endgroup\$
2
\$\begingroup\$

Java, 81 bytes

n->new Date().after(new Date(){{setHours(getMonth()+13);setMinutes(getDate());}})

Try it online!

Ungolfed:

n -> new Date().after(new Date() { //new Date() returns current date
    { //instance initialization
        setHours(getMonth() + 13); //month + 12 hours for PM + 1 because months are 0 indexed
        setMinutes(getDate()());
    }
})
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Does this handle December correctly? I haven't worked with Java in a long time, but this looks like it might send December 1 to 24:01 instead of just after noon. \$\endgroup\$
    – Mark S.
    Jul 16, 2017 at 22:06
  • \$\begingroup\$ Don't forget to include your import of java.util.Date in the byte count. \$\endgroup\$
    – Jakob
    Aug 12, 2017 at 3:50
2
\$\begingroup\$

Haskell, 135 129 bytes

import Data.Time
x(ZonedTime(LocalTime d(TimeOfDay h m _))_)|(_,x,y)<-toGregorian d=return(mod x 12<h-12&&y<m)
y=getZonedTime>>=x

this unpacking is quite annoying, maybe string handling is better suited

//edit: pattern guards safe 5 bytes

\$\endgroup\$
2
\$\begingroup\$

Mathematica, 65 64 62 bytes

3 Programs

p=Date[][[#]]&;{60,1}.#&/@(p[4;;5]>=p[2;;3]+{12+p@2~Mod~12,0})

{60,1}.#&/@(#[[4;;5]]>=#[[2;;3]]+{12+#[[2]]~Mod~12,0})&@Date[]

{60,1}.#&/@(#[4;;5]>=#[2;;3]+{12+#@2~Mod~12,0})&[Date[][[#]]&]

These are each one byte less if counts as a single byte in Mathematica.

Explanations

  1. Date[] returns a list in the form {y,m,d,h,m,s}. So Date[][[4;;5]] are the hours and minutes of the current time.
  2. p=Date[][[#]]&; makes p a function that takes in the indices we want and gives us those parts of the date.
  3. {60,1}.#& is an anonymous function that takes the dot product of {60,1} and the input to get a way to compare times. It's one byte shorter than TimeObject.
  4. p@2 is equivalent to p[2], the number of the month.
  5. +{12+p@2~Mod~12,0} adds {12,0} to the month and date when we're not in December, and adds {0,0} otherwise. (Thanks, michi7x7!)
  6. >= is the comparison operator, but we can't compare {hours, minutes} to {adjusted month, date} entrywise...
  7. /@ maps {60,1}.#& to both sides of the inequality in parentheses, so we can compare times correctly.
  8. For the programs that start with {60,1}.#&, they use # to represent the input to a big anonymous function, and & to signify the end.
  9. @Date[] Applies the big function on its line (which extracts parts of a list) to the date list itself.
  10. [Date[][[#]]&] Applies the big function on its line to another anonymous function, one which extracts parts of the date list.

Bonus

As an aside, if we ate lunch between 1AM and 12:59PM, then we could save 25 bytes with just {60,1}.#&[Date[][[#]]]&/@(4;;5>=2;;3).

You can test all of these out by pasting the code into the Wolfram Cloud sandbox and clicking Gear->Evaluate Cell or hitting Shift+Enter or Numpad Enter.

\$\endgroup\$
6
  • \$\begingroup\$ I believe that your bonus note is actually a valid solution - as your domain of valid times is 13:01 to 24:31 \$\endgroup\$ Jul 19, 2017 at 21:20
  • \$\begingroup\$ @TaylorScott Thanks for the code formatting (though the colorization seems to fail on some trickier cases). I'm not sure I understand your comment, though. If the If it's 7:20AM on July 19, then the "bonus" code would say "yes, you've had lunch" even though it's far from 7:20PM. The OP has test cases in the AM so I think this makes it invalid. What am I missing? \$\endgroup\$
    – Mark S.
    Jul 20, 2017 at 1:22
  • \$\begingroup\$ @Mark_S. I See - for some reason i had read that as being 11:59 PM rather than 12:59 -is there no concise way to add 12 hours to the bonus code? \$\endgroup\$ Jul 20, 2017 at 18:30
  • 1
    \$\begingroup\$ @TaylorScott Well, we want to add 12 to the hour for most months so for January through November we could replace the Date[] in the bonus with (Date[]+{0,12,0,0,0,0}) (there may be a way to golf that, but 12UnitVector[6,2] is longer). The problem is that on dates like December 3, we eat lunch at 12:03, not 24:03, so we need to add 12 except in December. This requires us to either 1. peek inside the date to see if we're in December or not (as in my answers), or 2. write a function that examines if we went to 24:XX after the fact, which would be longer. \$\endgroup\$
    – Mark S.
    Jul 21, 2017 at 0:21
  • 1
    \$\begingroup\$ @MarkS. 12+Mod[#[[2]],12] ? \$\endgroup\$
    – michi7x7
    Jul 31, 2017 at 12:42
1
\$\begingroup\$

JavaScript (ES6), 75 bytes

f=
(d=new Date)=>(d.getHours()-d.getMonth()-13||d.getMinutes()-d.getDate())>=0
<input type=button value=Lunch? onclick=o.textContent=f()><tt id=o>

Those long function names...

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

Python 3, 104 bytes

from datetime import*
n=datetime.now();print(n>=n.replace(hour=[0,n.month+12][n.month<12],minute=n.day))

Try it online!

All datetime tests. I replaced Feb 29th with Feb 28th because the invalid date wasn't working.

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

R, 92 bytes

library(lubridate)
d=Sys.Date()
cat(Sys.time()>ymd_hm(paste0(d,'-',month(d)+12,'-',day(d))))

Try it online!

                                   month(d)+12,'-',day(d)    # get month and day and paste into a string, adding 12 hours for pm
                      paste0(d,'-',                      )   # add current date to beginning
               ymd_hm(                                    )  # turn whole thing into a date-time object
cat(Sys.time()>                                            ) # compare with current date-time and print
\$\endgroup\$
1
\$\begingroup\$

q, 31 bytes

x>12:+"T"$(-3!x:.z.P)5 6 13 8 9

Example:

q).z.P
2017.07.16D19:35:26.654099000
q)x>12:+"T"$(-3!x:.z.P)5 6 13 8 9
1b

Interpreter is available here

Old version

{x:.z.p;x>"T"$":"sv"0"^2$/:string 12 0+`mm`dd$\:x}`
\$\endgroup\$
2
  • \$\begingroup\$ The 2$ pad will turn 6 to 6_ rather than _6, so you'd want (-2)$, but you can cancel out those extra 3 chars by using the shorthand for string as ($)... or instead of using $ to pad, prepend "0" and then take the last 2 chars: {x:.z.P;x>"T"$":"sv -2#'"0",'($)12 0+mmdd$\:x} for 49 bytes \$\endgroup\$
    – mkst
    Jul 16, 2017 at 17:32
  • \$\begingroup\$ good spot. the original was invalid. i added an even shorter version \$\endgroup\$
    – skeevey
    Jul 16, 2017 at 18:36
1
\$\begingroup\$

JavaScript, 75 bytes

t=new Date,t.setHours(13+t.getMonth()),t.setMinutes(t.getDate()),new Date>t

Which is equivalent to the following code:

function didEat()
  const d = new Date()
  d.setHours(12 /* PM */ + d.getMonth() + 1)
  d.setMinutes(d.getDate())
  return new Date > d
}
didEat()
\$\endgroup\$
2
  • \$\begingroup\$ last t can be used while modify \$\endgroup\$
    – l4m2
    Jan 2, 2018 at 23:04
  • \$\begingroup\$ t=new Date,t.setMinutes(t.getDate(t.setHours(13+t.getMonth(n=+t))))<n \$\endgroup\$
    – l4m2
    Jan 2, 2018 at 23:20
1
\$\begingroup\$

Python 2.7, 130 bytes

from datetime import*
a=str(datetime.now()).split()
print int(''.join(a[0].split('-')[1:]))+1200<int(''.join(a[1].split(':')[:2]))

Try it online

Note: There may be a problem with the sign. Please excuse that because I follow IST and it's quite confusing because it's 2:28am here now. Do correct the sign if you feel it is wrong.

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

Perl, 45 chars

sub c{@a=gmtime;$a[2]-12>$a[4]&&$a[1]>=$a[3]}

If I have to provide a method, it will be 45 for sub c{...}. If I have to print say ()||0 even makes it 47. I will add that in if it's a requirement.

\$\endgroup\$
2
  • \$\begingroup\$ I believe that because the original question specifies you need to make a program to help you make sure that snippets are not allowed - that said either of your listed output methods are generally considered valid \$\endgroup\$ Jul 19, 2017 at 21:30
  • 1
    \$\begingroup\$ fair enough, I will provide output then. Thanks for editing, I was not aware of the proper language tag! I was thinking perl -e was generally ok, but others have provided functions, so I edited it in. \$\endgroup\$
    – bytepusher
    Jul 19, 2017 at 21:44
1
\$\begingroup\$

Excel, 52 50 49 bytes

=TIME(MONTH(NOW())+12,DAY(NOW()),0)<=MOD(NOW(),1)

Input is this formula in any cell.
Output is either TRUE or FALSE.

Excel's built-in date handling helps a lot.
The TIME function returns the day's lunch time as a time value which, if converted to a date, would use Jan 0, 1900. We compare it against NOW - TODAY so we get the current time with a date value of 0 or Jan 0, 1900.

Saved 2 bytes thanks to Wernisch
Saved 1 byte thanks to Adam

\$\endgroup\$
3
  • \$\begingroup\$ Do you need the extra braces around NOW()-TODAY() ? \$\endgroup\$
    – Wernisch
    Jul 31, 2017 at 15:39
  • \$\begingroup\$ @Wernisch No, as it turns out. I had presumed it would evaluate the inequality before the subtraction but I didn't check it. Thanks. \$\endgroup\$ Jul 31, 2017 at 15:48
  • \$\begingroup\$ I think you can save a byte by changing from now()-today() to mod(now(),1) \$\endgroup\$
    – Adam
    Aug 12, 2017 at 5:34
0
\$\begingroup\$

JavaScript, 62 chars

f=
_=>[,m,d,H,M]=(new Date).toISOString().split(/\D/),+m+12+d<=H+M

Test code below:

console.log(( // May 4, 5:03 PM, false (1 minute before lunch)
  [,m,d,H,M]=(new Date("2017-05-04T17:03Z")).toISOString().split(/\D/),+m+12+d<=H+M
));

console.log(( // May 4, 5:04 PM, true (exact time)
  [,m,d,H,M]=(new Date("2017-05-04T17:04Z")).toISOString().split(/\D/),+m+12+d<=H+M
));

console.log(( // May 4, 5:05 PM, true (1 minute after)
  [,m,d,H,M]=(new Date("2017-05-04T17:05Z")).toISOString().split(/\D/),+m+12+d<=H+M
));

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

Excel VBA, 55 Bytes

Anonymous VBE immediate window function that takes no input and outputs a Boolean value representing whether I've had lunch to the VBE immediate window

n=Now:?TimeValue(n)>TimeValue(Month(n)&":"&Day(n)&"PM")
\$\endgroup\$
0
\$\begingroup\$

Ruby, 64+7 = 71 bytes

Requires the -rtime flag because for some reason Time::parse is like, the only function requires it out of the entire Time module.

p Time.parse("#{t=Time.now}"[/.+-(..)-(..) /]+[$1,$2]*?:+'pm')<t

Try it online! (it also prints out the current time)

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

Julia 0.6.0 99 bytes

a=split(string(Dates.today()),"-");(Dates.hour(now())<parse(a[2]))&&Dates.minute(now())<parse(a[3])

Julia has built in function to use the clock/calendar of the computer. My computer is running on ubuntu 16.04 and already with 12 hour clock, so I can't say if what I did works with other machine using different clock, but seems to works on my machine.

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

JavaScript ES6, 70 Bytes

_=>(h=x=>new Date().toJSON().substr(x,5).replace(/\D/,0))(5)+12e3<h(11)

Maybe not that right on some milliseconds...

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

Matlab, 241 bytes

dt=datestr(now,'mm/dd');
dt(2)
dt(4:5)
CrctLchTm=[' ' dt(2) ':' dt(4:5) ' PM']
CrntTm=datestr(now,'HH:MM PM')
CrntTm(7)=='A'
if ans==1
    Lch='false'
else
    CrctLchTm=str2num([CrctLchTm(2) CrctLchTm(4:5)])
    CrntTm=str2num([CrntTm(2) CrntTm(4:5)])
    CrntTm<CrctLchTm
    if ans==1
        Lch='false'
    else
        Lch='true'             
    end    
end

Explanation: First, I obtain the date as a string. Then, I isolate the month and day. Since the problem states that it is always interpreted as PM, then I automatically write false if the time is in AM. If the current time is in PM, then I continue on and just compare the numbers of the time.

Note: I've formatted it slightly differently here for readability.

\$\endgroup\$

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.