简体   繁体   中英

How can I store a formatted DateTime into column of type DateTime in Database?

I'm retrieving data from the database in a dataset and printing it in a pdfdocument. One table has got a DateTime column and the value comes as "12/27/2018 12:00:00 AM" . I'm trying to format that as dd/MM/yyyy but with no success since it is expecting a DateTime and formatting return a string value. Should I change the column datatype or there is a way to maintain it and format the datetime?

I recommend changing the database from string to DateTime. But if you cannot you can use something like this

            DataTable dt1 = new DataTable();
            DataTable dt2 = dt1.Clone();

            //change columns type
            dt2.Columns["Col A"].DataType = typeof(DateTime);
            int colNumber = dt2.Columns.IndexOf("Col A");

            foreach (DataRow row in dt1.AsEnumerable())
            {
                object[] rowData = row.ItemArray;
                rowData[colNumber] = DateTime.Parse(row.Field<string>("Col A"));
                dt2.Rows.Add(rowData);
            }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM