user10230915
user10230915

Reputation: 23

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.

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

Upvotes: 0

Views: 298

Answers (3)

Sach
Sach

Reputation: 10393

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:

MatchCalendarDate.ToString();

The thing is, a DateTime object doesn't have it's own inherent 'format'. 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.

Upvotes: 1

kishea
kishea

Reputation: 637

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

Upvotes: 0

Aldert
Aldert

Reputation: 4313

Return matchCalendarDate.Date; returns the date component, time set to zero

Upvotes: 1

Related Questions