|
|
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 |
|
|
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 );
|