合并实体模型(不为 空/0 字段的更新)
/// <summary>
/// 合并实体模型(不为 空/0 字段的更新)
/// </summary>
/// <typeparam name="T">源实体类型</typeparam>
/// <typeparam name="S">最终合并后返回的实体类型</typeparam>
/// <param name="tModel">源数据实体</param>
/// <param name="outModel">最终合并后返回的实体</param>
/// <returns>最终实体</returns>
public static S EntityMerge<T, S>(T tModel, S outModel)
{
Type type = tModel.GetType();
Type outType = outModel.GetType();
var properties = type.GetProperties();
var outProperties = outType.GetProperties();
foreach (var property in properties)
{
foreach (var item in outProperties)
{
var value = property.GetValue(tModel);
var ifchange = value != null && value.ToString() != "" && value.ToString() != "0" && !value.ToString().EqualsIgnoreCase("false") ? true : false;
if (property.Name == item.Name && ifchange)
{
item.SetValue(outModel, value, null);
break;
}
}
}
return outModel;
}
年月日转换-两个日期相差_年_月_天
public ActionResult Testdate()
{
DateTime dt1 = Convert.ToDateTime("2018-9-20");
DateTime dt2 = DateTime.Now;
int Years = dt2.Year - dt1.Year;
int Months = (dt2.Month - dt1.Month) ;
int Days = dt2.Day - dt1.Day;
string res = "";
if (Years >= 1)
{
if (Months > 0)
{
//如果年大于1 并且 月份也是大于当前月份 年份和月份差 都是准确的
if (Days >= 0)
{
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
else
{
Months = Months - 1;
DateTime newdt = new DateTime(DateTime.Now.Year,DateTime.Now.Month,1);
newdt = newdt.AddDays(-1);
int curmonthdays = newdt.Day;
Days = curmonthdays + Days;
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
}
else if (Months == 0)
{
if (Days >= 0)
{
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
else
{
Years = Years - 1;
Months = 11;
DateTime newdt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
newdt = newdt.AddDays(-1);
int curmonthdays = newdt.Day;
Days = curmonthdays + Days;
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
}
else //如果月份小于0,则不满一年
{
Years = Years - 1;
if (Days >= 0)
{
//如果是天数大于等于0,则用12加
Months = 12 + Months;
res = Years + "年" + Months + "月" + Days + "天";
}
else
{
//如果是天数小于0,则用11加
Months = 11 + Months;
DateTime newdt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
newdt = newdt.AddDays(-1);
int curmonthdays = newdt.Day;
Days = curmonthdays + Days;
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
}
}
else//当前时间减去入职时间,不到一年,直接算月份和天数
{
if (Years == 0)//同一年
{
if (Months > 0)
{
//如果年大于1 并且 月份也是大于当前月份 年份和月份差 都是准确的
if (Days >= 0)
{
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
else
{
Months = Months - 1;
DateTime newdt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
newdt = newdt.AddDays(-1);
int curmonthdays = newdt.Day;
Days = curmonthdays + Days;
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
}
else if (Months == 0)
{
if (Days >= 0)
{
//不处理
res = Years + "年" + Months + "月" + Days + "天";
}
}
}
}
var result = res;
return View();
}