【问题标题】:can not fomat data and time correctly in net core无法在 net core 中正确格式化日期和时间
【发布时间】:2020-11-24 11:59:57
【问题描述】:

我是一名专业知识分子,如果遇到愚蠢的问题,请原谅我的问题,我在以下地址创建了一个小型 Web 应用程序 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; }
            
    
    
    
        }
    
    
    }

【问题讨论】:

  • 也许这与日期格式中缺少右花括号}有关

标签: c# asp.net datetime asp.net-mvc-4 aps


【解决方案1】:

您可以使用 string 来显示它:

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

您可以使用 Book 的 类构造函数将 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 { } }

        }

【讨论】:

  • 嗨,迈克,尝试过,但出现以下错误“InvalidCastException:无法将'System.DateTime'类型的对象转换为'System.String'..” - 有什么想法吗??
  • 错误的原因是将 ruturn 值作为 Date 并且由于 udpate 您返回字符串。
猜你喜欢
  • 1970-01-01
  • 2017-04-10
  • 2022-10-04
  • 2017-12-29
  • 1970-01-01
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多