.NET Date Const (with Globalization) - vb.net

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.

Related

.NET Date variable specification & locale

I set the date variable
Dim myDate as Date
myDate = #5/15/2013#
Does this work always at runtime, no matter what is the system locale settings?
According to the MSDN 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.
The reason for this restriction is that the meaning of your code should never change depending on the locale in which your application is running. Suppose you hard-code a Date literal of #3/4/1998# and intend it to mean March 4, 1998. In a locale that uses mm/dd/yyyy, 3/4/1998 compiles as you intend. But suppose you deploy your application in many countries. In a locale that uses dd/mm/yyyy, your hard-coded literal would compile to April 3, 1998. In a locale that uses yyyy/mm/dd, the literal would be invalid (April 1998, 0003) and cause a compiler error.
So, the answer to your question is YES, it will always work at runtime, and NO, you do not need to change this for the locale settings of the computer.
Do keep in mind that date literals are somewhat frowned upon. They are supported in VB.Net as a backwards-familiarity thing from VB6. They don't even exist in other .Net languages like C#. If you have to hard-code a specific date, you are much better off using DateTime with separate parameters, such as:
Dim myDate as DateTime
myDate = new DateTime(2013,5,15)
Also note that Date is just a VB.Net alias to System.DateTime, again there for backwards familiarity from VB6. It doesn't matter which you use, they mean the same thing.
No, that does not work in a country such as Canada where the standard is dd/MM/yyyy. The best way to globalize your application would be to use DateTime.ParseExact and/or DateTime.TryParseExact
Dim tempdate As DateTime
tempdate = DateTime.ParseExact("05/20/2013", "MM/dd/yyyy", Globalization.CultureInfo.InvariantCulture)

Date.parse function error

i am using the date.parse function to format the date input in the textbox.
However if I input a future date the date parse function fails.
Why is it so?
I need to format the date and also input future dates.
If IsDate(TransactionDate.Text) Then
TransactionDate.Text = Date.Parse(TransactionDate.Text)
Else
MsgBox("Enter correct Transaction date")
TransactionDate.Focus()
End If
i used 12/5/2013 and it worked fine.
I suspect it didn't, actually. I suspect it actually parsed it as December 5th 2013, when you meant May 12th 2013.
It seems that it's trying to parse it as a format of MM/dd/yyyy, whereas you mean dd/MM/yyyy.
That could be because the thread you're using is in a US culture, for example.
I suggest that you use DateTime.TryParseExact:
If you want to specify a precise format, you can do that using a custom date/time format pattern
If you want to allow .NET to use an appropriate format for the culture, you can do that using a standard date/time format pattern
Specify the culture you want to use for parsing, using CultureInfo.InvariantCulture if it's meant to parse machine-generated text. You can use null to mean "the culture of the currently executing thread" but personally I'd make that explicit, for readability
Use the return value to determine whether parsing failed. If this indicates a bug somewhere, then it would make sense to use DateTime.ParseExact instead, as that will throw an exception. Basically you need to work out what you want to do on error.
You need to specify the format you are expecting the data string to be in. Dates can be written in many formats - US (mm/dd/yyyy) or European (dd/mm/yyyy), two digit years (yy) or four digit years (yyyy), different separator (/) vs (-) and so on. The list is endless.
You either need to state explicitly what date you expect or write your code to try various formats and cope with incorrect inputs.
The danger with the latter approach is that dates can be ambiguous - is "1/2/2013" the 1st of February or the 2nd of January?
Use an overload of Date.TryParse that takes an IFormatProvider and report an error if it fails.
dateString = "2008-03-01 10:00"
culture = CultureInfo.CreateSpecificCulture("fr-FR")
styles = DateTimeStyles.AdjustToUniversal Or DateTimeStyles.AssumeLocal
If DateTime.TryParse(dateString, culture, styles, dateResult)
Console.WriteLine("{0} converted to {1} {2}.", _
dateString, dateResult, dateResult.Kind)
Else
Console.WriteLine("Unable to convert {0} to a date and time.", dateString)
End If
Use DateTime.ParseExact and pass the format and provide.
dateString = "13/05/2013";
format = "dd-MM-yyyy";
CultureInfo provider = CultureInfo.InvariantCulture;
var result = DateTime.ParseExact(dateString, format, provider);

