Why does an uninitialised DateTime struct tell me it's monday - vb.net

I have a DateTime struct I use, and sombody commented out the part where it was created (but not declared) When I was using it, myDate.DayOfWeek == DayOfWeek.Monday returned true.
If the part where it is created is commented out, how can it tell me it's monday, instead of throwing some exception?

DateTime is a value type (a struct), and therefore it always has a value. It cannot be null like a reference type. When a variable of a value type is not assigned yet, it's initialized to some default value depending on the type. The default value for DateTime just happens to be a Monday in the calendar .NET uses.
Of course, calendars have changed many times in the past and applying our current calendar more than a few hundred years into the past just doesn't work, but to .NET, it's a Monday.

DateTime is a struct which means that it has to have some sort of default value. The default value for DateTime is DateTime.MinValue, which is 1 January 0001, which was a monday.

Related

Fluent assertion to verify DateTime field is not empty

var dte = "2021-12-18T15:06:33.2677927Z"
dte.Should().
I want to check that this dte is not empty.
Currently I am using :
dte.Should().BeAfter(new DateTime());
From the example, your definition of an "empty" DateTime seems to be one different from the default value.
If you're looking for a more readable/idiomatic way to express that, I would go with
DateTime subject = MethodUnderTest();
subject.Should().NotBe(default);
For the general case, one cannot speak of an "empty" DateTime since even the default value is just the minimum representable valid datetime, namely 0001-01-01T00:00:00.
So all of these are identical.
DateTime.Parse("0001-01-01T00:00:00")
default(DateTime)
new DateTime()
DateTime.MinValue
DateTime.FromBinary(0)

If - Strange Behavior in Detecting Type

I discovered this strange behavior in VB.Net today in trying to work with nullable DateTime data. I am pulling a DateTime value out of an XML file for inserting into a database, and I want to allow for an empty value. So I thought I should use If to prevent casting errors:
Dim LastRun As DateTime? = _
If(rowData("LastRun") = "", Nothing, CType(rowData("LastRun"), DateTime))
It seems like this should return a value of Nothing in the case that the If is false, or a value of the date time from LastRun if the value is not blank. Instead, when the If condition returns false, I get a value of DateTime.MinValue, which causes an exception on insert to the database due to SQL DateTime underflow.
I was able to fix it by using DateTime? as the cast in the last parameter, but this behavior seems odd to me. The expected type is clearly DateTime? because that's the variable type. Also, the narrowest type that can allow for both possible result values is DateTime?, since it could be either a DateTime or Nothing. And yet somehow it decides that the result value should be DateTime and then I guess typecasts Nothing to DateTime.MinValue? What is going on here?
Part of the problem is I'm used to C#, and the equivalent expression rowData["LastRun"] == "" ? null : (DateTime)rowData["LastRun"]) doesn't even compile (as expected), because there's "no implicit conversion between DateTime and null."
Nothing is not the same as null in C#, it is a mixture between null and default(T). So when you use Nothing on a value type(like the structure DateTime) you get it's default value what is DateTime.MinValue.

InvalidCastException when parsing dates in VB.NET

