You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.1 KiB
C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Newtonsoft.Json;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
namespace DS.Module.Core.Helpers
{
/// <summary>
/// 时间转换
/// </summary>
public class DatetimeJsonConverter : JsonConverter
{
/// <summary>
/// 是否可以转换
/// </summary>
/// <param name="objectType"></param>
/// <returns></returns>
public override bool CanConvert(Type objectType)
{
return true;
}
/// <summary>
/// 读json
/// </summary>
/// <param name="reader"></param>
/// <param name="objectType"></param>
/// <param name="existingValue"></param>
/// <param name="serializer"></param>
/// <returns></returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if ((reader.ValueType == null || reader.ValueType == typeof(DateTime?)) && reader.Value == null)
{
return null;
}
else
{
DateTime.TryParse(reader.Value != null ? reader.Value.ToString() : "", out DateTime value);
return value;
}
}
/// <summary>
/// 写json
/// </summary>
/// <param name="writer"></param>
/// <param name="value"></param>
/// <param name="serializer"></param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value == null)
writer.WriteValue(value);
else if (value != null)
{
var years = DateTime.Parse(value.ToString()).Year;
if (years == 1900|| years == 2000 || years == 1901 || years == 1970)
{
writer.WriteValue("");
}
else
writer.WriteValue(value);
}
}
}
}