Reputation: 103
I'm reading values from Excel and inserting read rows to SQL, but I'm facing an issue with date columns.
From Excel I'm reading the dates as 23-08-2011 01:33:01
, but in the database the values are stored as 2011-08-22 10:21:18.000
.
Is there a way I can convert in C# (not in T-SQL) the date I'm reading to a yyyy-mm-dd 00:00:00:000
format? I want to convert 23-08-2011 01:33:01
to 2011-08-23 00:00:00:000
.
Upvotes: 3
Views: 1599
Reputation: 22177
DateTime
object using DateTime.ParseExact
DateTime
object into SQL format using String.Format
and the appropriate format string.See these two resources for guide how to create a DateTime format string:
Standard Date and Time Format Strings
Custom Date and Time Format Strings
DateTime excel = DateTime.ParseExact("23-08-2011 01:33:01", "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
String sqlString = String.Format("{0:yyyy-MM-dd hh:mm:ss:ffff}", excel);
Upvotes: 3
Reputation: 31
string dateString = "23-08-2011 01:33:01";
string format = "dd-MM-yyyy hh:mm:ss";
DateTime date = DateTime.ParseExact(dateString, format, CultureInfo.InvariantCulture);
string again = date.ToString("yyyy-MM-dd 00:00:00:000");
Upvotes: 1
Reputation: 21887
Use the ParseExact
method from DateTime
DateTime parsedDate = DateTime.ParseExact("23-08-2011 01:33:01",
"dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
Depending on how you're inserting your records, you should be able to use your DateTime object, otherwise you can store it as a string:
string sqlDate = parsedDate.ToString("yyyy-mm-dd hh:mm:ss:fff");
Upvotes: 1