c# can display date and time. In this article you will learn how to deal with date and time in c#.

Date is default, but time cannot go back earlier than 1970. Why? that’s when the logic was added to computers.

Date and time in c#

Example

The program below is an example of date and time in c#. The formatting is explicitly defined (%y for year, %m for month etc).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
using static System.Console;
using System;

class CustomTime
{
static void Main()
{
DateTime now = DateTime.Now;

Write("Date : ");
WriteLine(string.Format("{0:d MMMM, yyyy}", now));
Write("Time : ");
WriteLine(now.ToString("hh:mm:ss tt"));
}
}

The code above displays the date and time. You can use an alternative formatting if you want..
The output will be similar to this:

1
2
Date : 2018-06-07
Time : 10:38:01

Exercises

  1. Display date in DD/MM/YYYY format