You can also take the first date in next month and go one day back then you will get the last day of the month. This is of course if theres not a built in way in the language you are using :-)
I forgot this was java. You all are right that there are classes which support managing dates.
I was kinda curious, if you didn't have those build-in classes (or if you were told not to use them for some reason), what would you do (as terms of algorithm)?
Give up, because dates suck /s (seriously though, never ever do it yourself unless you're specifically assigned to do it - this is a solved problem in practically every language).
If you actually have to do it manually there are a lot of solutions that are roughly equal - the array you mentioned, a switch with drop-through cases, or even a dictionary. An array would probably be the most performant, but imo it's just down to whatever you personally think is the most readable.
This example also should either use "else" or simply return the value directly. Right now it goes through two unnecessary conditionals if it's a month with 31 days (besides the bug you mentioned that will cause it to return 28 for every non-leap year).
i study c++, so i'm used to write functionality which is not build-in (i know that c++ has built-in methods for date, but they are not really meant for counting days in month)
Thanks for the advice, anyway
Also, i believe the check for leap year is also wrong -- "These extra days occur in each year which is an integer multiple of 4 (except for years evenly divisible by 100, but not by 400)"
I don't remember what exactly C++ provides off the top of my head, but unless it's easy and safe to derive from the provided functionality I'd always look for a library to solve concerns related to time.
Days in a month is one of the easiest things to solve and even there I'd only trust my own implementations for non-critical purposes where being a day off may be acceptable in occasional edge cases. There are always weird rarely known exceptions with dates.
Right now it goes through two unnecessary conditionals if it's a month with 31 days
Dont forget that it ends with an if else. Meaning if it's not the second month, days are 28... Meaning all months would result in 28 days as far as I can tell.
If I wanted to implement this without any other supporting code, I would probably use a switch case statement.
switch (month) {
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
return 31;
case 2:
if ((year % 100 == 0 && year % 400 != 0) || year % 4 != 0) { return 28; }
return 29;
default:
if (month > 12) { return -1; }
return 30;
}
This could be converted to using if and else statements pretty easily, and I'm not too sure about the performance of switch statements with low case counts such as in this example compared to an if else chain. As well, there are likely other optimizations that could be done to improve performance, such as x % 4 is the same as x & 3, although the compiler will probably catch that.
Edit: a better approach, as mentioned, would be to use an array. Here is some c code demonstrating the idea.
Depending on the needs and environment, i would probably use array, but only if i can manage to link it to a class which implements the function getDaysInMonth()
I dont think using internal (in the function) array would have made me any favour.
Can you elaborate on what you mean when you say array? Like, do you have a premapped array of size 12 which contains the proper values, and an exception for the 2nd month? If so, that would likely be faster than my solution.
Most languages have an EOM (end of month) function. But if it don't have, you can just take the next month and subtract one day. The last day is always the number of days in the month.
They actually have the rule backwards. Years that are divisible by 100 aren't leap years, but years divisible by 400 actually *are* leap years again. That's a deep cut bug though, since it won't be discovered for another 80 years.
That bug will be discovered in 2024, which should be a leap year, but won't be with the division by 400 check.
I'm ignoring the more pressing bug that every month will have 28 days here. February 1600, 2000, 2400... are the only months with 29 days in this code.
If it's divisible by 400, it's a leap year. But it's then divisible by 100 and also by 4, so according to your rule it would not be a leap year. In fact, every year that is divisible by 100 is also divisible by 4 as 100=4*25
Without the 400 year rule the year 2000 would have been a regular year because of the 100 year rule, but 2000 needs to be a leap year. This was only the second time the 400 year rule was used in the Gregorian calendar at all, and the first time for most of the world.
This is way more wrong than I first thought. It will return 28 days for all months except for february on years divisible by 400. The if-else on line 13 overwrites whatever the first two if statements set.
Yeah that's good idea. You never know when you'll have to change the implementation because they've decided that leap years function differently from now on, right?
Are you suggesting that we construct a Date or Calendar object for determining the amount of days or what do you mean by standard library?
I'm not that worried about constructing objects, but can you give a sane reason why using an approach that does require constructing another object is better than writing the very simple logic? Assuming that OP's input really is two integers: month and date.
Not much difference probably if you do it once, but do it a million times and tell me the YearAndMonth-approach is better. I guarantee that the simple method is a lot faster and just as reliable. I have also written Java backend code professionally for 5 years now, so a bit late to switch out of JVM.
You may have been writing code in Java for 5 years, but you still haven't understand a thing if you think that writing useless methods is better than using a built in class just because you have to initialize it. Not only the performance difference is literally none because of the optimizations that javac puts in place, but you are making your code base enormous and more likely to be buggy. Might be time to study again
First of all, my original post was in response to quite a bad implementation, which was most likely a school assignment. So I posted a working alternative. And as a response to that, it was said that you should instead use the builtin, which is a totally valid approach in my opinion too.
I have not once said that that it's better to write "useless methods" in place of builtins. What I have said and will say again, is that the switch-based approach will undoubtedly beat the YearAndMonth-approach in performance. Maybe it's meaningful, maybe not, it depends on the context. I doubt that OP's business case would require such micro-optimization, but who cares?
Writing a couple of modulos and switch-cases is not going to destroy your codebase.
Idk, if we're arguing whether such simple methods should ever be written at all, might just as well switch to JS and start using is-odd and is-even.
The performance thing you mentioned is absolute bs, the difference is so small that in any context it would be meaningless. Moreover, what is going to destroy your codebase is applying this thought process every time, not doing it once.
Finally your implementation is definitely correct, but while we are at it can be written in a far better way using the lambda switch statement and by refactoring the leap year condition as a method for readability purposes: https://pastebin.com/D05aUVA9
All of it. The code is a maintenance and debug nightmare. Not all cases are covered. The return value will only be correct sometimes, otherwise it'll always be 28. And Java can do all this for you in a couple of lines.
Whats so bad about this code? I personally would return instead of setting a days variable, use else’s (although not entirely necessary if you are returning) and checked if the month number was in a literal array, but those are pretty minor things. Usually i see incredibly inefficient bad code on this sub. Everything seems pretty much fine unless i am missing something, other than the if(|| which was already attributed to being a typo
Physicists have solved that headache a long time ago by using Julian years.It's like a Gregorian year (the ones we use in everyday life) except it has a concrete definition (I shit you not, a "year" isn't a metric unit. It's not a unit at all… And ironically it changes nearly every "year")
193
u/Cristichi wicked Aug 22 '21
If(||
Yeah I can relate to that paste
26
u/veselin465 Aug 22 '21
How would you do this code in other ways?
I can only think of an array and an addition check for leap year
Nevermind, i saw the problem, it will always return 28 for any of the months which are not februari
39
u/fletku_mato Aug 22 '21
Write it backwards and return immediately. The 31 day check can then be replaced by just "return 31;"
9
u/snake_case_captain Aug 22 '21
It's not like there are a metric shit-ton of libraries that already do that.
244
u/mfb- Aug 22 '21
Bonus error: Implementing the 400 year rule, but not the 4 and the 100 year rule.
29
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Aug 22 '21 edited Aug 22 '21
Image Transcription: Code
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
24
u/nonbinarydm Aug 22 '21
oof the classic else block
22
u/lt-gt Aug 22 '21
This is way more wrong than I first thought. It will return 28 days for all months except for february on years divisible by 400. The if-else on line 13 overwrites whatever the first two if statements set.
6
u/Dmon1Unlimited Aug 22 '21
So much inefficient nonsense. You could just simply it all to just one line of code by just returning string "yes"
2
u/OneTrueKingOfOOO Aug 22 '21
days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
19
u/fletku_mato Aug 22 '21
4
u/Spartelfant Aug 22 '21
This code is a perfect illustration of what Tom Scott says in his “The Problem with Time & Timezones - Computerphile” video.
TL;DR Make use of existing implementations when it comes to dealing with times and dates, otherwise you will get it wrong one way or another.
1
u/[deleted] Aug 22 '21 edited Aug 22 '21
I didn't get it. What's bad in this? Edit: I hadn't noticed
||in second if block. That's the cause?1
u/[deleted] Aug 23 '21
Whats so bad about this code? I personally would return instead of setting a days variable, use else’s (although not entirely necessary if you are returning) and checked if the month number was in a literal array, but those are pretty minor things. Usually i see incredibly inefficient bad code on this sub. Everything seems pretty much fine unless i am missing something, other than the if(|| which was already attributed to being a typo
3
u/kukisRedditer Aug 22 '21
I'm very interested why he chose to modulo 400 instead of 4
2
u/mr_flameyflame Aug 22 '21
if(||Compiler: wtf man OR WHAT?
2
u/bphase Aug 22 '21
Else considered harmful
2
u/heliosChromatic Aug 22 '21 edited Aug 22 '21
Dont forget about them idiots who think months are indexed zero-based..
was i about to write...
but the longer i looked at the code..
the worse it got.
also how are dates this fucked?
just copy an array from the internet like a true ape.
`
public static enum Month {
January,
...,
};
static byte[] daysInMonthLookup = new byte[]{31,...};
public static int DaysInMonth(Month month, int year)
{
}
Done.
2
u/hullabaloonatic Aug 23 '21
This is why I always want my languages to have enum classes, so that you can have a Month enum with a
getNumDays(year: Int = DateTime.Now.Year)method2
u/Melon_Chief Aug 23 '21
Physicists have solved that headache a long time ago by using Julian years.It's like a Gregorian year (the ones we use in everyday life) except it has a concrete definition (I shit you not, a "year" isn't a metric unit. It's not a unit at all… And ironically it changes nearly every "year")
EDIT: Have you considered a switch statement?
1
u/O_X_E_Y Aug 22 '21
been there done that...
1
u/Stbbrn-Rddtr Aug 22 '21
I’m gonna use that for my April’s fool PR
1
u/papafernwood Aug 22 '21
Leap year mother fucka
1
u/Zicrus Aug 22 '21
This will always return 28 unless it is February in a year divisible by 400
-12
u/Knuffya Aug 22 '21
Except for the inconsistent spacing and the leading || i see no problem with this code. Unless they got the days wrong lol.