I'm trying to Parse dates entered into a TextBox into a DateTime value but I keep getting an exception in the TryParseExact method. What I'm trying to do is:
DateTime.TryParseExact(tbAddDate.Text.Trim, "yyMMdd", New CultureInfo("sv-SE"), DateTimeStyles.None, row.Date)
This throws an InvalidCastException with the message "Conversion from type 'DBNull' to type 'Date' is not valid." I realize what is happening is that it's trying to set row.Date to DBNull which is not a valid value for a DateTime. What I don't understand is why it's trying to do this, as the documentation states that it should be set to MinValue and not DBNull.
As a sidenote, I know that I can get around a lot of these problems by using a DateTimePicker but the customer feels that they are very clunky as it's not possible to enter the dates directly with the keyboard.
It seems that (as magnifico's comment suggests) the problem is strictly related to the fact you're passing row.Date as the result argument. It must occur when the code attempts to assign row.Date with Date.MinValue (unless the documentation is inaccurate, which is less likely in this scenario).
I'd advise that you pass some different result argument, and use its value to update row.Date after calling TryParseExact. It might not be the ultimate permanent solution, but it should help you inspect this bug and find the cause to the InvalidCast exception.
Sidenote: perhaps this row.Date doesn't accept Date.MinValue as a legitimate value, i.e.: row.Date might be willing to accept only dates from 01/01/2000 onwards, and Date.MinValue returns 01/01/0001.

How to apply formatting string when binding DateTime to MaskedTextBox?

I have a MaskedTextBox using the mask "00/00/\2\000" to restrict input to a format of XX/XX/20XX, with the Text property bound to MyBindingSource.SomeProperty of type DateTime.
Recently, values with a single-digit month or day recently started displaying incorrectly. I expect that the ToString() method is being called on the value at some point in data binding, and I believe the call is not padding month / day with zeroes.
I tried setting the format type of the MaskedTextBox.Text property to DateTime in the advanced data binding properties, but it didn't help.
How can I apply ToString("MMddyyyy") when converting the DateTime object to a string, before the value is bound to the Text property?
You can use the binding's Parse and Format events to do the conversion yourself, as seen in this answer

.NET Date Const (with Globalization)

Does anyone know of a way to declare a date constant that is compatible with international dates?
I've tried:
' not international compatible
public const ADate as Date = #12/31/04#
' breaking change if you have an optional parameter that defaults to this value
' because it isnt constant.
public shared readonly ADate As New Date(12, 31, 04)
If you look at the IL generated by the statement
public const ADate as Date = #12/31/04#
You'll see this:
.field public static initonly valuetype [mscorlib]System.DateTime ADate
.custom instance void [mscorlib]System.Runtime.CompilerServices.DateTimeConstantAttribute::.ctor(int64) = ( 01 00 00 C0 2F CE E2 BC C6 08 00 00 )
Notice that the DateTimeConstantAttribute is being initialized with a constructor that takes an int64 tick count. Since this tick count is being determined at complile time, it seems unlikely that any localization is coming into play when this value is initialized at runtime. My guess is that the error is with some other date handling in your code, not the const initialization.
According to the Microsoft documentation,
"You must enclose a Date literal within number signs (# #). You must specify the date value in the format M/d/yyyy, for example #5/31/1993#. This requirement is independent of your locale and your computer's date and time format settings."
Are you saying that this is not correct and the parsing is affected by the current locale?
Edit: Did you try with a 4-digit year?
Once you have data into Date objects in VB, you don't have to worry about globalization until you compare something to it or try to export it.
This is fine:
Dim FirstDate as Date = Date.UtcNow() 'or this: = NewDate (2008,09,10)'
Dim SecondDate as Date
SecondDate = FirstDate.AddDays(1)
This pulls in the globalization rules and prints in the current thread's culture format:
HeaderLabel.Text = SecondDate.ToString()
This is bad:
Dim BadDate as Date = CDate("2/20/2000")
Actually--even that is OK if you force CDate in that case to use the right culture (InvariantCulture):
Dim OkButBadPracticeDate as Date = CDate("2/20/2000", CultureInfo.InvariantCulture)
If you want to force everything to a particular culture, you need to set the executing thread culture and UI culture to the desired culture (en-US, invariant, etc.).
Make sure you aren't doing any work with dates as strings--make sure they are actual Date objects!
Ok right, I understand more where you are coming from..
How about:
Create a static method that returns the date constant. This overcomes the international issue since it is returned as the specific DateTime value.
Now I remember optional params from my VB6 days, but can you not just overload the method? If you are using the overloaded method without the date, just pull it from the static?
EDIT: If you are unsure what I mean and would like a code sample, just comment this post and I will chuck one on.
OK, I am unsure what you are trying to do here:
The code you are posting is NOT .NET, are you trying to port?
DateTime's cannot be declared as constants.
DateTime's are a data type, so once init'ed, the format that they were init'ed from is irrelevant.
If you need a constant value, then just create a method to always return the same DateTime.
For example:
public static DateTime SadDayForAll()
{
return new DateTime(2001, 09, 11);
}
Update
Where the hell are you getting all that from?!
There are differences between C# and VB.NET, and this highlights one of them.
Date is not a .NET data type - DateTime is.
It looks like you can create DateTime constants in VB.NET but there are limitations
The method was there to try and help you, since you cannot create a const from a variable (i.e. optional param). That doesn't even make sense.