Date Manipulation using String and Regex

Hi Guys,

I have Two Question Like, I tried this “now.ToString(“d-MM-yyyy”)” it gives output 3-2-2023. but question is will the Single d will give all the dates in a month? and single M will give the all Months like 1 to 12?

and if string is like only this 03-02-2023 then how to manipulate it so it will take only 3-2-2023 using string manipulation and regex?

HI,

Single d or Single M is assigned as specific format. So if we need to express day or month, please add % character as the following image.

and if string is like only this 03-02-2023 then how to manipulate it so it will take only 3-2-2023 using string manipulation and regex?

There are several ways to achieve it. The following expression will work, for example.

System.Text.RegularExpressions.Regex.Replace("02-02-2023","\b0","")

image

Regards,

Hi @kuldeep.shinde

string dateString = "03-02-2023";
Regex regex = new Regex("^0");
dateString = regex.Replace(dateString, "");

The code uses a regular expression pattern to match any leading zero in the date string and replaces it with an empty string. The result will be a string in the format “3-2-2023”.

1 Like

Yes it will @kuldeep.shinde

i dont understand why you want to use regex and string manipulation , but for reference Alternate way can be

DateTime.ParseExact("15-02-2023",{"dd-MM-yyyy","d-M-yyyy"},System.Globalization.CultureInfo.InvariantCulture,System.Globalization.DateTimeStyles.None).ToString("d-M-yyyy")

Regards
Sudharsan

1 Like

Thank you @Yoichi @Sudharsan_Ka @Shanmathi for your Reply and Solutions to my Questions:)

1 Like