0

I have a <table> and i want in one <td>, to show date time like this: 04/2017 Its April, 2017:

<td class="card-date">
   @Html.DisplayFor(Function(modelItem) item.CreditCardExpirationDate.Month) +"/"+ 
   @Html.DisplayFor(Function(modelItem) item.CreditCardExpirationDate.Year)                                           

</td>

But the year is in 4 digit format, i need just 2 digits. And i need to add zero before the month. so it be 04 and not just 4. Thx.

Example Image

Ballon Ura
  • 882
  • 1
  • 13
  • 36

2 Answers2

4

You can use a custom format string:

item.CreditCardExpirationDate.ToString("MM\/yy")

Quoted from the documentation:

  • MM: The month, from 01 through 12.
  • \/: The literal character /.
  • yy: The year, from 00 to 99.

Note: If CreditCardExpirationDate is a DateTime? instead of a DateTime, you'll have to use ?.ToString instead of .ToString.

Since MVC does not allow you to call methods in DisplayFor, you need to annotate your model property instead: (I use C# syntax, since the link in your screen shot shows that your model is written in C#.)

[DisplayFormat(DataFormatString = @"{0:MM\/yy}")]
public DateTime CreditCardExpirationDate { get; set; }
Community
  • 1
  • 1
Heinzi
  • 167,459
  • 57
  • 363
  • 519
0

Sorry, I am no VB programmer, but in C# i would use DateTime and the Date Format strings:

// assuming item.CreditCardExpirationDate is DateTime
DateTime date = item.CreditCardExpirationDate;
var month = date.ToString("MM"); // month, leading zero
var year = date.ToString("yy"); // year, two digits

I hope you can adapt this to VB.

Georg Patscheider
  • 9,357
  • 1
  • 26
  • 36