c# - How to format Datetime? type to "yyyy-MM-dd" -


i query field database, planstartdate datetime type, , planstartdate can null, want format planstartdate "yyyy-mm-dd"

            datatable dt = ds.tables[0];         var query = dt.asenumerable()         .select(dr =>         new initoverview         {             iid = string.isnullorempty(dr.field<string>("iid").tostring()) ? "" : dr.field<string>("iid"),             projectname = string.isnullorempty(dr.field<string>("projectname")) ? "" : dr.field<string>("projectname"),             teamlead = string.isnullorempty(dr.field<string>("teamlead")) ? "" : dr.field<string>("teamlead"),             status = string.isnullorempty(dr.field<string>("status")) ? "" : dr.field<string>("status"),             overallstatus = string.isnullorempty(dr.field<string>("overallstatus")) ? "" : dr.field<string>("overallstatus"),             planstartdate = dr.field<datetime?>("planstartdate"),             planenddate = dr.field<datetime?>("planenddate"),             actualstartdate = dr.field<datetime?>("actualstartdate"),             actualenddate = dr.field<datetime?>("actualenddate")         }         ).tolist(); 

anybody can realize it? thanks

assuming have nullable datetime stored in variable, need check whether it's null or not. can access underlying value , convert string. nullable types provide boolean property hasvalue should check prior trying work underlying object.

using system;  public class program {     public static void main()     {         datetime? actualstartdate = datetime.now;          if(actualstartdate.hasvalue)         {             string s = actualstartdate.value.tostring("yyyy-mm-dd");             console.writeline("value: " + s);         }            } } 

fiddle here.

if want within object initializer, this, using ternary operator:

new initoverview {     planstartdate = dr.field<datetime?>("planstartdate").hasvalue         ? dr.field<datetime?>("planstartdate").value.tostring("yyyy-mm-dd") : "no date"; } 

fiddle here.

however, caution converting string @ point not idea. in code, should leave dates dates until need displayed user, delay long possible. in view layer of application should convert date string. keeps api cleaner (no need convert date again manipulate it) , ensures it's simple convert correct format display user according culture settings.

also, you're doing boring wiring of database records .net objects. it's tedious , waste of time. should use micro orm such dapper , make cleaner. be:

using (var connection = new sqlconnection(connectionstring)) {     return connection.query<initoverview>(selectstatement).aslist(); } 

Comments

Popular posts from this blog

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -

python - Error while using APScheduler: 'NoneType' object has no attribute 'now' -