Great analysis, Scott! The first thing that I noticed when saw this originally was that even if they had gotten the DateTime string conversions correct, it would only be 2022 for 1 second. The comparison should have been >=, not ==. I honestly hadn't even considered your other bullet points because that one struck me so hard. LOL
yeah i thought I just missed hearing Scott say this, but I dont think so. He even mentions that using exact new datetime without time parts would give only midnight value. I don't now, maybe just missing an acute angle
I'm fairly certain that `>=` would not work either since in the en-US culture the format is either MM/dd/yyyy or maybe M/d/yy, but in either case "10/01/2010" > "01/01/2022" when done with string comparison rather than date comparison.
I discovered your channel today and I'm so glad I did! You're voice is so relaxing and you explain everything in such detail. You're like the Bob Ross of coding.
I don't see another flaw mentioned - the else will display "it's still 2021" even when it's 2022 already. But yes, sad when marketing people take over, and thanks for the video!
Great video Scott! There is another issue with the original string. You pointed out the leading zero day/month month/day issues, but the time component is also very different and incompatible. Because your culture settings are set to use a 12-hour clock, there is no such thing as 00:00:00 as it would be 12:00:00 AM in your case. The fixes you mentioned obviously still apply, but it's worth pointing out that your solution of instantiating a new date saves you having to deal with the time, avoiding the problem altogether. Always solve the smallest problem possible 😉
Hey Scott, great short video about common misuses in C#, i would appreciate more of that. We all got burned on such things as beginners. My favourite one is , vs . as decimal separator in different cultures :)
Couple of other observations. Line 1 is trying to compare (with your culture setting) a 12 hour clock time and a 24 hour clock time. Also, unless you get lucky, the comparison might not happen at midnight exactly (strictly, with the format you have, between midnight and midnight plus one second) so you might never get the HNY message. The code could continue to output that it is 2021 whenever it is run. Despite it being 2022.
This was really helpful! Thanks! I'm an visual designer who's trying to start coding my own apps and this was the ureka moment for me to understand datetime! Thanks again cause I was really struggling to grasp how I should use it.
I can't believe you didn't mention the missing block of code 'You you = new You()' as having a new You is essential to any New Year function.... :) Love the content as always!
Someone out there is taking this as a personal challenge to change the regional settings in their OS to disprove Scott's "this will NEVER work" statement...
I love your customized prompts, fonts, etc. However, it is sometimes difficult to determine if it is the font ligatures or not when something looks wrong. For example, your "==" turns into a single, longer equal sign. Maybe your font also converted the ellipsis into a special ligature. I wouldn't fault anyone for not picking that out in your screenshot.
Great video! I personally hate DateTime comparisons and watched this to confirm I’m doing it right. A while ago I was working on software which incorrectly compared DateTime.Now to a UTC DateTime obtained via a REST service. So I think these types of issues are pretty common!
Thank you for turning this into a positive learning experience. I hope the aforementioned marketeer is making out okay - there are a lot of layers here even for "experienced" devs to trip up on.
Scott, the illustration of the Ellipsis cut and paste from Microsoft Word I have seen too many times from users; if user input is not cleansed prior to saving to database or other string processing operations, this can lead to hours of head scratching grief trying to solve wacky software behaviors caused by such input.
Woah. Missed the biggest logic bug. If it's not EXACTLY midnight, it says it's 2021. 12:01? It's 2021. Jan 3? 2021... I would just look at the year component of the datetime and check if it's >2021
@@shanselman OK, I watched again up to 9:17 when I thought you were going to finally point it out the first time I watched. Instead you're talking about the ellipsis and the escaped apostrophe. You jumped right into date string comparisons and date formats. I didnt see you point out the fallacy of comparing an exact time (and assuming if it's not midnight on the first, it must be last year) in the first place. Could you point out the timestamp where you cover that?
@@SarevansVoyage depends on the goal/plan for the software. If it's to be decommissioned sometime in January, then it could be fine. if not, we don't know what the intended behavior is. We've only got 2 cases defined. Given the 2 cases, the year check is certainly more correct than checking for that instant.
One other thing worth mentioning is that there are a couple of acceptable formats for representing datetimes on the wire (when in network transit, as opposed to in application memory). Unix epoch integer has been widely considered to be the standard for many years, but is starting to cede dominance to either 1900 integer (*shudder*) or ISO 8601 UTC string representation. None of these formats are perfect, and if your implementation provides a method for proper serialization, it's highly preferable to use that rather than roll your own, largely due to exactly the issues in the video.
Hi Scott, I am very new to the channel (this is my second video). This was a great video. I am new to the .NET ecosystem as a developer. Although you mentioned it a little, I would love to see "corrected" source code that takes care of all those implicit inputs you mentioned and "works" in all localizations and timezones.
Current culture can also effect what we see whether 1/3 is a month/day or day/month... either of which is entirely valid, depending on the cutlure, but probably not what was intended if we meant January versus March.
The whole aspect of internationalization is fascinating. I remember back n the mid 90s when Windows NT adopted Unicode and listening to a presentation by Nadine Kano in this topic. The intricacies are incredible!
The code could have intentionally included bugs to compel the Twitter community to engage with the tweet, criticize it, etc, and get it retweeted. After all, it was for marketing purposes, not to actually be executed.
Another point is to focus on the thing you actually care about. Do we care that it's January? Do we care that it's the first? Do we care that it's midnight? No, that's irrelevant. As the else WriteLine shows we only care about the year so focus on that. DateTime.Now.Year >= 2022.
And when using 12 hour clock, you have the 8 possible am/pm formats also: AM/am/A.M./a.m. and PM/pm/P.M./p.m. I had an issue recently also where an update to Windows 10 changed the date/time format strings it uses for different time zones so some old code I inherited broke because the default am/pm format for a particular timezone had changed!
😣 I couldn't get more than two minutes into this before tapping out; triggered by "lizard brain" memories of past DateTime debacles... usually manifesting as PagerDuty alerts at ungodly hours PST.
@@r7boatguy Exchange tried to store "2201010001" (date time '22-01-01 00:00) in a 32-bit signed integer, and yes, it overflowed. Still, it was directly related to dates and times.
Jajajaja buen analisis lo que llegue a captar... captar el ingles hablado me cuesta pero no me rindo jajajjaj... que linda personalización de Windows que tienes...es win 11?...saludos desde Argentina
I did not know you can run such a minimalistic C# file. Also what software do you use to record your screen? It is very nice to add those lines and boxes.
6:41 In fact, this would work in some cultures. In Brazil, dates are represented with leading zeros. So, if your culture was set to pt-BR, it would work. But I agree that dates should not be treated as strings.
Yep its bad code before I hear scott explain why its bad I think one thing is the date format of to string defaults it to what ever the format is used on the computer so if the format is different it not gonna work. One of the many things wrong with it but i'm pretty sure scott covers all of it.
Great talk, and excellent overview :) Might even be one more little problem? It is assuming the person is only running it before 2022? Anytime after midnight (if it ever possibly worked given your system culture setting matched...) it will be incorrectly saying it is still 2021. Heheh don't get me wrong, the older i get if we could freeze time so we don't age any more :) Might suggest this is a great example why teams should agree on standardizing on using extension methods for company-wide data handling. Given this is for people at all levels, really think for those starting out consider the following if it wouldn't make things better? // blah blah blah, nothing really new... DateTime dt1 = DateTime.Now; DateTime dt2 = DateTime.UtcNow; // Now for the goodness... if( dt1.CompareDate(d2)) // only date portion if( dt1.Compare(d2)) // Full date && time, less ms? if( dt1.CompareDateTime(dt2)) // another variant of the previous if( dt1.Compare(d2, DateTimeCompareOptions.DateOnlyTimeStirict) // compare without normalizing locals if( dt1.Compare(d2, DateTimeCompareOptions.DateOnlyTimeLax) // convert the date to the same local then compare So with these helpers, it will localize all your code for handing data equality, and help indicate exactly how things get compared. For example the last two, what would "Lax"or "Strict" imply? Lax would possibly try normalizing the dates to the same local/timezone and then compare dt.year == dt2.year and the rest of the date portion while the "Strict" compare without attempting to normalize the local. Either way, would assert anyone using this would know the exact behavior and in the end improve the code quality. Could be extended to string or Custom object as there will be one set of routines for comparing data per the "global business rules"... Anyway just a thought/suggestion for those just starting out. Wonder over my career before extension methods i wrote: if( str1.Compare(str2, StringComparison.OrdinalIgnoreCase)) with extension methods now: if( str.StrCompare(str2)) And project wide so all the developers will have a standard/good understand of exactly what is going on. And if we need to enforce case sensitivity, change the one extension method.... Done!
my impostor syndrome is getting worsen after seeing those tweet. I remember when I post an open issue in some github repo then it turned to be a joke. I was fine with those but since then I never write someone else github issue again.
As long as the ticks value was derived from a DateTime or DateTimeOffset that was in the same timezone as the one you're comparing against, I feel comparing the ticks values should be safe.
Hey, Scott! Great analysis, as always. I'm in the process of learning C# so this helps a lot. I have a question related to dates: isn't it more efficient to store dates as unix timestamps? UT is interpreted the same regardless of region, and is calculated from the same point in time regardless of time zone. What would be the caveats of using unix timestamps instead of ISO 8601?
I don't work with Unix timestamps too often, but it's probably fine to store it like that as long as you don't use the 32-bit timestamp, as in 2038 the number of digits will not be sufficient to represent a date after 2038 (look up the Year 2038 problem). Also, Unix timestamps have no way of specifying a time zone, so if that is important to you, you will have to store this information elsewhere. ISO 8601 allows for specifying an optional timezone with the date and time string. Another advantage is that an ISO 8601 string is pretty much human readable, whereas a Unix timestamp is just a bunch of numbers that a human can't usually decipher into a usable time string without code or a conversion tool. As far as efficiency is concerned, it really depends on how you're storing the data in the first place. If you're writing (serializing) the date data to a string into a JSON file for example, whatever is shorter between the Unix timestamp and the ISO 8601 string will be more space efficient. If we're talking about memory efficiency, I have no idea how .NET internally stores the date data in memory; that's probably something Scott can answer to.
It largely depends on where you are storing them. If you are storing it in a binary form like in a database or a custom binary file then the UNIX timestamp 64-bit format is probably the way to do it. Only computers will be reading those dates so it doesn't matter what they look like. If you are storing text in an xml, json or config file then you'll want to use the ISO format because it's a text format. It also clearly looks like a date and time string so that'll be clearer to anyone or any tools reading those files. It's also easier if someone wants to manually edit those files.
Am I the only one which see that Scott made mistake in his presentation? He advice to compare DateTime.Now == new DateTime(2002, 1, 1) which also will not work as we are in year 2022. :-)
If you wanted to compare strings, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") == "01/01/2022 00:00:00" but if you wanted to compare raw dates, the value equality is based on the Ticks of the DateTime object, so if(DateTime.Now == new DateTime(2022, 1, 1)) should do it. Timezones are irrelevant to ticks. So long as both values have the same Year, Month, Day ... Milliseconds, then the ticks should be the same.
@@DaveRogersEsq Thanks for the answer. A new question came to my mind. How often should the program we write perform this date check (if(DateTime.Now == new DateTime(2002,1,1))? Should the program perform this check every millisecond? What if the date changes until the program is executed?
@@cenkakay3506 I'd never do a check exactly like that. This was just a bit of code for marketing purposes. If you did have a service which was triggered to do something at a point in time, the best way to do it before .NET core would be to hook into a WMI event. You'd have to research whether that is possible with .NET Core or whether some replacement has been built into the framework. The BackgroundWorker services stuff is also pretty good as it lets you fire the logic at a specified interval, whether it be every second or less. You can check whether the "time of interest" has passed on each run. But I'd use < or > rather than equality.
"This worked in TEST but not in PROD, the databases must be different". Nope. The regional settings were different. Be explicit. Another issue I see. where record_date
Great analysis, Scott! The first thing that I noticed when saw this originally was that even if they had gotten the DateTime string conversions correct, it would only be 2022 for 1 second. The comparison should have been >=, not ==. I honestly hadn't even considered your other bullet points because that one struck me so hard. LOL
The string comparison struck me first and then the fact that it was an exact comparison.
Yeah, I was also surprised he did not mention the ==. Nothing was correct about that code, lol
yeah i thought I just missed hearing Scott say this, but I dont think so. He even mentions that using exact new datetime without time parts would give only midnight value.
I don't now, maybe just missing an acute angle
I'm fairly certain that `>=` would not work either since in the en-US culture the format is either MM/dd/yyyy or maybe M/d/yy, but in either case "10/01/2010" > "01/01/2022" when done with string comparison rather than date comparison.
@@dionito70 they both strings and in c# you can use ==
And this is why Scott is who he is. He took a thing most of us simply mocked and made fun of and turned it into a teachable moment. Kudos Scott.
😍
Fun to see you "Exchange" information on how to parse dates correctly. :) The TIMING is perfect.
🤣
"Virtually everything with dates is hard" - truer words have never been spoken :)
Everything to do with dates, numbers and strings are hard (see Jon Skeet). Those also turn out to be our primitive types...
I discovered your channel today and I'm so glad I did! You're voice is so relaxing and you explain everything in such detail. You're like the Bob Ross of coding.
I don't see another flaw mentioned - the else will display "it's still 2021" even when it's 2022 already. But yes, sad when marketing people take over, and thanks for the video!
Great video Scott! There is another issue with the original string. You pointed out the leading zero day/month month/day issues, but the time component is also very different and incompatible. Because your culture settings are set to use a 12-hour clock, there is no such thing as 00:00:00 as it would be 12:00:00 AM in your case. The fixes you mentioned obviously still apply, but it's worth pointing out that your solution of instantiating a new date saves you having to deal with the time, avoiding the problem altogether. Always solve the smallest problem possible 😉
Scott for what it's worth... I've been coding for 25 plus years and I don't know if anyone could have explained this better. Well done!
Awesome as always .
You only get this kind of legend once .
I truly admire you Scott.
Always like hearing you talk about toy code examples. Thanks!
Hey Scott, great short video about common misuses in C#, i would appreciate more of that. We all got burned on such things as beginners. My favourite one is , vs . as decimal separator in different cultures :)
Couple of other observations. Line 1 is trying to compare (with your culture setting) a 12 hour clock time and a 24 hour clock time. Also, unless you get lucky, the comparison might not happen at midnight exactly (strictly, with the format you have, between midnight and midnight plus one second) so you might never get the HNY message. The code could continue to output that it is 2021 whenever it is run. Despite it being 2022.
This was really helpful! Thanks! I'm an visual designer who's trying to start coding my own apps and this was the ureka moment for me to understand datetime! Thanks again cause I was really struggling to grasp how I should use it.
Scott never disappoints. A long troll video with his soft voice. Liked that gif you shared on twitter for this tweet 👍
I can't believe you didn't mention the missing block of code 'You you = new You()' as having a new You is essential to any New Year function.... :) Love the content as always!
Thank you for a great explanation. Also, thanks for zooming in on your code, so it is easy to view.
More great content for .NET newbies, thanks Scott
Learned a heap from this analysis! Ty Scott
This should be the first lesson of the first hour in any programming course!
Also, the string conversion adds AM/PM to the end, so wouldn't have worked even with the proper ddmmyyyy. Great video!
My favorite tech instructor! Always delivering 😁
Someone out there is taking this as a personal challenge to change the regional settings in their OS to disprove Scott's "this will NEVER work" statement...
🥰
I love your customized prompts, fonts, etc. However, it is sometimes difficult to determine if it is the font ligatures or not when something looks wrong. For example, your "==" turns into a single, longer equal sign. Maybe your font also converted the ellipsis into a special ligature. I wouldn't fault anyone for not picking that out in your screenshot.
Great video! I personally hate DateTime comparisons and watched this to confirm I’m doing it right. A while ago I was working on software which incorrectly compared DateTime.Now to a UTC DateTime obtained via a REST service. So I think these types of issues are pretty common!
That == comparison is screaming to be replaced.
Thank you for turning this into a positive learning experience. I hope the aforementioned marketeer is making out okay - there are a lot of layers here even for "experienced" devs to trip up on.
I'm no expert on US timezones but I am surprised to see it's the first of March over there already
Happy new year Scott! I wish you and your family all the best for 22!
Scott, the illustration of the Ellipsis cut and paste from Microsoft Word I have seen too many times from users; if user input is not cleansed prior to saving to database or other string processing operations, this can lead to hours of head scratching grief trying to solve wacky software behaviors caused by such input.
Woah. Missed the biggest logic bug. If it's not EXACTLY midnight, it says it's 2021. 12:01? It's 2021. Jan 3? 2021...
I would just look at the year component of the datetime and check if it's >2021
Yes! I showed that first.
@@shanselman OK, I watched again up to 9:17 when I thought you were going to finally point it out the first time I watched. Instead you're talking about the ellipsis and the escaped apostrophe.
You jumped right into date string comparisons and date formats. I didnt see you point out the fallacy of comparing an exact time (and assuming if it's not midnight on the first, it must be last year) in the first place. Could you point out the timestamp where you cover that?
@@LiqdPT oops, my bad
Checking only year is also not correct. It will say happy new year during the whole year.
@@SarevansVoyage depends on the goal/plan for the software. If it's to be decommissioned sometime in January, then it could be fine. if not, we don't know what the intended behavior is. We've only got 2 cases defined.
Given the 2 cases, the year check is certainly more correct than checking for that instant.
One other thing worth mentioning is that there are a couple of acceptable formats for representing datetimes on the wire (when in network transit, as opposed to in application memory). Unix epoch integer has been widely considered to be the standard for many years, but is starting to cede dominance to either 1900 integer (*shudder*) or ISO 8601 UTC string representation. None of these formats are perfect, and if your implementation provides a method for proper serialization, it's highly preferable to use that rather than roll your own, largely due to exactly the issues in the video.
Hi Scott, I am very new to the channel (this is my second video). This was a great video. I am new to the .NET ecosystem as a developer. Although you mentioned it a little, I would love to see "corrected" source code that takes care of all those implicit inputs you mentioned and "works" in all localizations and timezones.
You should take a stab at writing it, based on what you have learned. :)
Yes... try to write it and post it here. I'm sure there are some around that would critique it.
Current culture can also effect what we see whether 1/3 is a month/day or day/month... either of which is entirely valid, depending on the cutlure, but probably not what was intended if we meant January versus March.
The whole aspect of internationalization is fascinating. I remember back n the mid 90s when Windows NT adopted Unicode and listening to a presentation by Nadine Kano in this topic. The intricacies are incredible!
The code could have intentionally included bugs to compel the Twitter community to engage with the tweet, criticize it, etc, and get it retweeted. After all, it was for marketing purposes, not to actually be executed.
Another point is to focus on the thing you actually care about. Do we care that it's January? Do we care that it's the first? Do we care that it's midnight? No, that's irrelevant. As the else WriteLine shows we only care about the year so focus on that. DateTime.Now.Year >= 2022.
And when using 12 hour clock, you have the 8 possible am/pm formats also: AM/am/A.M./a.m. and PM/pm/P.M./p.m.
I had an issue recently also where an update to Windows 10 changed the date/time format strings it uses for different time zones so some old code I inherited broke because the default am/pm format for a particular timezone had changed!
says "Dates are a data type"
writes "Dates are a date type"
I found that funny since it's a video explaining a mistake lol
fun watch all around, and I'm kinda shocked y2k2 wasn't even mentioned, good show... but boy, "implicit input" the horror! brrr...
Thanks for sharing, Scott. Maybe I missed it, but did you address the use of the "is equal to" conditional operator?
Very informative. Thank you :)
😣 I couldn't get more than two minutes into this before tapping out; triggered by "lizard brain" memories of past DateTime debacles... usually manifesting as PagerDuty alerts at ungodly hours PST.
One of the first things I do on every machine is turn off smart ellipses, dashes, and quotes.
Fishing day nice catch
When I saw the title of this video, I wasn't sure if you were going to talk about Tinder vs Harmony, or what. :)
Elipses depending on whether the target viewer renders correctly...
The result can be 01/01/2022, it depends on the regional configuration that we have in the control panel, which can be M / dd / yyyy or MM / dd / yyyy
DateTime.Now.ToString actually has an overload that let's you specify the format.
Forward this video to Microsoft Exchange Server team, Scott. Oh, wait! It will not be delivered ☹️
Their issue wasn't dates and times, it was integer overflow!
@@r7boatguy Exchange tried to store "2201010001" (date time '22-01-01 00:00) in a 32-bit signed integer, and yes, it overflowed. Still, it was directly related to dates and times.
When the senior developer fix stuff from a junior developer
Amazing. another method will be included in the library.
Jajajaja buen analisis lo que llegue a captar... captar el ingles hablado me cuesta pero no me rindo jajajjaj... que linda personalización de Windows que tienes...es win 11?...saludos desde Argentina
So when I handwrite a date and forget that it's now 2022, it is actually this code that my brain is processing!
Thanks for this!
I ISO-8601 all my dates in web apps I create. I've never had a complaint from anyone in Europe, APAC, or North America.
I did not know you can run such a minimalistic C# file. Also what software do you use to record your screen? It is very nice to add those lines and boxes.
That's .NET 6 and ZoomIt!
Excellent reminder! We don't get enough of them. Also, is that the new notepad? Looks awesome 😊
I assume you're kidding. But if not, looks like Visual Studio (some preview version) going by the icon in the left of the title bar.
Hi, great video for beginners like me , Plz do more of these , concise and useful 🙏🏻
who needs vs2022, when we have microsoft word!
Big like! I wonder if Javascript running in the browsers is also affected by OS culture.
A way to get Scott's attention.
6:41 In fact, this would work in some cultures. In Brazil, dates are represented with leading zeros. So, if your culture was set to pt-BR, it would work. But I agree that dates should not be treated as strings.
>= instead of == would also have been better owing to the contents of 'else'
Yep its bad code before I hear scott explain why its bad I think one thing is the date format of to string defaults it to what ever the format is used on the computer so if the format is different it not gonna work. One of the many things wrong with it but i'm pretty sure scott covers all of it.
I'm sure the ad guy/gal/them that wrote the code loves that he triggered a whole discussion including a play by play breakdown by Scott Hanselman!! 😂😁
Great talk, and excellent overview :) Might even be one more little problem? It is assuming the person is only running it before 2022? Anytime after midnight (if it ever possibly worked given your system culture setting matched...) it will be incorrectly saying it is still 2021. Heheh don't get me wrong, the older i get if we could freeze time so we don't age any more :)
Might suggest this is a great example why teams should agree on standardizing on using extension methods for company-wide data handling. Given this is for people at all levels, really think for those starting out consider the following if it wouldn't make things better?
// blah blah blah, nothing really new...
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.UtcNow;
// Now for the goodness...
if( dt1.CompareDate(d2)) // only date portion
if( dt1.Compare(d2)) // Full date && time, less ms?
if( dt1.CompareDateTime(dt2)) // another variant of the previous
if( dt1.Compare(d2, DateTimeCompareOptions.DateOnlyTimeStirict) // compare without normalizing locals
if( dt1.Compare(d2, DateTimeCompareOptions.DateOnlyTimeLax) // convert the date to the same local then compare
So with these helpers, it will localize all your code for handing data equality, and help indicate exactly how things get compared. For example the last two, what would "Lax"or "Strict" imply? Lax would possibly try normalizing the dates to the same local/timezone and then compare dt.year == dt2.year and the rest of the date portion while the "Strict" compare without attempting to normalize the local. Either way, would assert anyone using this would know the exact behavior and in the end improve the code quality. Could be extended to string or Custom object as there will be one set of routines for comparing data per the "global business rules"...
Anyway just a thought/suggestion for those just starting out. Wonder over my career before extension methods i wrote:
if( str1.Compare(str2, StringComparison.OrdinalIgnoreCase))
with extension methods now:
if( str.StrCompare(str2))
And project wide so all the developers will have a standard/good understand of exactly what is going on. And if we need to enforce case sensitivity, change the one extension method.... Done!
my impostor syndrome is getting worsen after seeing those tweet. I remember when I post an open issue in some github repo then it turned to be a joke. I was fine with those but since then I never write someone else github issue again.
You forgot about the fact that the earth is in three dates for a whole hour every day when giving datetime examples! 😫
awesome video...
"Never compare Dates as ints". But...but...we have Ticks from the DateTime class?
As long as the ticks value was derived from a DateTime or DateTimeOffset that was in the same timezone as the one you're comparing against, I feel comparing the ticks values should be safe.
And you never even mentioned AM/PM :-)
DATEing is never easy, things are never really what they are on face value
Hey, Scott! Great analysis, as always. I'm in the process of learning C# so this helps a lot. I have a question related to dates: isn't it more efficient to store dates as unix timestamps? UT is interpreted the same regardless of region, and is calculated from the same point in time regardless of time zone. What would be the caveats of using unix timestamps instead of ISO 8601?
I don't work with Unix timestamps too often, but it's probably fine to store it like that as long as you don't use the 32-bit timestamp, as in 2038 the number of digits will not be sufficient to represent a date after 2038 (look up the Year 2038 problem). Also, Unix timestamps have no way of specifying a time zone, so if that is important to you, you will have to store this information elsewhere. ISO 8601 allows for specifying an optional timezone with the date and time string. Another advantage is that an ISO 8601 string is pretty much human readable, whereas a Unix timestamp is just a bunch of numbers that a human can't usually decipher into a usable time string without code or a conversion tool.
As far as efficiency is concerned, it really depends on how you're storing the data in the first place. If you're writing (serializing) the date data to a string into a JSON file for example, whatever is shorter between the Unix timestamp and the ISO 8601 string will be more space efficient. If we're talking about memory efficiency, I have no idea how .NET internally stores the date data in memory; that's probably something Scott can answer to.
It largely depends on where you are storing them. If you are storing it in a binary form like in a database or a custom binary file then the UNIX timestamp 64-bit format is probably the way to do it. Only computers will be reading those dates so it doesn't matter what they look like. If you are storing text in an xml, json or config file then you'll want to use the ISO format because it's a text format. It also clearly looks like a date and time string so that'll be clearer to anyone or any tools reading those files. It's also easier if someone wants to manually edit those files.
What's the best practice for sending dates in a REST API?
a bit hard even have timeonly , date only in .net core 6
I would think ISO 8601 would be safe, possibly in UTC as well. Just document :)
Another vote for ISO 8601
Am I the only one which see that Scott made mistake in his presentation? He advice to compare DateTime.Now == new DateTime(2002, 1, 1) which also will not work as we are in year 2022. :-)
Ha ha. I see this post on Facebook too. Probably not what the authors intended.
But what about the correct way?
If you wanted to compare strings, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") == "01/01/2022 00:00:00" but if you wanted to compare raw dates, the value equality is based on the Ticks of the DateTime object, so if(DateTime.Now == new DateTime(2022, 1, 1)) should do it. Timezones are irrelevant to ticks. So long as both values have the same Year, Month, Day ... Milliseconds, then the ticks should be the same.
@@DaveRogersEsq Thanks for the answer. A new question came to my mind. How often should the program we write perform this date check (if(DateTime.Now == new DateTime(2002,1,1))? Should the program perform this check every millisecond? What if the date changes until the program is executed?
@@cenkakay3506 I'd never do a check exactly like that. This was just a bit of code for marketing purposes. If you did have a service which was triggered to do something at a point in time, the best way to do it before .NET core would be to hook into a WMI event. You'd have to research whether that is possible with .NET Core or whether some replacement has been built into the framework. The BackgroundWorker services stuff is also pretty good as it lets you fire the logic at a specified interval, whether it be every second or less. You can check whether the "time of interest" has passed on each run. But I'd use < or > rather than equality.
"This worked in TEST but not in PROD, the databases must be different". Nope. The regional settings were different. Be explicit.
Another issue I see. where record_date
I remember getting time in epoch format in C# is so unnecessary verbose
Just make an extension method on DateTime, that way you only have to write the logic once.
So, you're telling me MS Word has a bug... ;-)
if (DateTime.Today.Year == 2022)
Word as your IDE ... LOL
So glad the channel has been monetized... commercials so annoying.
I still can't surpass 4:44:44, coincidence I think not
total coincidence! I was shocked!
@@shanselman I'm not joking after I saw this, I went to like the video and it was 443 and I become the 444th, I'm panicking
The comparison can be done elegantly with property pattern: if (DateTime.Now is { Year:2022, Month:1, Day:1 })
what do you know, I could be working for Microsoft! 🤣
Just learn the api in other words
a piece of advice to Programmers having trouble with Dates. get your hair fix, brush your teeth, you might get a good one. Cheers! 2022!