DateOnly And TimeOnly In C#

DateOnly

  • The new DateOnly struct can be used when we simply want to express the date component. a historical record, where the fact of the occurrence is more important to us than the precise minute it occurred

Syntax:

var date  = new DateOnly(Year, Month, Day);

Example:

var date = new DateOnly(2000, 3, 17);

Functions:

There are 4 functions:

  1.  AddDays(int day)
  2. AddMonths(int month)
  3. AddYears(int year)

Example:

var date = new DateOnly(2019,05,21);
Console.WriteLine(date);

Output:

21/05/2019

1. AddDays()

Example:

var addDay = date.AddDays(1);
Console. WriteLine(addDay);

Output:

22/05/2019

2. AddMonths()

Example:

var addMonth = date.AddMonths(1);
Console. WriteLine(addMonth);

Output:

22/06/2019

3. AddYears()

var addYear = date.AddYears(1);
Console. WriteLine(addYear);

Output:

22/06/2020

TimeOnly

  • When we are only interested in the time component, we can utilise the new TimeOnly struct.

Syntax:

TimeOnly(int hour, int minute)
TimeOnly(int hour, int minute, int second)
TimeOnly(int hour, int minute, int second, int millisecond)

Example:

var time = new TimeOnly(10,30);

Output:

10:30 AM

Functions:

There are 2 functions:

  1. AddHours()
  2. AddMinutes()

Example:

var time = new TimeOnly(10,30);
Console. WriteLine(time);

Output:

10:30 AM

1. AddHours()

Example:

var addHour = time.AddHours(2);
Console. WriteLine(addHour);

Output:

11:30 AM

2. AddMinutes()

Exmaple:

var addMinute = time.AddMinutes(5);
Console. WriteLine(addMinute);

Output:

11:35 AM

 

 

 

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories