简体   繁体   English

无法将日期转换为特定格式

[英]Cannot convert date into specific format

I'm trying to convert a Date into a specific format, I saw a lot of questions here with the same target but all the proposed solutions return a string, I need to return a DateTime in my custom format. 我正在尝试将Date转换为特定格式,在这里我看到了很多目标相同的问题,但是所有建议的解决方案都返回一个字符串,我需要以自定义格式返回DateTime

This is my code: 这是我的代码:

private DateTime? _matchCalendarDate = DateTime.Now;

public DateTime? MatchCalendarDate
{
   get
   {
      var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");
      var c = DateTime.ParseExact(date, "dd-MM-yyyy", CultureInfo.InvariantCulture);
      return c;
   }
   set
   {
      _matchCalendarDate = value;
      OnPropertyChanged();
   }
}

this return: 8/15/2018 12:00:00 AM but should return 15/08/2018 此返回: 8/15/2018 12:00:00 AM但应返回15/08/2018

Return matchCalendarDate.Date; 返回matchCalendarDate.Date; returns the date component, time set to zero 返回日期部分,时间设置为零

When you say it returns 8/15/2018 12:00:00 AM , I'm guessing you're simply calling ToString() on the property, like so: 当您说它返回8/15/2018 12:00:00 AM ,我猜您只是在该属性上调用ToString() ,如下所示:

MatchCalendarDate.ToString();

The thing is, a DateTime object doesn't have it's own inherent 'format'. 问题是, DateTime对象没有它自己固有的“格式”。 It's format is whatever you want it to be. 它的格式是您想要的任何格式。

So when you actually use the property to print the value it returns, you can choose how you want it do be displayed. 因此,当您实际使用该属性来打印其返回的值时,可以选择希望其显示的方式。

Something like; 就像是;

MatchCalendarDate.ToString("dd-MM-yyyy");

But then, that essentially renders the conversion in your property redundant. 但是,从本质上讲,这会使属性中的转换变得多余。 So assuming your intention is to store a DateTime object, but retrieve it in the format you like, what you should do is declare a second string property that does the conversion for you. 因此,假设您打算存储DateTime对象,但以您喜欢的格式检索它,则应该声明一个第二个字符串属性,该属性为您完成转换。

You may have to consider converting to the original format first then to your required format 您可能需要考虑先转换为原始格式,然后再转换为所需格式

 private  DateTimeDateTime _matchCalendarDate, _matchCalendarD = DateTime.Now;

    public DateTime MatchCalendarDate
    {
       get
       {
          var date = _matchCalendarDate.Value.ToString("dd-MM-yyyy");

          var dt = DateTime.ParseExact(date, "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);

          var c = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);

          return c;
       }
       set
       {
          _matchCalendarDate = value;
          OnPropertyChanged();
       }
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM