My Format Date Function Doesn't Work In Microsoft Access - vba

I am writing a simple code that converts the date value of the default format(MM/DD/YYYY) of the first textbox into a different format of(DD/MM/YYYY) of the second textbox based on the Exit Event
For some reason, it ALWAYS returns the date format MM/DD/YYYY.
'First Code to convert it into a string
Private Sub date1_Exit(Cancel As Integer)
Dim dat_ed As Date
dat_ed = CDate(Me.date1.Value)
dat_ed = Format(CStr(dat_ed), "d/m/yyyy")
Me.date2.Value = dat_ed
End Sub
'Second Attempt to convert it directly
Dim dat_ed As Date
dat_ed = CDate(Me.date1.Value)
dat_ed = Format(dat_ed, "d/m/yyyy")
Me.date2.Value = dat_ed

Your code is wrong on a couple of places, mainly because you're confusing dates and strings formatted as dates.
Dim dat_ed As String 'You want this to hold a formatted date, so it's a string not a date
'dat_ed = CDate(Me.date1.Value) 'We can't do this because a string can't hold a date
'So we combine the next two calls
dat_ed = Format(CDate(Me.date1.Value), "d/m/yyyy")
'No CString in format, we need it to get the date as a date
'Note that / in format means the system date separator, if you want literal slashes, use \/ instead
Me.date2.Value = dat_ed
Also note, if your textbox has the Format property set to a specific date format, you need to modify that property, instead of assigning a formatted date to it.

You are making it way too complicated.
First, if you have applied a date/time format to the Format property of a textbox, Access knows that this is a datetime value.
Second, a date/time value carries no format. It is a value.
Third, to have a date value displayed in a specific format, apply this format to the Format property of the textbox.
Thus, apply the format d/m/yyyy (or d\/m\/yyyy) to textbox date2. Then:
Private Sub date1_Exit(Cancel As Integer)
Me!date2.Value = Me!date1.Value
End Sub

Related

VB.NET - Unable to enforce two digit day and month when converting string to Date

