How to render DateTime in format DD/MM/YYYYTHH:mm ASP.NET CORE 5.0 MVC

I am trying to render DateTime in format DD/MM/YYYYTHH:mm in C# ASP.NET CORE 5.0 MVC but I am not sure is it good idea to render in backend side or in frontend. Since in frontend side I use DataTable Currently this is format which I get in my datatable

2021-03-05T13:22:48.3190414  

But I want to be formated as

05-03-2021T13:22

I try couple of solution something like in datatable

{
                "data": "dateAndTime", "width": "15%",
                "def": function () { return new Date(); },
                "displayFormat": 'DD/MM/YYYY',
                "wireFormat": 'YYYY-MM-DD',
                "keyInput": false
            },

 [Display(Name = "Datum i vrijeme slanja")]
        public DateTime DateAndTime { get; set; } = DateTime.Now;

Also in backend I try something like this:

ticketVM.Ticket.DateAndTime = DateTime.Parse("DD/MM/YYYY");

And get this kind of error

The string 'DD/MM/YYYY' was not recognized as a valid DateTime. There is an unknown word starting at index '0'.

Any advice and suggestion how to get format render in format DD/MM/YYYYTHH:mm ??

Answer

The Format String means it’s a string after format:

public string DateAndTime()
{
    return DateTime.Now.ToString("dd/MM/yyyy HH:mm");
}

You can replace :

[Display(Name = "Datum i vrijeme slanja")]
public DateTime DateAndTime { get; set; } = DateTime.Now;

to

[Display(Name = "Datum i vrijeme slanja")]
public string DateAndTime { get; set; } = DateTime.Now.ToString("dd/MM/yyyy HH:mm");

About the ToString rules you can see Fildor‘s commets : See Custom date and time format strings .

Leave a Reply

Your email address will not be published. Required fields are marked *