How to apply formatting string when binding DateTime to MaskedTextBox? - vb.net

I have a MaskedTextBox using the mask "00/00/\2\000" to restrict input to a format of XX/XX/20XX, with the Text property bound to MyBindingSource.SomeProperty of type DateTime.
Recently, values with a single-digit month or day recently started displaying incorrectly. I expect that the ToString() method is being called on the value at some point in data binding, and I believe the call is not padding month / day with zeroes.
I tried setting the format type of the MaskedTextBox.Text property to DateTime in the advanced data binding properties, but it didn't help.
How can I apply ToString("MMddyyyy") when converting the DateTime object to a string, before the value is bound to the Text property?

You can use the binding's Parse and Format events to do the conversion yourself, as seen in this answer

Related

Cannot write date in BigQuery using Java Bigquery Client API

I'm doing some ETL from a CSV file in GCS to BQ, everything works fine, except for dates. The field name in my table is TEST_TIME and the type is DATE, so in the TableRow I tried passing a java.util.Date, a com.google.api.client.util.DateTime, a String, a Long value with the number of seconds, but none worked.
I got error messages like these:
Could not convert non-string JSON value to DATE type. Field: TEST_TIME; Value: ...
When using DateTime I got this error:
JSON object specified for non-record field: TEST_TIME.
//tableRow.set("TEST_TIME", date);
//tableRow.set("TEST_TIME", new DateTime(date));
//tableRow.set("TEST_TIME", date.getTime()/1000);
//tableRow.set("TEST_TIME", dateFormatter.format(date)); //e.g. 05/06/2016
I think that you're expected to pass a String in the format YYYY-MM-DD, which is similar to if you were using the REST API directly with JSON. Try this:
tableRow.set("TEST_TIME", "2017-04-06");
If that works, then you can convert the actual date that you have to that format and it should also work.
While working with google cloud dataflow, I used a wrapper from Google for timestamp - com.google.api.client.util.DateTime.
This worked for me while inserting rows into Big Query tables. So, instead of
tableRow.set("TEST_TIME" , "2017-04-07");
I would recommend
tableRow.set("TEST_TIME" , new DateTime(new Date()));
I find this to be a lot cleaner than passing timestamp as a string.
Using the Java class com.google.api.services.bigquery.model.TableRow, to set milliseconds since UTC into a BigQuery TIMESTAMP do this:
tableRow.set("timestamp", millisecondsSinceUTC / 1000.0d);
tableRow.set() expects a floating point number representing seconds since UTC with up to microsecond precision.
Very non-standard and undocumented (set() boxes the value in an object, so it's unclear what data types set() accepts. The other proposed solution of using com.google.api.client.util.DateTime did not work for me.)

how to pad zero on left with String.Format

i tried to use String.Format string with leading zero
Dim formatstring As String = ("{0,0}{1}{2,0:YYYY-MM-DD}{3}{4,0:00000}{5}{6,0:00000}{7}{8}{9}{10}{11}{12}")
with {4,0:00000} it would be fill zero on left
example
014 to 00014
with {6,0:00000} it would be fill zero on left too
example
547 to 00547
but it's not happen just still shown 014 and 547
For what you want to happen, the objects passed in the 4th and 6th indices need to support the IFormattable interface. From the docs:
If you specify formatString, the argument referenced by the format item must implement the IFormattable interface. Types that support format strings include:
All integral and floating-point types. (See Standard Numeric Format Strings and Custom Numeric Format Strings.)
DateTime and DateTimeOffset. (See Standard Date and Time Format Strings and Custom Date and Time Format Strings.)
All enumeration types. (See Enumeration Format Strings.)
TimeSpan values. (See Standard TimeSpan Format Strings and Custom TimeSpan format Strings.)
GUIDs. (See the Guid.ToString(String) method.)
That you have a value of 014, rather than simply 14, implies that what you have is already a string. The String type does not implement IFormattable. To get this to work, you need to first parse the strings to integers or similar type.

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

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.

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)