Search code examples
c#asp.netdatetimeasp.net-mvc-4aps

can not fomat data and time correctly in net core


I am a compelte Knowbie so excuse my quesstion if it comes across dumb, i have created a small web application at the folliwng https://wireme.co.uk/BookList but i can not get the date to display correctly, not sure what i am doing wrong, please see my code below:

using Microsoft.VisualBasic;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;


    namespace BookListRazor.Model
    {
        public class Book
        {
            [Key]
            public int PO { get; set; }
            [Required]
            public string Creator { get; set; }
            [Required]
            public string Company { get; set; }
    
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
            public DateTime Date { get { return Mydate; } set { Mydate = value; } }
    
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
    
            public DateTime Mydate = DateAndTime.Now;
            [DataType(DataType.Date)]
            [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy")]
            public DateTime MyDate { get; set; }
            
    
    
    
        }
    
    
    }

Solution

  • You can use string to display it :

    [DataType(DataType.Date)]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
    public string MyDate { get; set; }
    

    You can convert DateTime to string using Book's class constructor :

         public Book()
          {
            this.MyDate = Mydate.ToString();
          }
    

    I would also change DateAndTime to DateTime as long as you declare using c# :

        public DateTime Mydate = DateTime.Now;
    

    OR

    What I would do is reducing amount of properties. If I understand correctly what you want to achive, this should be enough :

            public class Book
            {
                [Key]
                public int PO { get; set; }
                [Required]
                public string Creator { get; set; }
                [Required]
                public string Company { get; set; }
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
                public string MyDate { get { return DateTime.Now.ToString(); } set { } }
    
            }