Convert string to date time in a `cshtml` file using razor?

6.1k views Asked by At

How can I convert an int to DateTime in a cshtml file using razor ?

For example date=201411 should get converted to 2014 November. I tried to use:

DateTime.TryParse(date);
DateTime.ParseExact(date, "yyyymm");
2

There are 2 answers

0
Tim Schmelter On BEST ANSWER

It's not an int but a string, however, use MM for the months otherwise it's minutes:

DateTime dt = DateTime.ParseExact("201411", "yyyyMM", null); // null means current-culture

If you want the year/month use DateTime.Year/DateTime.Month:

int year = dt.Year;
int month = dt.Month;
0
Dmitry Bychenko On

Possible solution is just to create a DateTime:

  int source = 201411;
  // You can't remove the day from DateTime, so let it be the 1st Nov 2014
  DateTime result = new DateTime(source / 100, source % 100, 1);

To output the DateTime as "2014 November" use formatting, e.g.:

  //TODO: Put the right culture 
  String text = result.ToString("yyyy MMMM", CultureInfo.InvariantCulture);