Display years in different formats with C# DateTime

CsharpProgrammingServer Side Programming

Set a DateTime object;

DateTime dt = DateTime.Now;

To get years in different formats, try the following −

dt.ToString("yy")
dt.ToString("yyy")
dt.ToString("yyyy")
dt.ToString("yyyyy")

Here is the complete code −

Example

 Live Demo

using System;
using System.Threading;
using System.Diagnostics;
public class Demo {
   public static void Main() {
      DateTime dt = DateTime.Now;
      // Today's date
      Console.WriteLine("Today = {0}", DateTime.Today);
      Console.WriteLine("Displaying current year in dufferent formats:");
      Console.WriteLine(dt.ToString("yy"));
      Console.WriteLine(dt.ToString("yyy"));
      Console.WriteLine(dt.ToString("yyyy"));
      Console.WriteLine(dt.ToString("yyyyy"));
   }
}

Output

Today = 9/4/2018 12:00:00 AM
Displaying current year in dufferent formats:
18
2018
2018
02018
raja
Published on 04-Sep-2018 17:30:17
Advertisements