I'm using VS 2013 and VB language
My task is to store a user entered date in the format mm/dd/yyyy
Dim date1 As String = Format("MM/dd/yyyy")
Dim date2 As Date
Dim date3 As Date
date1 = Console.ReadLine()
date2 = DateTime.Now
date3 = DateTime.Parse(date1)
Console.ReadLine()
I first tried entering the date as Dim date1 as Date, but entering it in mm/dd/yyyy is invalid format.
So I tried this method, and get the error "String was not recognized as a valid DateTime"
How can I format the entered date so that it will be recognized as a valid datetime?
Thanks
User cannot be forced to enter the date in the format that you expect (particularly on a console application). So your best line of action is trying to parse this date and inform your user that the input is invalid
Dim isValid = False
Dim dt As DateTime
While(Not isValid)
Console.WriteLine("Please enter a date in the format MM/dd/yyyy")
Dim input = Console.ReadLine()
isValid = DateTime.TryParseExact(input, "MM/dd/yyyy", _
CultureInfo.InvariantCulture, DateTimeStyles.None, dt)
End While
DateTime.TryParseExact is a method of the DateTime that tries to parse the input string accordingly to a format specified. If the string complies to the format required then the method returns true and the last parameter is set to the datetime resulting from the conversion. Otherwise the method return false without throwing an exception so you could take the appropriate measures (in this case request again the input)
All dates are stored in memory as dates, and do not actually have formats. The formats appear when you change the date into a string (i.e. with the Date.ToString() method).
I think the best option here is to use Date.Parse() with no arguments, so that the command-line will accept all date formats (be prepared to catch format exceptions), and then when you need to display the date back to the user, format it using a format string and the Date.ToString() method.
Code example follows:
Dim strDateFormat = "MM/dd/yyyy"
Dim date2 As Date
Dim date3 As Date
date2 = Now()
date3 = Date.Parse(Console.ReadLine())
Console.WriteLine(date3.ToString(strDateFormat))
P.S. As you have it written, the command input overwrites your formatting string, so your formatting string is effectively useless.
Related
I need to convert a dd/mm/yy date to dd/mm/yyyy automatically.
Example: if I insert in the textbox "12/01/90", the program should automatically convert the text to "12/01/1990" or "01/01/20" to "01/01/2020".
Also, I should check the date to make sure it is correct.
Example: if I enter "80/70/2000" it must give me an error because the date does not exist. How can I do? Thanks in advance.
If you have the input as a string, you would first parse it into a date with the format specifier, and then convert it back into a string.
Dim input as String = "22/03/19" ' dd/mm/yy
Dim dt as DateTime = DateTime.MinValue
If (DateTime.TryParseExact(input,
"dd/MM/yy",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None,
dt
)) Then
Dim output as String = dt.ToString("dd/MM/yyyy")
Console.WriteLine(output)
else
Console.WriteLine("Error")
end if
Output:
22/03/2019
You can try it here
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!
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.
I have user input that needs to be verified that the string is in the datetime format as follows:
yyyy-MM-dd HH:mm:ss
The user does not have a choice for any other format but for error checking how do I detect whether string in is this format.
sDate = DateTime.ParseExact(startDate, "yyyy-MM-dd HH:mm:ss", CultureInfo.CurrentCulture)
startdate is the string.
This code will help you to convert the date into the format which which you wanted to check
Dim format As String = "yyy-MM-dd HH:mm:ss" 'let input be "02-02-2014 12:12:12"
MsgBox(dt.ToString(format)) ' the output will be 2014-02-02 12:12:12
it works properly in VS 2010(windows 7)
IMHO, you should consider using DateTimePicker control for taking date/time input. Use Custom Format (if needed). It will save you to first take it and validate it.
You should use DateTime.TryParseExact if you want the date/time format to be exactly in a particular format.
Function IsValidDate(ByVal dateValue As String) As Boolean
Return DateTime.TryParseExact(dateValue, "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture, DateTimeStyles.None, Nothing)
End Function
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)