I'm working in a web application using VB.NET. There is also VisualBasic code mixed in it, in particular the Date variable and the Month function of VB.
The problem is this part:
Month("10/01/2008")
On the servers, I get 10 (October) as the month (which is supposed to be correct). On my machine, I get 1 (January) (which is supposed to be wrong).
Two of my colleagues (on their own machines) get different answers, one got 1, the other got 10.
The question is, why is this so?
On my end, I can solve the problem by using .NET's DateTime's Parse (or ParseExact) function to force everything to be "dd/MM/yyyy" format. This works. I'm just wondering why there's an inconsistency.
Extra info: I know the parameter for Month function is supposed to be a Date variable. The code used a string as parameter, and Option Strict was off, and the developers mainly let VB do its own conversion thing. (Legacy code maintenance has a lot of inertia...)
If it helps, the version of Microsoft.VisualBasic.dll on the servers is 7.10.6310.4 (under the Framework folder v1.1.4322). The version on mine (and my 2 colleagues') machine is 7.10.6001.4.
Edit: Regional settings for all machines already set to dd/MM/yyyy format (short date format).
This normally has to do with the regional settings, and more specifically the date/time formats. If you set these formats so that they are all the same on the machines you're testing on, the results should be consistent.
Your idea of using ParseExact is definitely the better solution to go with, IMHO.
This is because the runtime has to convert your given value "10/01/2008" which is indeed a string implicitly to the DateTime datatype.
When converting strings to dates and the other way round, the string format depends on the locale settings of windows.
See this link on msdn.
In this article a way to specify a date literal which is independent of your locale settings:
Just enclose the date with the sign # and specify it in the form mm/dd/yyyy:
So the code
Month(#10/01/2008#)
should give you the answer 10 on any machine.
Ther a two more worarounds given in that msdn article:
1. Use the Format Function with predifned Date/Time Format
To convert a Date literal to the
format of your locale, or to a custom
format, supply the literal to the
Format Function, specifying either
Predefined Date/Time Formats (Format
Function) or User-Defined Date/Time
Formats (Format Function). The
following example demonstrates this.
MsgBox("The formatted date is " &
Format(#5/31/1993#, "dddd, d MMM
yyyy"))
2. Use the DateTime-Class Constructor to construt the right DateTime value
Alternatively, you can use one of the
overloaded constructors of the
DateTime structure to assemble a date
and time value. The following example
creates a value to represent May 31,
1993 at 12:14 in the afternoon.
Dim dateInMay As New
System.DateTime(1993, 5, 31, 12, 14,
0)
Related
I'm working with data in t-SQL and in order to automate my package in SSIS that will process each file with each given date, I need to figure out the regex or conversion for a file such as 'leads_2019-Dec-22' so the package can complete.
So far this is as far as I've gone, however this only works for 'YYYY-MM-DD' formats. I'm unable to change the format from the data loader tool I have, so there's no easy fix to this other.
#[User::UploadedFile] =
REPLACE(REPLACE(REPLACE(REPLACE(#[User::UploadedFileName], "yyyy",
(DT_STR,4,1252)DATEPART( "yyyy" , getdate())),"mm",RIGHT("0"+
(DT_STR,4,1252)DATEPART("mm",getdate()),2)), "dd", RIGHT("0"+
(DT_STR,4,1252)DATEPART("dd",getdate()),2)), "hh", right("0" +
(DT_STR,4,1252)DATEPART("Hh",getdate()),2) )
Has anyone dealt with this before and if so, how did/would you solve this using an Expression?
SQL Server does not support regular expressions.
However, the format used in the file name is very similar to a format you can use with convert to get the actual date from it's string representation.
The format convert supports under style 106 is dd mom yyyy - meaning all you have to do is isolate the date part from the string, replace the hyphens with spaces, and convert.
Please note that if the default language of the current login is not English, you might get errors because the month names depends on the language settings.
This is why I've included the set language statement in my code:
SET LANGUAGE us_english;
DECLARE #FileName varchar(20) = 'leads_2019-Dec-22';
SELECT CONVERT(Date, REPLACE(RIGHT(#FileName, 11), '-', ' '), 106);
Result:
2019-12-22
If you can be sure, now and forever, that this will never-ever run in systems with a different culture you can use easy conversions or set the language and culture for a session specifically.
But - if ever run on different systems - this might pass all your internal tests and may break in production with silly errors.
Culture specific approaches (and even worse: language specific ones) are very dangerous...
To overcome this you can use the following culture-safe approach (but it will be slower than simple conversions):
--Your question is not clear for me about the actual input.
--The string I use here seems to be your needed outcome...
--However, you will get the ghist how you can approach this issue with any given value...
DECLARE #TheFileName varchar(20) = 'leads_2019-Dec-22';
--not needed, just for testing... (in Germany "Dec" needs to be "Dez"...)
SET LANGUAGE GERMAN;
SELECT FORMAT(TRY_PARSE(RIGHT(#TheFileName,11) AS DATE USING 'en-us'),'yyyy-MMM-dd','en-us');
You have three obstacles:
First is to cut off the pure date. I do this by using RIGHT assuming we always need the rigth-most eleven characters.
Second is to get a date-typed value out of this. TRY_PARSE() accepts a culture parameter to ensure correct reading.
Third is to create the correct output. Here I use FORMAT(), which again allows for a specific culture.
Assuming you want the an output string in YYYY-MM-DD format from a variable called UploadedFileName that has data like 'leads_2019-Dec-22', you can just replace the "leads_" part and convert the rest to a date. Then you can parse the date to change it to the desired YYYY-MM-DD format:
(DT_WSTR, 4) YEAR((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_","")) + "-" +
(DT_WSTR, 2) MONTH((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_","")) + "-" +
(DT_WSTR, 2) DAY((DT_DATE) REPLACE(#[User::UploadedFileName],"leads_",""))
What is this date format called: 1YYMMDD
Example: 06/28/1959 outputs as 1590628
Example: 06/28/2019 outputs as 1190628
There is always a stinking 1 in front of it, no matter what.
As #TomNash already mentioned in his comment the 1 seems to be a century marker.
So your date format is CYYMMDD where C could be
0 : for 19xx
1 : for 20xx
This kind of format is not part of ISO 8601!
It looks to be a little bit like an IBM special and maybe AS/400 specific solution for the year-2000-problem.
My personal recommendation is to convert such date formats always to ISO 8601 via an intermediate layer before processing them.
Last but not least please remember to set software that use such outdated formats onto a list, because a solution like the century marker has only moved the year-2000-problem 100 years to the future - so the childs of our grandchilds will have the same problem again ...
Is possible change format date by specific pattern ? I need to made a function which has a two parameters. First is date and second is pattern. I need convert more date variants. Goal this function is change US and European date format.
For example i need convert
EU: dd:MM:yyyy hh:mm:ss
to
US: MM:dd:yyyy hh:mm:ss
On another page i need change
EU: dd/MM/yyyy
to
US: MM/dd/yyyy
And i have a several next variant to convert
And i want to made a similar function
Formater(euDate, pattern)
BEGIN
....
RETURN usDate
My production server is unfortunately SQL server 2005 and doesn't support function FORMAT(). And function CONVERT() doesn't support some variant of date, which i need convert. So in my current solution i parse EU date at individualy parts (#day = day(#euDate), #month, #year, ...) and join them in new string . And i compare it with input parameter in pattern and return CASE which is equal like pattern. I want to this function make general and simplier.
Thank you for Your advice.
You almost certainly can use the convert function. You can read more about all the options here.
If there is some obscure invariant you need, check out this blog by Anubhav Goyal.
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)
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);