Reputation: 5271
I want to know how to change a DateTime format into another. I mean, I get a value in string that it will represent a DateTime value added into Typed DataTable, but I got an error at the moment of adding the DataRow
dr[i] = value;
dt.Rows.Add(dr);
The column for that field was set like this.
DataColumn dc = new DataColumn("CreateDate", typeof(System.DateTime));
dt.Columns.Add(dc);
So, I'm receiving this value "30-01-1984" and crash!!! so. Imagine that I defined now 2 datetime formats. I want to configure this format for telling to my app that I'm gonna receive this format "MM-dd-yyyy" and change it to this format "yyyy-MM-dd". So I want to parse my string value into the first format and then verify if I can change it into the new format.
Thanks
Upvotes: 0
Views: 3003
Reputation: 223267
Since you are getting a formatted string with DateTime
value, you have to parse it in .Net DateTime
type object, using DateTime.Parse
or DateTime.ParseExact
, (or DateTime.TryParse
variants) like:
string yourStringDate = "30-01-1984";
DateTime dateTimeObj = DateTime.ParseExact(yourStringDate,
"d-M-yyyy",
CultureInfo.InvariantCulture));
(I have used single d
and M
which would work for both single digit Day and Month)
Later add that in your DataTable. like:
DataRow dr = dt.NewRow();
dr["CreateDate"] = dateTimeObj;
I am not sure how you are getting back the date as string, If you are storing DateTime
as string in Database, then its better to use DateTime
type provided by database, instead of keeping dates as string.
Upvotes: 3