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.
Related
I'm trying to format a date for an API. the desired format is: yyyy-MM-ddTHH:mm:ss.fffffff+HH:mm
(eg. 2022-10-12T09:52:14.1234567+03:00). I'm using Date.ParseExact in the following way:
Date.ParseExact("2022-10-12T09:52:14.1234567+03:00", "yyyy-MM-ddTHH:mm:ss.fffffff+HH:mm", CultureInfo.InvariantCulture)
.
Initially I used 'Now' instead of this string, but then I saw that the string and the desired format have to match. The error I'm getting is 'DateTime pattern 'H' appears more than once with different values.'. Is there a way to avoid that? Also is it possible to use 'Now' in this line?
Thank you
I suspect that you don't have a parse issue, you don't need ParseExact at all. You have a Date and want to return it as a formatted string. Then use ToString and zzz for the utc-offset:
string result = DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss.fffffffzzz");
Read also: Custom date and time format strings
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 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)