0

I'm working on my first project in asp.net core razor pages and trying to add a creation date time field to my Article model which is by default filled with current date time. I have defined it liked this:

[Required]
[DataType(DataType.DateTime)]
public DateTime CreationDate { get; set; } = DateTime.Now;

when I visit the Article creation page, it is shown like this:

2019/02/02 09:25:36.377 PM

I don't want the second and millisecond to be shown here, but couldn't find a way to remove them. Any help would be appreciated.

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
stratauren
  • 3
  • 1
  • 2
  • _[DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm}")]_ – Steve Feb 02 '19 at 18:32
  • please review https://stackoverflow.com/q/1004698/125981 – Mark Schultheiss Feb 02 '19 at 19:07
  • thanks @MarkSchultheiss, the link you pointed to actually solved the problem for me. – stratauren Feb 02 '19 at 19:14
  • I strongly suggest you read https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings and https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-date-and-time-format-strings . – Ian Kemp Feb 02 '19 at 19:55

2 Answers2

0

You problably want to either use DateTime.ToString(string) to show the date. For example CreationDate.ToString("yyyy/MM/dd HH:mm") would become 2019/02/02 09:25

Or you can use the DisplayFormat Attribute. Example

[Required]
[DataType(DataType.DateTime)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy/MM/dd HH:mm}")]
public DateTime CreationDate { get; set; } = DateTime.Now;
ZarX
  • 1,096
  • 9
  • 17
  • thanks to you and @Steve for your replies, but unfortunately [DisplayFormat(DataFormatString = "{0:yyyy/MM/dd HH:mm}")] doesn't solve the problem. also I can't use CreationDate.ToString("yyyy/MM/dd HH:mm") because i want the formatted date in the edit (creation) form of my article. – stratauren Feb 02 '19 at 18:51
  • @stratauren if you need to have the format also in edit mode add ApplyFormatInEditMode = true to the annotation – Steve Feb 02 '19 at 18:55
  • @Steve I did what you said, but now it only shows yyyy/MM/dd --:-- in my field not the current date time. – stratauren Feb 02 '19 at 18:57
0

Why not just (put this in the getter)

var newdate = CreationDate.AddTicks(-CreationDate .Ticks % TimeSpan.TicksPerMinute);

Or try this out c# 6+

[Required]
[DataType(DataType.DateTime)]
public DateTime CreationDate { get; set; } = DateTime.Now.AddTicks(-DateTime.Now.Ticks % TimeSpan.TicksPerMinute);
Mark Schultheiss
  • 32,614
  • 12
  • 69
  • 100