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; }
            
    
    
    
        }
    
    
    }

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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 { } }

        }


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x