Nullable<System.DateTime>日期格式转换 (转载)
一、问题
1、html页面中时间显示出错,数据库中时间是正确的。
原因:没有把DateTime转成String类型。
2、 在C#中,发现不能直接使用ToString("yyyy-MM-dd HH:mm")这样的格式进行日期格式转换。
原因:在DB中,字段设置为Nullable<System.DateTime>,是可空的DateTime类型。
二、解决方案
if (user.BirthDate.HasValue)
{
userInfo.BirthDate = user.BirthDate.Value.ToString("yyyy-MM-dd");
}else
{
userInfo.BirthDate = string.Empty;
}
三、完整案例
public UserInfo GetUserNoPasswordByUserName(string userName) { var user= db.T_User.Select(d => new { Address = d.Address, BirthDate = d.BirthDate, Company = d.Company, Phone = d.Phone, RealName = d.RealName, TelPhone = d.TelPhone, TypeID = d.TypeID, UserID = d.UserID, UserName = d.UserName, UserStatus = d.UserStatus }).Where(d => d.UserName == userName).SingleOrDefault(); UserInfo userInfo = new UserInfo(); userInfo.Address = user.Address; if (user.BirthDate.HasValue) { userInfo.BirthDate = user.BirthDate.Value.ToString("yyyy-MM-dd"); }else { userInfo.BirthDate = string.Empty; } userInfo.Company = user.Company; userInfo.Phone = user.Phone; userInfo.RealName = user.RealName; userInfo.TelPhone = user.TelPhone; userInfo.TypeID = user.TypeID; userInfo.UserID = user.UserID; userInfo.UserName = user.UserName; userInfo.UserStatus = user.UserStatus; return userInfo; }
//自定义视图数据类 public class UserInfo { public int UserID { get; set; } public string UserName { get; set; } public Nullable<short> TypeID { get; set; } public short UserStatus { get; set; } // public string Password { get; set; } public string RealName { get; set; } public string Company { get; set; } public string BirthDate { get; set; } public string Phone { get; set; } public string TelPhone { get; set; } public string Address { get; set; } }
//数据实体类 public partial class T_User { public int UserID { get; set; } public string UserName { get; set; } public Nullable<short> TypeID { get; set; } public short UserStatus { get; set; } public string Password { get; set; } public string RealName { get; set; } public string Company { get; set; } public Nullable<System.DateTime> BirthDate { get; set; } public string Phone { get; set; } public string TelPhone { get; set; } public string Address { get; set; } }
转载来源:https://blog.csdn.net/baidu_34331194/article/details/68944906
树立目标,保持活力,gogogo!