convert string to a date and format in csharp

To convert a string to a date and format it in C#, you can use the DateTime.ParseExact or DateTime.TryParseExact methods to parse a string with a specific format and convert it to a DateTime object. Then, you can use the .ToString method with a custom format string to format the DateTime object into a desired string representation.

Here's an example:

main.cs
// Input string
string dateString = "2021-12-31";

// Parse the string with a specific format
DateTime date = DateTime.ParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture);

// Format the DateTime object into a desired string representation
string formattedDate = date.ToString("dd/MM/yyyy");

// Output the formatted date
Console.WriteLine(formattedDate); // Output: 31/12/2021
393 chars
12 lines

In the example above, we first parse the input string "2021-12-31" using the DateTime.ParseExact method with the format "yyyy-MM-dd". This format specifies that the string should have the year in four digits, followed by a hyphen, followed by the month in two digits, another hyphen, and finally the day in two digits.

Then, we format the DateTime object into our desired string representation using the .ToString method with the custom format string "dd/MM/yyyy". This format specifies that the output string should have the day in two digits, followed by a slash, followed by the month in two digits, another slash, and finally the year in four digits.

Finally, we output the formatted date, which is "31/12/2021" in this case.

Note that the CultureInfo.InvariantCulture parameter is used to specify the culture settings for parsing and formatting, making it culture-independent and avoiding any potential issues with different date formats in different regions.

related categories

gistlibby LogSnag