假设C#中的类如下:
[Serializable]
[JsonObject]
public class HistoricalValue
{
[JsonProperty("record_date")]
public string RecordDate { get; set; }
[JsonProperty("pay_date")]
public string PayDate { get; set; }
[JsonProperty("ex_div_date")]
public string ExDivDate { get; set; }
}
能够将属性中属于字符串类型的DateTime数据格式化为特定日期时间字符串格式,让我们说“dd-MMM-yyyy”对我非常有益。是否有可能通过属性实现这一目标? 我尝试了以下代码但没有成功:
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString ="{0:dd-MMMM-yyyy}")]
public string PayDate { get; set; }
答案 0 :(得分:1)
我有一些处理DateTimes的规则。没有特别的顺序:
针对您的具体情况: 我不会将DateTime作为字符串公开。我将它公开为DateTime实例。将其转换为字符串应该留给GUI和Serialize / Deseriablize函数。
如果我认为它总是另一端的另一个.NET应用程序,我甚至可以考虑将DateTime作为Tick计数(有效的大整数)进行转换。当然,使用JSON,你可能会想要类似字符串的东西。
答案 1 :(得分:0)
我通过创建自定义Json转换器解决了这个问题。
public class JsonDateTimeConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return reader.Value.ToString().DateTimeFormatter("dd-MMM-yyyy");
}
public override bool CanWrite
{
get { return false; }
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
}
}
然后你可以像这样使用它:
[JsonProperty("inception_date")]
[JsonConverter(typeof(JsonDateTimeConverter))]
public string InceptionDate { get; set; }
DateTimeFormatter是一种扩展方法。
public static string DateTimeFormatter(this string possibleDatetime, string format)
{
DateTime result;
if( DateTime.TryParse(possibleDatetime, out result))
{
return result.ToString(format);
}
return possibleDatetime;
}