无法在 net core 中正确格式化日期和时间

can not fomat data and time correctly in net core

我是一个知识渊博的人,所以请原谅我的问题,如果遇到愚蠢的问题,我已经在下面创建了一个小型网络应用程序 https://wireme.co.uk/BookList 但我无法正确显示日期,不确定我是什么我做错了,请看下面我的代码:

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

你可以用字符串来显示它:

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

您可以使用 Book 的 class 构造函数将 DateTime 转换为字符串:

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

只要您使用 c# 声明,我也会将 DateAndTime 更改为 DateTime :

    public DateTime Mydate = DateTime.Now;

我会做的是减少属性的数量。如果我正确理解你想要达到的目标,这应该足够了:

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

        }