Reputation: 159
I am calling the webservice which gives me the Datetime as "dd-MM-yyyy 00:00:00". Now i want to save it to the database. So in order to save the date, i have to convert the date format to MM/dd/yyyy. I have tried below code to convert the date time format, but nothing works for me
1. DateTime.ParseExact(string, "MM/dd/yyyy", culture);
2. Convert.ToDateTime(string).ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);
Can anyone help me on this?
Upvotes: 12
Views: 101205
Reputation: 21
DateTime date=DateTime.Now;
string result = date.ToString("MM/dd/yyyy");
Upvotes: 2
Reputation: 167
You Can also do it by capturing day/month/year separately....
string formattedDate= Convert.ToDateTime(your_date_object).Day.ToString() + "/" + Convert.ToDateTime(your_date_object).Month.ToString() + "/" + Convert.ToDateTime(your_date_object).Year.ToString();
Upvotes: 0
Reputation: 1942
var dateTime = "28-08-1993 12:12:12";
DateTime dt = DateTime.ParseExact(dateTime, "dd-MM-yyyy hh:mm:ss", CultureInfo.InvariantCulture);
var convertedDate = dt.ToString("MM/dd/yyyy");
Console.WriteLine(convertedDate);
Upvotes: 2
Reputation: 7352
DateTime type have not any specific format you can directly save it to database. But if you want it as specific format string then you can do it by
//input date string as dd-MM-yyyy HH:mm:ss format
string date = "17-10-2016 20:00:00";
//dt will be DateTime type
DateTime dt = DateTime.ParseExact(date, "dd-MM-yyyy HH:mm:ss", CultureInfo.InvariantCulture);
//s will be MM/dd/yyyy format string
string s = dt.ToString("MM/dd/yyyy");
and if you get input date
as DateTime
type then you can get formatted string directly
string s1 = date.ToString("MM/dd/yyyy");
Upvotes: 15
Reputation: 43936
The DateTime
is a struct that does not have any information about something like a "format".
You only use a format if you want to create a string representation of the DateTime
's value. What you mean by "nothing works for me" is probably that your debugger always uses the same format to display the value of your DateTime
.
What you have to do to insert the value into your database depends on the database system and the kind of connection you use. Normally you should use a parameterized query where you can pass the DateTime
as it is and everything will work fine.
If you have to put your DateTime
value directly into your query string, you can simply use myDate.ToString("MM/dd/yyyy",CultureInfo.InvariantCulture);
. But I am absolutely sure you use a database connection that supports parameterized queries accepting your DateTime
directly and I would not suggest to convert the value back into a string representation.
Upvotes: 5