r/badcode • • Jun 01 '21

c# DateTimes are hard

Post image
914 Upvotes

77 comments sorted by

303

u/Yserbius Jun 01 '21

To be fair, DateTimes are hard. Like ridiculously unintuitively hard. There was a time when computer scientists figured everything can be represented as the number of seconds from 1970. We know now that that idea is woefully wrong. You need to know time zones. You need to factor in Daylight Savings. You need to have a different API depending on whether you're talking about an instant in time, or the amount of time during which something is occurring.

So you have bloated messes that look like this because it's honestly the only way to pass that unit test which attempts to roll back a transaction triggered from Venezuela to a server across the International Date Line in the second when Daylight Savings Time switches over.

85

u/Ali3nat0r Jun 01 '21 edited Jun 01 '21

Want to calculate how long it's been since the start of World War I, and display it to a Russian client? Good luck, because Russia only switched to the Gregorian Calendar in 1918.

Edit: That's a bad example. A better example would be having a Russian citizen's date of birth officially listed as before 1918, and working out their age. You can't just subtract it from the current date like you normally would, you have to add an edge case that converts it to Gregorian first

35

u/tiredofsametab Jun 01 '21

A fun one is Japanese dates which use the regnal name of the era and do not start on 1/1 of the calendar (western) year. Still used heavily in banking and official documents here.

23

u/Yserbius Jun 01 '21

Actually that's fairly straightforward with some knowledge of modern time libraries. You need to get an instance of JulianCalendar in the API of your choice, input the date, then just run the built in conversions to get a GregorianCalendar instance, then calculate the difference between that and the current date as a GregorianCalendar.

Alternatively, you can convert today's date to JulianCalendar and get the difference in terms of years. Of course, don't forget to factor in time zones in case said Russian citizen's birthday is today!

Or you could just ask the Russian Orthodox Church who still use Julian for everything.

39

u/FrostBite_97 Jun 01 '21

Or you could just ask the Russian Orthodox Church who still use Julian for everything.

That's how the API works.

20

u/DJOMaul Jun 01 '21

Hmm. Now I'm picturing a bunch of monks sitting in front of banks of computers doing datetime conversations manually for each api request....

It's been a long day.

2

u/EleanorStroustrup Jun 02 '21

a bunch of monks sitting in front of banks of computers doing datetime conversations manually for each api request

https://www.mturk.com/

5

u/detroitmatt Jun 02 '21

Assuming you know ahead of time that your client is Russian

27

u/fakehalo Jun 01 '21

There was a time when computer scientists figured everything can be represented as the number of seconds from 1970.

In fairness, it was a necessary evil to do calculations based on a 32bit number going forward due to the limitations of the time (pun intended?). But, 2038 might be an interesting year.

9

u/AndMetal Jun 01 '21

I've been getting back into some hobby coding recently since I just bought a new laptop and sorta ran into this last night. The API I'm calling has a method to get the server time as an epoch, and when working with the JSON libraries (.NET) there are options to cast it. The recommended option was Int32, but I was getting a FormatException during runtime. Eventually I realized the value returned via the API is the epoch in milliseconds, not seconds, so I had to move up to Int64 🤦‍♂️

2

u/jarfil Jun 02 '21 edited Dec 02 '23

CENSORED

10

u/blehmann1 depraved Jun 01 '21

Well, representing everything as a Unix timestamp is a good idea, it's just only for an internal representation. Right now the hellishness comes from one source: converting to/from an evil disgusting time object with timezones and DST and conflicting calendars, etc.

Imagine how much worse it would be if we had to convert from every hellish time object to every other without a locale agnostic intermediate.

And for what it's worth, it's C# so it doesn't use a Unix timestamp on the inside, the epoch begins at 1 AD (although for lots of other Microsoft stuff it's in the 17th century...)

9

u/anyfactor Jun 02 '21

I don't think anyone can write badcode when it comes to DateTime. I kid you not, my project was stuck for 4+ months because I had to calculate between 3 different timezones, multiple time formats and approximately matching the time from a data set.

4+ month. Endless ideas, endless idea testing. 4+ MONTH!

Then in one fell sweep, I solved the entire thing in under 15 lines of code. And it is as good as it gets.

I couldn't imagine someone getting paid and being responsible for this complex of a problem. I still haven't tested for DST yet.

6

u/Spire Jun 02 '21

Then in one fell sweep, I solved the entire thing in under 15 lines of code.

No way. I don't believe you.

I still haven't tested for DST yet.

Aha!

1

u/anyfactor Jun 02 '21

I have trust in module(s) I have imported!

3

u/NikkoTheGreeko Jun 02 '21

Yes, they really are. I share this with every new hire.

https://youtu.be/qabriMQ1SYs

2

u/[deleted] Jun 02 '21

luckily most langs have datetime stuff builtin or coming, even js has a proposal for utils and libs until then

