0

I`m trying to convert date from 01/01/2019 02:00:00 into 01/01/2019 datetime object. However, the string is transformed like 01/01/2019 but the try parse exact returns again the first option.

and also, I would like in my view to show the date, but not in 01/01/2019 format. I would like to have 1st Jan 2019

What I`m doing wrong?

Here is my code.

public DateTime ConvertDate(DateTime dt)
{
        var datestring = dt.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);
        DateTime datePostedObj;
        DateTime.TryParseExact(datestring,
                               "MM/dd/yyyy",
                               null,
                               DateTimeStyles.None,
                               out datePostedObj);

        return datePostedObj.Date;
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Csibi Norbert
  • 780
  • 1
  • 11
  • 35
  • You mean `datePostedObj.Date` does contains a time component, right? – XouDo May 04 '19 at 11:23
  • 1
    I'm afraid your question is unclear (to me, at least) - could post a [mcve]? The formatting part should probably be a separate question (after you've researched it and tried to solve it yourself - so you can show that attempt in the new question). It's not clear to me why you're formatting and then reparsing to start with, to be honest. Why not just use `dt.Date`? – Jon Skeet May 04 '19 at 11:25
  • @XouDo when I pass the dt to the method I have a datetime with time. Then, I make that dt to string so that I will capture only date without time. The datePostedObj has a date but with time again. So I would like to have a datetime obj without time. – Csibi Norbert May 04 '19 at 12:28
  • @JonSkeet Thanks for your time. Well, I use dt.Date as you said but insead of having the DATE only, I still have the date & time.. if u understand what I`m saying. – Csibi Norbert May 04 '19 at 12:30
  • 1
    Not really. `DateTime` is *always* a date and time. There's no notion of a "date only" `DateTime` value... there's just a `DateTime` at midnight. If you want a "date only" value, you'd need to use something like my [Noda Time](https://nodatime.org) library which has separate types for "date", "date and time", "instant in time" etc. – Jon Skeet May 04 '19 at 12:32
  • @JonSkeet thanks, now I understand what`s happening. – Csibi Norbert May 04 '19 at 12:35

1 Answers1

4

You are doing some rework.

You have already dt as a Datetime. You generate it's textual (aka string) representation, then parse it to DateTime again. That's unnecessary.

If you want to get your date part "only", you can get dt.Date as a Datetime.

If you want to get "1st Jan 2019" as a string representation from your dt, you can do some work since .NET Framework doesn't have a built-in function for day name suffix. But how you can do it is explained on Getting day suffix when using DateTime.ToString() topic as well.

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364