Search code examples
c#datesimpledateformatdate-formattingdate-conversion

How to get the date from the given string in c#


I only need date from this string Wed, 02/05/2020 - 12:31 what format should I use whenever I am using {MM/dd/yyyy} I am getting the same value if there is any other way please let me know

        item.changed=Wed, 02/05/2020 - 12:31


    `if (ListRecord.checkresponse == "Response Letters")
                {
                
                string checkresponse = item.changed;
                string issueDate = string.Format("{0:MM/dd/yyyy}", checkresponse);

                 }`

Solution

  • To use date formatting, you need to start with a DateTime object, not a string.

    So in your scenario you'll have to parse your string as a DateTime, then format it out again to a different string format. There's no way to directly format string -> string, all the logic about formatting is in the DateTime class.

    Here's an example:

    string changed = "Wed, 02/05/2020 - 12:31";
    var checkresponse = DateTime.ParseExact(changed, "ddd, MM/dd/yyyy - HH:mm", CultureInfo.InvariantCulture);
    string issueDate = string.Format("{0:MM/dd/yyyy}", checkresponse);
    Console.WriteLine(issueDate);
    

    Demo: https://dotnetfiddle.net/bhNImo

    (Alternatively, since what you mainly want to do here is strip the first and last parts of the string and keep the date part, you could use a regular expression do to this from the string, but overall it's probably more reliably to use date parsing and formatting.)