2

u/JuhaJGam3R Jun 02 '21

Representing time as seconds from 1970 is a good idea. It allows you to not factor in DST, time zones, etc. and just compare absolute moments to each other. It's far more useful than any other representation for most things, from counters to timestamps and expirations, intervals, timers, etc. Try figuring out the difference in seconds between this time yesterday and now without using seconds since 1970. A calculation alone is not enough, you'd have to start tracking whether there was any kind of adjustment done, possibly the date for that, etc. In Unix timestamps it's as simple as subtracting one number from another.

This has no problems. There is no date line as a concept, no time zones, no problems with either. Rolling back a translation mid-DST switch across the date line is the same thing as rolling back anything else, the absolute time does not care about time zones. The whole world runs on a single absolute time which can be converted into real dates with some complexity but be generally right-ish even with dumb methods.

The point is that absolute time is easy and removes all internationalization issues until it's converted into real dates. It works really well.

1

u/EleanorStroustrup Jun 02 '21

Until you need milliseconds, or something a long time in the past or future...

1

u/JuhaJGam3R Jun 02 '21

Well a 64 bit second counter does 20 times the present age of the universe in either direction. With milliseconds that's .2 times the age of the universe or 2.8 billion in each direction, give or take a bit. A nanosecond counter only does 275 million years forward and back. If you're dealing with numbers bigger than that for time I suggest you get a new job, yours is quackery.

1

u/EleanorStroustrup Jun 03 '21

I was thinking 32 bits.

1

u/JuhaJGam3R Jun 03 '21

Nothing runs 32 bits anymore except legacy systems. Y38K pushed critical applications to upgrade. It was different back in the day, though. Even then people just used two registers to store a double word timestamp when they need longer time. Precision is not an issue, nor is the length. Besides if there's a 32 bit system which never needed to deal with long time periods still running by 2038 it's their own damn fault.

2

u/temmoku Jun 02 '21

Had to calculate daily rainfall from automatic rain gauge data but in Australia rainfall is reported at 9:00 AM so the accumulated rainfall for the previous 24 hours, which spans two days. That took some thought. If I recall, I basically subtracted nine hours from all the times, calculated a daily total and then recorded it for the next day.

2

u/[deleted] Jun 17 '21

well, if you want to talk about a specific instant in time, "seconds since/until some epoch" is fine

but that also means leap seconds shouldn't be included in that

it should be "if I started a timer right then, and left it running until now, what would it say?" The length of a second is well defined.

But when you actually want to display that time to a human user, that's when the fun comes in.

3

u/tomthecool Jun 01 '21

Nobody ever thought that EVERYTHING can be represented by the Unix time stamp!...

However it still remains a pretty good system for specifying a universally recognised moment in time, very concisely.

195

u/bonkwonkponkreal Jun 01 '21

Datetime formats are horror. This post inflamed my anxiety.

77

u/[deleted] Jun 01 '21

How is this bad code? Am I missing something?

80

u/[deleted] Jun 01 '21

It's not UTC. And it it's just the same as saying timestamp = datetime.now

3

u/[deleted] Jun 01 '21

Yup I missed that part, thanks

48

u/[deleted] Jun 01 '21

[removed] — view removed comment

19

u/hsantefort12 Jun 01 '21

Ah datetime, the absolute bane of my existence

0

u/[deleted] Jun 01 '21

[deleted]

5

u/[deleted] Jun 01 '21

[removed] — view removed comment

1

u/DogmaSychroniser Jun 02 '21

The firm I'm at just has a class called clock which has a getter and setter property that let's you capture the date time and fix it if you need to for a test, elsewise it just calls DateTime.Now()

2

u/[deleted] Jun 02 '21

[removed] — view removed comment

1

u/DogmaSychroniser Jun 02 '21

I'd probably build it differently if I had a say in it but I came waaaay late to the party.

13

u/szescio Jun 01 '21

Not sure what they are trying to achieve, but a) for sure theres an easier way b) if its so complicated, put that shit in a helper or provider

1

u/[deleted] Jun 01 '21

They're formatting the time and then parsing it

-4

u/[deleted] Jun 01 '21

Yes.

27

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 01 '21 edited Jun 01 '21

Image Transcription: Code


[The code is in an overview of a Git commit; the first line in the method is highlighted red, and the second line is highlighted green, meaning that the first line was replaced with the second line.]

public ApiResult()
{
    TimeStamp = DateTime.UtcNow;
    TimeStamp = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
}

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!

8

u/britishben Jun 01 '21

