-1

In this team ASP.NET MVC project, there's a JPStudent index view with the lambda expression:

@Html.DisplayFor(modelItem => item.JPStartDate)

JPStartDate is a DateTime property of the JPStudent model. The Index view returns a time stamp with the date, but I need it to display only day, month and year.

I know the common answer is to convert the DateTime to string in order to do this. At first, I was going to convert it to string and add it as another property to the list, since I need to maintain the same lambda expression which returns item.JPStartDate (I'm not supposed to mess with that expression, as per team rules). I would've then switched out the item.JPStartDate in the expression for the new property. However, I get errors in my model file when I try to add the date string as a new property in the properties list.

The JPStudentsController sets:

jPStudent.JPStartDate = DateTime.Now;

So I tried my string conversion to ddmmyy here, and got

Cannot implicitly convert string to DateTime

errors. I'm a little stumped here. I need to extract only the day, month and year but without messing with the way the Index view is set up to return the date property to the view.

Does anyone have any suggestions in this particular situation? I may be missing some simple way of doing it that I'm just not thinking of right now. If anyone has any suggestions for isolating day, month and year from DateTime, I'd really appreciate it!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
FreddieMercury
  • 191
  • 1
  • 13
  • 1
    possible duplicate: https://stackoverflow.com/questions/27561530/how-to-remove-time-portion-of-date-in-c-sharp-in-datetime-object-only – jazb Dec 08 '18 at 00:31
  • Thank you, JohnB. I'm having a look right now. – FreddieMercury Dec 08 '18 at 00:38
  • Can you use DisplayTemplates? see https://stackoverflow.com/questions/6365633/what-is-the-html-displayfor-syntax-for – Phil M Dec 08 '18 at 00:46
  • 1
    Check out: https://stackoverflow.com/questions/28114874/html-displayfor-dateformat-mm-dd-yyyy – marc_s Dec 08 '18 at 09:20

2 Answers2

1

You are trying to get the year, month and day from a DateTime? Is that correct? If so, you can just use the Day, Month and Year properties:

        var jpStartDate = DateTime.Now;
        var day = jpStartDate.Day;
        var month = jpStartDate.Month;
        var year = jpStartDate.Year; 
Jon Vote
  • 604
  • 5
  • 17
1

By this way you will change the value: DateTime jpStartDate = DateTime.Now;

DateTime reduced = new DateTime(jpStartDate.Year, jpStartDate.Month, jpStartDate.Day, 0, 0, 0);

or

reduced = jpStartDate.Date;

It depends if you want to change only visualisation or also a value.

VitezslavSimon
  • 342
  • 2
  • 7