@manhng

Welcome to my blog!

Format DateTime in C#

June 30, 2020 11:57

Date Format in CSharp (edit)

Utils Class

namespace ConsoleApp1
{
internal class Program
{
private static void Main(string[] args)
{
var dtHddt = new System.Data.DataTable();

dtHddt.Columns.Add("Dosage", typeof(int));
dtHddt.Columns.Add("Drug", typeof(string));
dtHddt.Columns.Add("Patient", typeof(string));
dtHddt.Columns.Add("commandDate", typeof(System.DateTime));

dtHddt.Rows.Add(25, "Indocin", "David", null);
dtHddt.Rows.Add(50, "Enebrel", "Sam", System.DateTime.Now);
dtHddt.Rows.Add(10, "Hydralazine", "Christoff", System.DateTime.Now);
dtHddt.Rows.Add(21, "Combivent", "Janet", System.DateTime.Now);
dtHddt.Rows.Add(100, "Dilantin", "Melanie", System.DateTime.Now);

string s = string.Empty;
for (int i = 0; i < dtHddt.Rows.Count; i++)
{
s = dtHddt.GetSafeDate(i, "commandDate");
System.Console.WriteLine(s);
}
}
}

public static class DataTableExt
{
public static string GetSafeDate(this System.Data.DataTable dt, int idx, string colName)
{
string s = string.Empty;
try
{
if (dt != null &&
dt.Rows.Count > 0 &&
dt.Rows[idx][colName] != null &&
dt.Rows[idx][colName] != System.DBNull.Value)
{
var myDateTime = System.Convert.ToDateTime(dt.Rows[idx][colName]);
s = myDateTime.ToString("dd/MM/yyyy hh:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
return s;
}
}
}

Usage

dtHddt: System.Data.DataTable
string s = dtHddt.GetSafeDate(0, "commandDate");

Categories

Recent posts