I am having difficulty taking a string and converting it to a vb.net Date object, while enforcing two digit day and month. Please consider the following form example, using today's date. (02/01/2019)
Dim myDate As Date = Date.Now
Dim myDateString = String.Format("{0:D2}/{1:D2}/{2:D4}", myDate.Month, myDate.Day, myDate.Year)
myDate = DateTime.ParseExact(myDateString, "MM/dd/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)
Label1.Text = myDate 'This will show "2/1/2019"
Label2.Text = myDateString 'This will show "02/01/2019"
This situation leaves Label1.Text as "2/1/2019", but Label2.Text as "02/01/2019". No matter what I have tried, it appears that the actual conversion from the correctly formatted String into a Date object will remove these zeros. Does anyone have any thoughts as to how I can enforce a "MM/dd/yyyy" format when converting to a Date object?
Thank you in advance,
You should consider that a DateTime variable has no format. It is just a number expressing the Ticks elapsed from the starting DateTime.MinValue (1/1/0001).
It has no memory that you have built it using a particular formatting parser.
So, when you assign a date to a string like you do in your
Label1.Text = myDate
then you are asking the ToString representation of that date. The output of this method without a formatting parameter is whatever your locale settings decide it to be. If you want to force the desidered output you need to tell the date's ToString method in what format you want the output
Label1.Text = myDate.ToString("MM/dd/yyyy")

How to change date format vb.net 2015

I want to filter SQL-table between start date and end date, I used before string variable then I use string.format to make the format mm/dd/yyyy, I tried now in VB.net 2015 the following code:
Dim S as String
s=inputbox("Enter Start date")
S=string.format(S,"mm/dd/yyyy")
But it doesn't work, can somebody give me a solution?
You could try this for handling the input value, assuming you only need the date value as a formatted string, since your question is about formatting a date:
Dim S As String
S = InputBox("Enter Start date")
If IsDate(S) = True Then
Dim d As Date = Date.Parse(S)
S = d.ToString("mm/dd/yyyy")
Else
'Handle the non date input here
End If
But I think you should consider #Plutonix comment, since we don't know exactly how you are sending the date to perform the filtering, or how your table fields are defined.
Regards!

Why converting a date to a string changes the order?

Here is a peculiar result generated from this simple code:
Dim TodaysDate As Date = Date.Today ' Returns #8/12/2014#
Dim StringDate As String = TodaysDate ' Returns 12/08/2014
Dim AnotherStringDate As String = TodaysDate.ToString ' Returns 12/08/2014 00:00:00
What is going on? Why the string reversed the result, although I did not even used any conversion command?
Change Option Strict to On, then you get a compiler error instead of weird conversions. In general, a Date is not a String but it can be represented as one.
If i remember correctly VB uses helper methods with Option Strict Off to convert the type automatically which are sitting in the namespace Microsoft.VisualBasic.CompilerServices.
I've looked at the source-code (with ILSpy) and found a class StringType which has a method FromDate:
' Microsoft.VisualBasic.CompilerServices.StringType
Public Shared Function FromDate(Value As DateTime) As String
Dim ticks As Long = Value.TimeOfDay.Ticks
If ticks = Value.Ticks OrElse (Value.Year = 1899 AndAlso Value.Month = 12 AndAlso Value.Day = 30) Then
Return Value.ToString("T", Nothing)
End If
If ticks = 0L Then
Return Value.ToString("d", Nothing)
End If
Return Value.ToString("G", Nothing)
End Function
Since your Date was derived from Date.Today which is the current date without time, the code will be executed which starts with If ticks = 0L Then(ticks is from the time of the day).
This returns:
Value.ToString("d", Nothing)
which is the same as Date.ToShortDateString. The format is derived from your current culture since null is passed as CultureInfo. So obviously your current culture uses / as date separator.
You could also force this format by using:
Dim StringDate As String = TodaysDate.ToString("d")
StringDate = TodaysDate.ToShortdateString()
StringDate = TodaysDate.ToString("dd/MM/yyyy", CultureInfo.InvariantCulture)
The last option also ensures that this format is used even if your current culture is different.
A date is stored internally as number. And a date/datetime variable doesn't really know or care what actual date it represents; it is just a number (decimal). The string representation is for our eyes only. When you convert a date/datetime variable to string type, it is converted in the format specified by our machine locale settings, unless we specifically tell it to convert it to some other format.
I am assuming that the date/time settings on your PC is in the dd/mm/yyyy (indian format) format rather than the default mm/dd/yyyy (US format).
So this is what is actually happening:
' You store today's date in a Date variable and it returns #8/12/2014# i.e. 12-Aug-2014
Dim TodaysDate As Date = Date.Today
' You convert it to string. Since you didn't sepecify the format, it picks up the fromat settings from your PC regional settings.
' Returns 12/08/2014 which means 12-Aug-2014 (in your locale)
' You didn't do .ToString, but that's implicit, unless you set OPTION STRICT ON, in which case it will force you to put .ToString
Dim StringDate As String = TodaysDate
' Same argument as above.
Dim AnotherStringDate As String = TodaysDate.ToString ' Returns 12/08/2014 00:00:00
As for the question why converting a date to a string changes the order? The answer is that it doesnt.
When you convert to string, your local culture format is used, as explained by Tim. That's not teh case with Date literals in VB.
Date literals - values between hashes such as #02/11/2014# - are always displayed in InvariantCulture or "m/d/y" pattern. This is likely because when you wish to create a date using a literal, you must specify the Day and Month in that format. See MSDN:
Date literals must be in the format #m/d/yyyy# or they are invalid.
So, it would make no sense to display the date to you in one pattern but require you to create them using a different pattern. This is just the way VB works (in part because the legacy functions have no notion of cultures beyond the local one in use). This is a VB-ism as seen in this VB vs C# date display in Visual Studio:
The culture is set to fr-FR.
But your strings ultimately represent the same date - they can make a roundtrip:
Dim TodaysDate As Date = Date.Today ' Returns #8/12/2014#
Dim AnotherStringDate As String = TodaysDate.ToString
Dim mydt As DateTime = DateTime.Parse(AnotherStringDate)
If mydt = TodaysDate Then
Console.Beep()
End If
It will beep because the same DateTime is created from the string even though it may display in the pattern of "d/m/y" for yur culture.

VBA:Compare two date formats in vba

How do we compare two date strings in vba, like "01.02.2013 < 02/02/2013"?
Whatever the dates are this always showing true. And two date formats are correct in the example i menioned.
Below vba code throws error.
Sub aa()
Dim a As Variant, b As Variant, c As Variant
a = Format("1.2.2012", "DD\/MM\/YYYY")
b = Format("2.2.2012", "DD\/MM\/YYYY")
MsgBox (a)
End Sub
Convert your dates (strings) to a format CDate() accepts. 02/02/2013 works, I think 02.02.2013 doesn't. Use Replace() if needed.
Then you can cast your String data into the Date datatype with CDate(myString). Dates can be compared with each other by the means of the usual operators, such as > < =.
Clean up the strings to the correct format (see what CDATE accepts, and then use CDate(a) >= CDate(b) to compare.

How to get a date field from MM/dd/yyyy to yyyy/MM/dd in vb.net

I need to get a date field from MM/dd/yyyy to yyyy/MM/dd in vb.net but it should still be a date field afterward so that I can match it against a date in a database.
At the moment all I'm managing to do is to change it to a string in that format.
I tried this type of code which also did not work.
DateTime.Parse(yourDataAsAString).ToString("yyyy-MM-dd")
fromDeString = String.Format("{0:yyyy/MM/dd}", aDate)
fromDate = Format("{0:yyyy/MM/dd}", aDate)
Any help would be much apreciated, thanks
You're not understanding that a date object does not store the digits in any particular format. The only way to get the digits formatted in the order you want is to convert it to a string. Why do you need to compare them in a particular format? A date is a date no matter how it is formatted. 12/15/78 == 1978/12/15.
If you are not able to compare dates from the DB against a date object in VB, it is likely that the date you are comparing to in the database is being returned to you in string format, in which case you should covert it to a date object for comparison.
Dim sDate As String = "2009/12/15" 'Get the date from the database and store it as a string
Dim dDate As New Date(2009, 12, 15) 'Your date object, set to whatever date you want to compare against
Select Case Date.Compare(dDate, Date.Parse(sDate))
Case 0
'The dates are equal
Case Is > 0
'The date in the database is less
Case Is < 0
'The date in the database is greater
End Select
Here's a sample module demonstrating the functionality you desire.
Imports System.Globalization
Module Module1
Sub Main()
Dim culture As New CultureInfo("en-us", True)
Dim mmDDyy As String = "10/23/2009"
Dim realDate As Date = Date.ParseExact(mmDDyy, "mm/dd/yyyy", culture)
Dim yyMMdd As String = realDate.ToString("yyyy/MM/dd")
End Sub
End Module
Hope this helps.
Kind Regards
Noel
Your second should actually work. Instead just try:
dim chislo as date = date.now dim message As String = $"
Today`s Date: {String.Format("{0:dddd, dd/MM/yyyy}", Chislo)} "
MsgBox(message)