format string to a year in csharp

To format a string to a year in C#, you can use the ToString() method with a custom format specifier for the year. Here's an example:

main.cs
DateTime date = DateTime.Now;
string year = date.ToString("yyyy");
Console.WriteLine(year);
92 chars
4 lines

In the example above, DateTime.Now gets the current date and time. The ToString() method is then called with the custom format specifier "yyyy" to retrieve only the year part of the date. The result is stored in the year variable, which can be displayed or used in further processing.

The "yyyy" format specifier represents a four-digit year. You can also use "yy" for a two-digit year.

Remember to include the using System directive at the top of your file to access the DateTime class.

This will output something like 2022 for the current year.

Note that if you have a specific date stored in a string, you can parse it into a DateTime object before formatting it as shown above.

related categories

gistlibby LogSnag