Formatting Dates

Formatting Dates

by JBrooks 2. July 2009 09:37

I was having a lot of code that looked like the following:

         if(dr["StartTime"] != DBNull.Value)   
                tbStartTime.Text = dr["StartTime"].ToString("M/d/yy H:mm");

              tbStartTime.Text = "";


         tbStartTime.Text = DateTime.Now.ToString("M/d/yy H:mm");


You usually use the same formatting throughout an application so I simplified this by using the following function:

        public string formatDate(object date)
            if (date != DBNull.Value)
                return Convert.ToDateTime(date.ToString()).ToString("M/d/yy H:mm");
                return "";

 So now I can have my formatting in one place and use this like so:

       tbStartTime.Text = formatDate(dr["StartTime"]);

 and using the same function:

     tbStartTime.Text = formatDate(DateTime.Now);






ASP.Net | Development