Convert Decimal to Date Value

kynaplt1665 21 Reputation points
2022-04-06T23:07:29.637+00:00

Hi.

I have a program in MVC.
It gets data from AS400 such as birthday and display it but in decimal like 06051985. I want it to be displayed in 06/05/1985.
How will I do it and where (View, Model, Controller?).

Thanks.

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,178 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,263 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jaliya Udagedara 2,731 Reputation points MVP
    2022-04-06T23:40:00.673+00:00

    You can do something like below by having a GETTER only property in your Model.

    MyModel myModel = new MyModel { BirthdayAsInt = 06051985 };
    Console.WriteLine(myModel.Birthday); // 06/05/1985
    
    public class MyModel
    {
        public int BirthdayAsInt { get; set; }
    
        public string Birthday
        {
            get
            {
                // TODO: Validate BirthdayAsInt is in the expected format, otherwise below can throw can error
                // Or make the following code defensive
    
                string birthdayAsString = BirthdayAsInt.ToString("D8");
    
                int date = Convert.ToInt32(birthdayAsString.Substring(0, 2));
                int month = Convert.ToInt32(birthdayAsString.Substring(2, 2));
                int year = Convert.ToInt32(birthdayAsString.Substring(4, 4));
    
                return new DateTime(year, month, date).ToString("dd/MM/yyyy");
            }
        }
    }
    
    0 comments No comments

0 additional answers

Sort by: Most helpful