简体   繁体   English

将日期时间转换为字符串

[英]Convert a datetime to string

Howsit! Howsit!

I encounter an error when i get a null value in my datareader. 当我在数据读取器中获得空值时遇到错误。

public List<Complaint> View_all_complaints()
{
    csDAL objdal= new csDAL();
    List<Complaint> oblcomplist=new List<Complaint>();

    using( IDataReader dr=objdal.executespreturndr("View_all_complaints"))
    {
        while (dr.Read())
        {
            Complaint objcomp= new Complaint();
            populate_reader(dr,objcomp);
            oblcomplist.Add(objcomp);
        }
    }
    return oblcomplist;
}

public void populate_reader(IDataReader dr, Complaint objcomp)
{
    objcomp.ref_num = dr.GetString(0);
    objcomp.type = dr.GetString(1);
    objcomp.desc = dr.GetString(2);
    objcomp.date = dr.GetDateTime(3);
    objcomp.housenum = dr.GetInt32(4);
    objcomp.streetnum = dr.GetInt32(5);
    objcomp.status = dr.GetString(6);
    objcomp.priority = dr.GetString(7);
    objcomp.cid = dr.GetInt32(8);
    if (!dr.IsDBNull(9))
    {
        objcomp.resolved_date = dr.GetDateTime(9);
    }
}

in sql resolved date allows null values, this is so because only when a complaint has been resolved , it must reflect that date otherwise it should be null. 在sql中,date允许使用null值,这是因为仅当投诉解决后,它才能反映该日期,否则应为null。

if dr.getdatetime(9) is null then it must just set a string saying "Not Resolved" 如果dr.getdatetime(9)为null,则必须只设置一个字符串“ Not Resolved”

please help! 请帮忙!

You haven't shown what your Complaint type looks like, but basically you'll want to make sure that its resolved_date is of type DateTime? 您尚未显示Complaint类型,但是基本上您需要确保其resolved_date的类型为DateTime? aka Nullable<DateTime> . aka Nullable<DateTime> That allows you to model a missing value elegantly. 这样就可以优雅地对缺失值进行建模

As for displaying it - you haven't shown anything about where you display the data, but you'd want something like: 至于显示它-您没有显示数据显示位置的任何信息,但是您需要类似以下内容:

string text = complaint.ResolvedDate.HasValue ? complaint.ResolvedDate.ToString()
                                              : "Not Resolved";

(I've changed this to use a property with the idiomatic name at the same time...) (我将其更改为同时使用具有惯用名称的属性...)

IDataReader has a " IsDBNull " method, that should be called before calling GetXXX(), in case your value is not nullable. IDataReader有一个“ IsDBNull ”方法,如果您的值不可为空,则应在调用GetXXX()之前调用该方法。

For example: 例如:

objcomp.date = dr.GetDateTime(3); 

should be: 应该:

objcomp.date = dr.IsDBNull(3) ? DateTime.MinValue : dr.GetDateTime(3); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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