Wednesday, 10 October 2012

DateTime: Format in SQL and Everywhere else

Get the value from DateTime:
DateTime date1 = new DateTime(2008, 12, 31); 
DateTime date2 = date1.AddMonths(1);
DateTime date3 = date1.AddYears(1);
DateTime date4 = date1.AddDays(1);
DateTime date5 = date1.AddDays(-3);

Find the date name:
Input: string day = DateTime.Now.DayOfWeek.ToString();
Output: Wednesday

Find the date name in another language format:
Input: DateTime.Now.ToString("dddd", new System.Globalization.CultureInfo("de-DE"))
Output: Wednesday in German
Format the DateTime without time/ Convert DateTime to String:
String str=DateTime.Now.ToString("d");

DateTime Format in gridview column:
if you're using a BoundField, simply do as follows:
<asp:boundfield datafield="Your_Date_Column" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />
Convert String to DateTime and use it in the SQL select statement:
If you mean storing the date part only in the database (MSSQL?), I don't think you can. A datetime field will always contain time, that's what it's made for. If you mean formatting a string in the code, look at datetime format expressions, there is plenty to choose from.
String ws=DateTime.Now.ToString("d");
DateTime dt = Convert.ToDateTime(ws);

format(varDate,"dd/MM/yyyy HH:mm:ss")

string sql = "SELECT tGymReg.AdmissionNumber, tRegistration.WeekStartDate FROM tGymReg RIGHT JOIN tRegistration ON tGymReg.AdmissionNumber = tRegistration.AdmissionNumber WHERE (((tRegistration.WeekStartDate)=format(\""+dt+"\",'dd/MM/yyyy') Or (tRegistration.WeekStartDate) Is Null) AND ((tGymReg.Induction)=True)) ORDER BY tRegistration.WeekStartDate,tGymReg.AdmissionNumber"; SELECT     yourField1, CONVERT(DATETIME, yourDateFieldName, 103) AS YourDateFieldFormated FROM YourTable

No comments:

Post a Comment