Home Search Contact us About us
Title C# Dates and Times
Summary How to use and format dates and times in C#.
Contributor John McTainsh
Published 31-Jan-2001
Last updated 31-Jan-2001
Page rating   67% for 21 votes Useless Brilliant

Description

The DateTime class allows the formatting and managing of date and time. Of particular interest to international applications is the ability to format strings according to locality.

includes

To use dates and times it is necessary to use include the following.

    using System;                                   //Date time
    using System.Globalization;                     //Date Formatting

Modifying Dates

Simple addition and subtraction can be applied to DateTime as follows. The following determines the date that is 31 days after 25-Jan-2001.

    DateTime dtAccountOpened = new DateTime( 2001, 1, 25 );
    DateTime dtPaymentDue = dtAccountOpened.AddDays( 31.0 );

Formatting to a specific layout

Use the following to format my birthday to 2-Jun-1965.

    DateTime dtNow = DateTime.Today;                //Now is not necessary
    string sText = dtNow.Format( "d-MMM-yyyy", DateTimeFormatInfo.InvariantInfo );

Formatting to a specific locality

The following code will output "22/06/1965 09:00:00" in New Zealand and "06/22/1965 09:00:00" in USA. Note the month and day is placed in the local format.

    DateTime dtNow = DateTime.Now;
    string sNow = dtNow.Format( "G", DateTimeFormatInfo.CurrentInfo );
Comments Date
thanks 28-Jan-2004 Turmace
ive been looking all over the place tryn to figure this out!! lol
thanks!!!!
17-May-2004 C# Beginner
Good One
Home Search Contact us About us