Marc
Marc

Reputation: 16522

Convert string to date

I have a Web service that receives dates on this format dd/MM/yyyy.

I realized that it crash cause sometimes I have dates like this one 1/1/2012.

I have no control on what the web service receives.

I tried

    myDate = cDate(myString)

    myDate = Convert.toDatetime(myString)

    myDate = DateTime.ParseExact(myString, "dd/MM/yyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)

    myDate = Convert.ToDateTime(myString.ToString("dd/MM/yyyy"))

Nothing works, so is there any elegant way to do this or I have to split and add "0" when it's a date like this

Thank you

Upvotes: 2

Views: 6838

Answers (3)

nimblebit
nimblebit

Reputation: 559

ACCESS SQL DATE QUERY SOLVED

Convert String Date To Access SQL Date

When trying to select data from an SQL query in my project, the date was formatted as: 31/01/2014 04:46:54, the field column was declared as datetime in the database...

however when I used an sql statement fldPlaceOrderDate = #31/01/2014 04:46:54# It would not return any rows. When I would view the column in microsoft access it would display it the same way. So I concluded there must be a bug with my SQL in my vb project right?

So I copied the SQL from my vb.net project into the access query builder sql view, and it didn't return any rows there either. So I built the SQL again manually using the MS Access Design View. I formatted the date the same #31/01/2014 04:46:54# ... this time it returned the row, and it showed the date was actually formatted as MM/dd/yy HH:mm:ss

So I tried the following instead in my project

"SELECT fldReference" & VBCRLF & _ "FROM tblOrders" & VBCRLF & _ "WHERE fldPlaceOrderDate = #" & CDATE("31/01/2014 04:46:54").ToString("MM/dd/yy HH:mm:ss") & "#;"

This fixed the problem!

Upvotes: 0

ken2k
ken2k

Reputation: 49013

How about

DateTime date = DateTime.ParseExact(dateAsString, "d/M/yyyy", CultureInfo.InvariantCulture)

Upvotes: 1

Oded
Oded

Reputation: 499272

This works:

myDate = DateTime.ParseExact(myString, 
                             "d/M/yyyy", 
                             CultureInfo.InvariantCulture, 
                             DateTimeStyles.None)

It also works for "01/02/2012", "21/1/2012", "1/11/2012" and "12/12/2012".

Upvotes: 4

Related Questions