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)
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_",""))
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);
I'm developing an app for iPhone that uploads pictures to a webserver. These pictures have the time of when they were taken in the filename. Since they can be taken from anywhere in the World, I have to keep attention to timezones and DST. I thought I can use CFAbsoluteTimeGetCurrent, that shouldn't be localized ([NSDate date] returns the localized version of time, with or without "AM", "PM", "p.m." or any other variant... for example it returns Arabian characters, if your phone is set in arabic language!).
So, can you suggest me a function to convert CFAbsoluteTimeGetCurrent to a "MySQL like" date, something like "2011-11-03 14:12:10"?
My second question is: what about timezones and daylight saving? CFAbsoluteTimeGetCurrent always returns an UTC date, no matter how the iPhone timezone is set? Is it always DST-free?
Of course I know that the local iPhone date/time could be wrong, but milliseconds-precision is not important for my application :)
Thank you in advance!
What on earth do you mean by
([NSDate date] returns the localized version of time, with or without "AM", "PM", "p.m." or any other variant... for example it returns Arabian characters, if your phone is set in arabic language!).
[NSDate date] returns an NSDate* object. I'm assuming what you really mean is the output of -[NSDate description] returns a string localized in the user's current locale, but then the question is, why are you depending on the output of -[NSDate date]? If you need to format a date a certain way, you should use an NSDateFormatter.
CFAbsoluteTime represents a moment in time, independent of time zones or localization settings. If you want to format a date (i.e. an NSDate object) you should look at NSDateFormatter, which lets you specify the exact format and localization (if any) of the output string. (If you need to work at the Core Foundation level, CFDateFormatter does the same thing.)
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.
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)