converting and formatting datetime

debbieb

Member
Joined
Mar 13, 2013
Messages
8
Programming Experience
Beginner
Hi, I am very new to programming in visual basic. I'm working on an asp.net page and I have a value I'm pulling from a sqlserver database named "LastUpdatedDate" this is coming over as a string which I'm then trying to put into a datetime format so I can run a search for that same time in another database.

LastUpdatedDate returns "3/13/2013 4:17:01 PM" (as a string)

then I am trying to convert it a datetime field in this format "yyyy-MM-dd HH:mm" (so it will look like this:2013-03-13 16:17) using

dim mostrecentsavedate as datetime
mostrecentsavedate = DateTime.ParseExact(LastUpdatedDate, "yyyy-MM-dd HH:mm", CultureInfo.InvariantCulture)

but I keep getting the "String was not recognized as a valid DateTime..." error

Any help would be MUCH appreciated.

note: I also tried running these variations with no luck:

mostrecentsavedate = DateTime.ParseExact(LastUpdatedDate, "yyyy-MM-dd HH:mm", Nothing)

mostrecentsavedate = DateTime.ParseExact(LastUpdatedDate, "M/dd/yyyy HH:mm:ss tt", CultureInfo.InvariantCulture)

I'm in Visual Basic 2012 - let me know if you need more info
 
Hi,

Two major pointers for you:-

1) When you want to convert a "Date String" to a DateTime variable then you have to specify what the originating format of the string is and NOT what you may want it to look like at a later time in your code. So all the variations you have tried so far would fail since the incoming string is not in any of these formats. You nearly got there on your last try but try this:-

VB.NET:
Dim myDateTime As DateTime = DateTime.ParseExact("3/13/2013 4:17:01 PM", "M/dd/yyyy h:mm:ss tt", Globalization.CultureInfo.InvariantCulture)

Since the incoming string is now a valid DateTime variable you can now display this in any way that you want by formatting the ToString method of the DateTime variable. i.e:-

VB.NET:
MsgBox(myDateTime.ToString("yyyy-MM-dd HH:mm"))

2) Why is this NOT a DateTime type in your SQL DataSource? If it where, then you could ignore all this, but I suppose, only you can answer that.

Hope that helps.

Cheers,

Ian
 
Back
Top