I have the following code -
DateTime timeStamp;
timeStamp = System.Convert.ToDateTime(y.InnerText);
Where y.InnerText is
I use this step 1. Convert to DateTime. 2. Use ToString(); function
Example :
DateTime myDateTime = DateTime.Now;
string myDateTimeString = myDateTime.ToString("yyyy-mm-dd hh:mm:ss");
How can I set the format of the DateTime object?
You can't. DateTime values don't have formats, any more than int or double values do. When you want to convert them to/from strings, that's where you specify any formatting information.
Instead, you should use parameterized SQL and avoid converting the DateTime value back into a string in the first place. This is a general best practice - don't include values in your SQL string; parameterized SQL has multiple benefits:
I would also suggest that instead of using Convert.ToDateTime, you specify your expected format when parsing. For example:
timeStamp = DateTime.ParseExact(y.InnerText,
"dd/MM/yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
Basically, the two rules I try to apply are:
And what if you just override your ToString() method of your DateTime object? Wouldn't you be able then to choose the format you want and every time it is used, it will be formatted in the way you want it without being bothered by it.
This is just a thought so I don't know if there are better solutions or not.
You can then use the properties year, month, day, to build it like you want. Something like:
public override ToString(){
return this.Year + "-" + this.Month + "-" + this.Day;
}
Greetings
you can use ToString convertion to 2013-03-11 11:35:24
DateTime timeStamp;
timeStamp = System.Convert.ToDateTime(y.InnerText).ToString("yyyy-MM-dd HH:mm:ss");
if you are passing datetime to sql database try with yourdatetime.ToString("yyyy/MM/dd") format this will work for you.
and one more thing you can add a datetime format for your Applicaton culture. so this will treat you datetime format at you desire.
using System;
using System.Globalization;
using System.Threading;
namespace test {
public static class Program {
public static void Main() {
CultureInfo culture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
culture.DateTimeFormat.ShortDatePattern = "yyyy/MM/dd HH:mm:ss";
culture.DateTimeFormat.LongTimePattern = "";
Thread.CurrentThread.CurrentCulture = culture;
Console.WriteLine(DateTime.Now);
}
}
}
Basically Date does not have a format. If the database parameter/field is Datetime type you should be fine passing as a Date type. It is not a good idea to pass date as a string.
However, if that something you have to deal with, then you better pass the Date in a none culture specific date format (ISO8601 or ISO) in a parameterised query. Otherwise you could have problems with database servers in different culture settings.
For example, for sql server, it is safe (in conversion) to pass date time in ISO8601 as;
'yyyy-mm-ddThh:mi:ss.mmm' //(no spaces)