It might be a bit more readable in diff format - something like this:

 public ApiResult()
 {
  • TimeStamp = DateTime.UtcNow;
+ TimeStamp = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")); }

7

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 01 '21

I prefer not to add characters to the code block that aren't in the code, if possible to avoid. I also think that wouldn't work well with screen-readers (I know visually-impaired programmers are rare, but they do exist), and although it conveys the same information, it doesn't actually describe how that information is conveyed in the image, which I prefer to do as it's a more "direct" transcription that way.

3

u/britishben Jun 01 '21

That's a fair point - I wasn't aware that screen-readers would struggle with it. I guess mine is more an "interpretation" than a transcription, too.

19

u/[deleted] Jun 01 '21

[removed] — view removed comment

16

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 01 '21

Oh my god, I feel so stupid... These are things I know

I've fixed it, thanks for pointing it out!

9

u/[deleted] Jun 01 '21

[removed] — view removed comment

19

u/MurdoMaclachlan public boolean isInt(int i) { return true; } Jun 01 '21

You saw nothing

13

u/Ooze3d Jun 01 '21

I’m currently working with lots of dates and between formats and offsets, my code looks a little like this. I ended up storing it as a string that auto converts to date as it’s being entered in the database. Angular and Node kept going back and forth with the offset and I couldn’t find a stable way to do it.

11

u/Willinton06 Jun 01 '21

Yeah, he could have said DateTime.Now, the reason the new implementation works is because he’s not using UtcNow

3

u/[deleted] Jun 01 '21

Maybe they wanted to remove (floor) milliseconds?

3

u/Willinton06 Jun 01 '21

You can do AddMilliseconds(-DateTime.Now.Millisecond), 10 times more performant

3

u/dabombnl Jun 02 '21

No, you can't. The first call to DateTime.Now may have a different number of milliseconds than the second call for the number to subtract.

4

u/Willinton06 Jun 02 '21

My bad, just put the DateTime.Now in a variable like:

var now = DateTime.Now;
now = now.AddMilliSeconds(-now.MilliSeconds);

1

u/[deleted] Jun 01 '21

I know, just saying, that’s also something that this code is doing along with not explicitly being utc

5

u/lookaze Jun 01 '21

I hope they will come up with some better way to handle time was soon as there are a couple of people on Mars. I could deal with some interplanetary standard time before I start converting to local timezones which are only approximations based on where the local star is currently positioned

4

u/jarfil Jun 02 '21 edited Dec 02 '23

CENSORED

7

u/Cmgeodude Jun 01 '21

I see and understand that this is repetitive, bad code.

DateTimes really are the worst, though.

3

u/[deleted] Jun 01 '21 edited Jun 01 '21

I once had to spend an hour arguing with someone that the logs do UTC by default so the timestamp is in-fact current and not old by 7hrs like they thought it was.

Also who can tell if 2021-10-07 is actually the Seventh of October or the 10th of July ? 🤷‍♂️

3

u/Return-foo Jun 01 '21

My boss told me that he wanted all possible date time formats that we were scrapping from the web converted to our standard. Boy oh boy that was not fun times.

1

u/[deleted] Jun 03 '21

That’s just evil 😮

3

u/KaiserMazoku Jun 02 '21

DateTimes are always annoying, especially in Javascript when you forget to offset the month by 1.

2

u/Giocri Jun 01 '21

I still have nightmares from when I had to make a parser for an api that didn't respect the datetime format said on the documentation.

8 different date time format from the same api 7 of which undocumented and we had to find out from reading the raw json coming in.

1

u/DogmaSychroniser Jun 02 '21

I just vomited a little

2

u/ign1fy Jun 01 '21

The C# DateTime lib is the best I've worked with (C, Java and JS suck at it). However, I did have to write my own function to truncate a timestamp to the nearest second. It was much cleaner than this example.

2

u/[deleted] Jun 02 '21

I don’t know why it’s written this way, but I can probably come up with a few valid guesses.

DateTimes are the absolute worst in so many ways and have absolutely bizarre behavior.

1

u/wischichr Jun 02 '21

You should try NodaTime.

1

u/DogmaSychroniser Jun 02 '21

The worst part is the string format there will interpolate months and minutes.

0

u/ghillisuit95 Jun 01 '21

I feel like everyone is missing the fact that this is a function called ApiResult() and for some reason it is assigning to what appears to be a global variable and that is it. That is not at all what I would expect a function called ApiResult() to do.

8

u/aaaantoine Jun 01 '21

It's a constructor for a class named ApiResult. The "global variable" is potentially a read-only property (that can be set only during construction).

3

u/ghillisuit95 Jun 01 '21

Ooohh. Okay, I take back my judgement

0

u/PFthroaway Jun 01 '21

DateTimeOffset is much better to use. It may not give you the specific time zone, but you know when it was, which is really all that matters.

0

u/XDracam Jun 01 '21

At least it's almost r/ISO8601

0

u/NikkoTheGreeko Jun 02 '21

Let's be fair, dates and times are ridiculously difficult.

https://youtu.be/qabriMQ1SYs

0

u/_hoyet Jun 02 '21

I'm assuming the Convert class is able to be mocked in tests. This is probably solid code, with context.