Visual basic script that control a date format - vb.net

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.

Related

T-SQL format date by pattern

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.

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);

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")

Format date like M/D/Y

I got a date of the type SYDATUM and wondering how to format it in a format like m/d/y.
I've found some snippets on the web, but they were not really helpful.
-thanks yor your help.
You should be more specific - what exactly do you want to do with the date (use type D internally, it's shorter and does the same thing).
Do you want to WRITE it to a list screen? Use the formatting options described in the documentation and online help:
WRITE l_my_date MM/DD/YYYY.
Do you want to convert it to a text variable? Very similar:
WRITE l_my_date TO l_my_text MM/DD/YYYY.
To set the date format in a SAPscript form, see the SET DATE MASK command.
To print the formatted date in a SmartForm, use the WRITE command and a temporary variable (yes, ugly, I know...)
Most controls (ALV Grid for example) should take care of the format automatically.
However - be careful when hard-coding the format into your application. Usually you don't have to do this because the system automatically uses the format specified in the user master data. This ensures that every user will see the date formatted according to their locale settings.
Normally it's better to export the date into the plant level country specific date format:
if w_country is initial.
select single LAND1
from T001W
into w_country
where WERKS eq w_the_plant.
endif.
SET COUNTRY w_country.
write w_the_date to w_export.
for example 03/04/2002 could be different date in different country.
You can try the keyword TRANSLATE. Alternatively suggest you could have a look at this link

VisualBasic Month function inconsistency

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)