sinae
sinae

Reputation: 11

convert string to datetime vb.net

i need to convert strings to date format. the requirement is if current month is selected, the date should be getdate. if any other month is selected then it should be first of that month. the data coming in is "January 2010", "February 2010" and so on. but it should be inserted into sql server database as 01/01/10 or 02/01/10

Upvotes: 1

Views: 21634

Answers (4)

Jojo Sardez
Jojo Sardez

Reputation: 8558

You could use this function:

Private Function GetDate(ByVal source As String) As DateTime
    Dim converted = DateTime.Parse(source)
    If (converted.Year.Equals(DateTime.Now.Year) And converted.Month.Equals(DateTime.Now.Month)) Then
        GetDate = DateTime.Now
    Else
        GetDate = converted
    End If
End Function

it could analysed passed month + year values like "April 2010".

Upvotes: 0

Fredrik Mörk
Fredrik Mörk

Reputation: 158289

I think the following should do the job for you:

Dim theDate As DateTime = DateTime.ParseExact(input, "MMMM yyyy", CultureInfo.InvariantCulture)

The InvariantCulture makes sure that the month names can be parsed correctly.

Upvotes: 3

Paul Creasey
Paul Creasey

Reputation: 28824

DateTime.ParseExact Method (String, String, IFormatProvider)

DateTime dt = DateTime.ParseExact(dateString,formatString);
dt = (dt.Month == DateTime.Now.Month) ? DateTime.Now : dt;

If your calling this alot in a loop performance may be better if you only call DateTime.Now once and store it in a variable before comparison, since DateTime.Now is a fairly expensive operation.

If the SQL server column is of type DateTime then you don't need to worry about the format, jut pass the DateTime object and it will work.

Upvotes: 0

Kyle
Kyle

Reputation: 4366

DateTime.ParseExact should be able to help you out in VB.Net

Upvotes: 1

Related Questions