Reputation: 49
I am trying to convert a string into a DateTime
and change its format from 05/06/2012 12:00:00
to 2012-06-05 12:00:00.000
to search in the database (SQL Server 2008 R2) DATETIME
column type. The original date is coming from a calendar!
I tried this:
string Datereturn = row.Cells[9].Text;
DateTime dategiven = DateTime.ParseExact(Dategiven,
"YYYY-MM-DD hh:mm:ss[.nnn]", CultureInfo.InvariantCulture);
but it pops an error of invalid datetime
Upvotes: 0
Views: 532
Reputation: 499012
To parse 05/06/2012 12:00:00
:
DateTime dategiven = DateTime.ParseExact(Dategiven,
"dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
To get a different formatted string:
string newFormat = dateGive.ToString("yyyy-MM-dd hh:mm:ss");
I suggest reading Custom Date and Time Format Strings on MSDN.
Also the different between parsing and formatting (in regards to DateTime
):
Parsing means taking a string representing a datetime and getting a DateTime
object from it
Formatting a DateTime
is taking a DateTime
object and getting a string from it, formatted as needed.
Upvotes: 1
Reputation: 6322
Can you try this
DateTime dategiven = DateTime.ParseExact(Dategiven, "dd/MM/yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Upvotes: 0