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

How to convert int

to DateTime

file cshtml

using a razor?

For example, date=201411

should be converted to 2014 November

. I tried using:

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

      

+3


source to share


2 answers


It's not an int but a string, however, use MM

for months, otherwise it's minutes:

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

      



If you want to use year / month DateTime.Year

/ DateTime.Month

:

int year = dt.Year;
int month = dt.Month;

      

+3


source


A possible solution is to simply create 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 DateTime as "2014 November"

, use formatting like:

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

      

+2


source







All Articles