简体   繁体   English

格式化C#对象列表中的所有日期属性

[英]Formatting all date properties in C# object list

I'm having huge issues with formatting the DateTime of each date property within a list of objects. 我在格式化对象列表中每个日期属性的DateTime时遇到了很大的问题。 Here's a few examples of what I've tried so far: 这是到目前为止我尝试过的一些示例:

var data = vulnerabilityList.Skip(skip).Take(pageSize).ToList()
    .Select(v => { v.PublishedDate = 
    v.PublishedDate.ToString("dd/MM/yyyy"); return v; });

and

var data = vulnerabilityList.Skip(skip).Take(pageSize).ToList()
    .Select(v => { v.PublishedDate = 
        DateTime.ParseExact(v.PublishedDate.ToString(), "dd/MM/yyyy", 
            CultureInfo.CurrentCulture); return v; });

Ultimately I want the format as 31/12/2017 and it'll be returned as JSON so it seems the data annotations on the vulnerability class are ignored. 最终,我希望格式为31/12/2017,并且将以JSON格式返回,因此似乎忽略了漏洞类上的数据注释。 The first example doesn't compile as obviously it's trying to set a DateTime as a string, but I included it as an example of what I'm looking to do. 第一个示例显然没有编译,因为它试图将DateTime设置为字符串,但是我将其作为示例进行了说明。

Thanks 谢谢

A datetime is a representation of a date and time using a number, and it doesn't have an inherent format. datetime是使用数字表示日期和时间的格式,它没有固有的格式。 It's intended for you to format it how you want it when you read it or display it to users. 它旨在让您在阅读或显示给用户时对其进行格式化。 So doing something like this: 所以做这样的事情:

v.PublishedDate = (DateTime)v.PublishedDate.ToString("dd/MM/yyyy")

Is only going to set the publish date to dd/MM/yy 00:00:00 (if it did work). 仅将发布日期设置为dd / MM / yy 00:00:00(如果它可以正常工作)。

I believe what you'll need to do is either change how you're parsing your JSON in the end, or store the DateTime as a string in a new property for reading. 我相信您需要做的是要么更改最终解析JSON的方式,要么将DateTime作为字符串存储在新属性中以进行读取。

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

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