DateTime.Date (long value)

I have spent quite a few hours and still unable to understand this:
Dim unix_time_at_midnight As Long
DateTime.DateFormat = "MM/dd/yyyy"
unix_time_at_midnight = DateTime.DateParse(DateTime.Date(unix_time*1000))/1000
where both unix_time_at_midnight and unix_time are long values. I understand DateTime.DateParse excepts a String and converts it to DateTime. What is (DateTime.Date(unix_time*1000))/1000 returning and what is its equivalent in Java? The requirement is to get the number of seconds since GMT midnight and I have successfully implemented it in Java. However, I would like to understand this particular line of code written in VB.net
EDIT: This method was written in Basic4Android and probably constitutes more of its libraries then vb.net. However, I have looked into each for details but unable to understand. Would appreciate if you could elaborate. Please see the links.
Take this:
DateTime.Date(unix_time*1000)
The documentation says:
Date (Ticks As Long) As String
Returns a string representation of the date (which is stored as ticks).
The date format can be set with the DateFormat keyword.
So that part returns a string representing the date.
It then uses DateTime.DateParse, which is documented as:
DateParse (Date As String) As Long
Parses the given date string and returns its ticks representation.
Taken together, this appears to take the ticks, multiplied by 1000, converted to a string that doesn't contain hour information which is parsed back to ticks which are divided by 1000.
The important thing to note is that the DateFormat set on the line before contains only the formatting for the date, no hours/minutes/seconds and smaller units of time exist in it. This means that the string returned essentially represents midnight of that date.

How to change Time Format in VB.NET from 24 to 12?

I am using these codes for displaying time in VB.NET
it shows up in 24 hours format besides i need it in 12 hours format
System.DateTime.Now.Hour
System.DateTime.Now.Minute
System.DateTime.Now.Second
example:
14:12:42
I need it as :
02:12:42
thanks.
Use String.Format. For example:
String.Format("{0:T}", System.DateTime.Now) //02:12:42 PM
String.Format("{0:hh:mm:ss}", System.DateTime.Now) //02:12:42
String.Format("{0:hh:mm:ss tt}", System.DateTime.Now) //02:12:42 PM
Also, this website to be very helpful in summarizing the various ways you can use String.Format. Keep in mind the culture can make a difference on non-custom formats. The first example above using T (Long Time format) works on my US-based PC just fine. But if you say:
String.Format(System.Globalization.CultureInfo.InvariantCulture, _
"{0:T}", System.DateTime.Now)
You end up with 14:12:42. The latter two examples are custom formats and are not affected by culture.
When using DateTime objects you can actually use the ToString() method and set your format inside it.
string currentTime = System.DateTime.Now.ToString("hh:mm:ss");
Check this msdn article out for more clarity:
http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx
Use the appropriate format string for display.
string formatted = myDateTime.ToString("hh:mm:ss");
I have used a custom format string in this case.
1-Use regex to get first two characters of that string ie from 23:11:59 get 23
2-convert this number to integer type
3-now check it if it is not greater than 12 and if it is subtract 12 from it and by using string.replace replace the old value.
Try This...
Dim CurTime As String
CurTime = TimeOfDay.ToString("h:mm:ss tt")

Visual basic script that control a date format

I would like to control a string if is in the dd/mm/yyyy format and if the dd number is between 1 and 31 and if mm is between 1 and 12.
In vb.net you can use the IsDate() function to test the validity of a date. This will insure that the day and the month are within the valid range.
You can use the DatePart function:
DatePart("m", date)
DatePart("d", date)
Wait what? Your question is not very clear. Do you have a DateTime and need to output it in a specific format? Are you accepting a string from the user and need to make sure it fits that format? Do you get a string from somewhere else that you need to match for a specific format?
Most of all, why do you care? You shouldn't be dealing with dates as strings, except at the point of interaction with the user or other data source. Inside your program they should be a DateTime type. Assuming you're 'vb.net' tag is correct, the DateTime has handy Parse, TryParse, and ParseExact, and TryParseExact static methods you can use to accept most anything the user could throw at you.