CODEDIGEST
Home Articles CodeDigest Tutorials FAQs
Skip Navigation LinksHome » Article » ASP.Net Article » Working with DateTime Object and Formatting DateTime Object in ASP.Net   You are not logged in.
Search
 

Technologies
 

Sponsors
 

CodeDigest Navigation
 

Technology News
 

Community News
No News Feeds available at this time.
 
Working with DateTime Object and Formatting DateTime Object in ASP.Net

By BalaMurugan
Posted On Jul 02,2009
Article Rating: (Login)
Be first to rate
this article.
No of Comments: 0
Print this article.
Category: ASP.Net

Subscribe to our feed!

Working with DateTime Object and Formatting DateTime Object in ASP.Net

 

DateTime is one of the most frequently used objects in any project we work. Most often, we get requirements to do some basic operations like formatting, adding, comparing on the datetime objects in our projects. This article will help us to understand the DateTime object and other operation we can do with datetime object.

DateTime structure is a value type that resides in the namespace System. According to msdn, the DateTime value type represents dates and times with values ranging from 12:00:00 midnight, January 1, 0001 Anno Domini (Common Era) through 11:59:59 P.M., December 31, 9999 A.D. (C.E.).

With this information, we will move forward to understand some of the very useful basic operations on DateTime object.

TimeSpan Object

TimeSpan object (a structure again) is one of the important object that helps us in performing various operations on DateTime object. It basically represents a time interval in terms of days, hours, minutes, seconds and fractions of seconds. Basically, a TimeSpan object can be used to store the result of DateTime objects operations like addition, subtraction in terms of a time interval.

 

Basics of DateTime Objects

To get the current date and time,

DateTime dtNow = DateTime.Now;

 

The property Now will return the current system date and time represented in local time. The property Today will get you the current date.

 

To get the current Coordinated Universal Time (UTC) date and time,

DateTime dtNow = DateTime.UtcNow;

 

Operations on DateTime Objects

DateTime Addition

DateTime object is packed with number of methods to perform addition operations. For example, to add number days, hours, minutes, etc.

DateTime.Add(TimeSpan value)

DateTime.AddDays(double value)

DateTime.AddHours(double value)

DateTime.AddMilliseconds(double value)

DateTime.AddMinutes(double value)

DateTime.AddMonths(int value)

DateTime.AddSeconds(double value)

DateTime.AddTicks(double value)

DateTime.AddYears(int value)

 

To add one year(365 days, a non leap year) with current DateTime,

 

TimeSpan tsYear = new TimeSpan(365, 0, 0, 0, 0);

DateTime dtNow = DateTime.Now;

Response.Write("Add Time Span: " + dtNow.Add(tsYear).ToString());

 

Rest of the above addition operations are self explanatory.

 

DateTime Subtraction

Subtraction operations on DateTime object can be done on 2 ways,

1.      A DateTime object can be subtracted with another DateTime object which will return a TimeSpan object.

DateTime dtNow = DateTime.Now;

DateTime dtDate = DateTime.Today;

TimeSpan ts = dtNow.Subtract(dtDate);

Response.Write("Subtract(DateTime.Now - DateTime.Today): " + ts.ToString());

2.      A DateTime object can be subtracted with a TimeSpan object to return a Date. For example, to subtract 365 days(a non leap year) from today,

TimeSpan tsYear = new TimeSpan(365, 0, 0, 0, 0);

DateTime dtNow = DateTime.Now;

DateTime dtResult = dtNow.Subtract(tsYear);

Response.Write("Subtract(DateTime.Now - new TimeSpan(365, 0, 0, 0, 0)): " + dtResult.ToString());

 

DateTime Comparison

To compare 2 DateTime object, we can use DateTime.Compare(DateTime, DateTime)/ DateTime.CompareTo(DateTime) methods, both return integer. Return value 0 indicates both are equal, a negative return value indicates first argument is earlier than second and positive return value indicates first is later than second.

Let us see all the 3 cases with an example,

 

Case 1

DateTime dtNow = DateTime.Now;

DateTime dtNow2 = DateTime.Now;

        if (DateTime.Compare(dtNow, dtNow2) == 0)

        {

            Response.Write(dtNow.ToString() + " is same as " + dtNow2.ToString());

        }

        else if (DateTime.Compare(dtNow, dtNow2) < 0)

        {

            Response.Write(dtNow.ToString() + " is earlier than " + dtNow2.ToString());

        }

        else

        {

            Response.Write(dtNow.ToString() + " is later than " + dtNow2.ToString());

        }

Result

28/06/2009 13:16:35 is same as 28/06/2009 13:16:35

 

Case 2

Try the below code,

DateTime dtNow = DateTime.Now;

       DateTime dtNow2 = DateTime.Now;

       dtNow2 = dtNow2.Add(tsYear); 

        if (DateTime.Compare(dtNow, dtNow2) == 0)

        {

            Response.Write(dtNow.ToString() + " is same as " + dtNow2.ToString());

        }

        else if (DateTime.Compare(dtNow, dtNow2) < 0)

        {

            Response.Write(dtNow.ToString() + " is earlier than " + dtNow2.ToString());

        }

        else

        {

            Response.Write(dtNow.ToString() + " is later than " + dtNow2.ToString());

        }

Result

28/06/2009 13:16:35 is earlier than 28/06/2010 13:16:35

 

Case 3

DateTime dtNow = DateTime.Now;

       DateTime dtNow2 = DateTime.Now;

        TimeSpan tsYear = new TimeSpan(365, 0, 0, 0, 0);

        dtNow2 = dtNow2.Subtract(tsYear);

        if (DateTime.Compare(dtNow, dtNow2) == 0)

        {

            Response.Write(dtNow.ToString() + " is same as " + dtNow2.ToString());

        }

        else if (DateTime.Compare(dtNow, dtNow2) < 0)

        {

            Response.Write(dtNow.ToString() + " is earlier than " + dtNow2.ToString());

        }

        else

        {

            Response.Write(dtNow.ToString() + " is later than " + dtNow2.ToString());

        }

Result

28/06/2009 13:28:05 is later than 28/06/2008 13:28:05

 



ASP.Net Hosting

Recent Articles

Formatting DateTime Objects

Formatting DateTime object to display date in different format is one another important task we often do in our projects.

 

Below you can find some of the datetime formatting methods that can be used to format date time,

 

DateTime dtNow = DateTime.Now;

Response.Write("Current Date and Time: " + dtNow.ToString() + "<br>");

Response.Write("Long Date: "+ dtNow.ToLongDateString() +"<br>");

Response.Write("Long Time: " + dtNow.ToLongTimeString() + "<br>");       

Response.Write("Short Time: " + dtNow.ToShortDateString() + "<br>");

Response.Write("Short Time: " + dtNow.ToShortTimeString() + "<br>");

 

OUTPUT

Current Date and Time: 28/06/2009 16:28:05

Long Date: 28 June 2009

Long Time: 16:28:05

Short Time: 28/06/2009

Short Time: 16:28:05

 

Most of the time, we will require to format the date time string various different formats. For example, “Sunday, August 11, 1981”, “Sunday, August 11, 1981 3:32:00 PM”, “Sunday, August 11, 1981 3:32:00 PM”, “Sunday, August 11, 1981 11:32:00 PM”, etc.

 

To make these custom format, we can set the datetime format in ToString(format) method.

 

For example,

 

Response.Write("Short Date: " + dtNow.ToString("d") + "<br>");

 

OUTPUT

Short Date: 28/06/2009

 

The below table list some of the format string that can be used to format datetime string,

Format Pattern

Description

Output

d

Short date

11/8/1981

D

Long date

Sunday, August 11, 1981

t

Short time

3:32 PM

T

Long time

3:32:00 PM

f

Full date/time
(short time)

Sunday, August 11, 1981 3:32 PM

F

Full date/time
(long time)

Sunday, August 11, 1981 3:32:00 PM

g

General date/time
(short time)

8/11/1981 3:32 PM

G

General date/time
(long time)

8/11/1981 3:32:00 PM

m or M

Month

August 11

r or R

RFC 1123

Sun, 11 Aug 1981 8:32:00 GMT

s

Sortable date/time

1981-08-11T15:32:00

u

Universable sortable date/time

1981-08-11 15:32:00z

U

Universable sortable date/time

Sunday, August 11, 1981 11:32:00 PM

y or Y

Year month

August, 1981

 

Apart from using the above formats, we can display DateTime string by our own custom formats using the formatting pattern characters d/M/y/h/m/s.

 

For example,

 

Response.Write("Current Date and Time: " + dtNow.ToString("d/m/yyyy") + "<br>");

 

OUTPUT:

Current Date and Time: 28/6/2009

 

The below table will list some of the combinations,

d/m/yyyy

28/6/2009

dd/MM/yyyy

28/06/2009

dddd dd,MM,yyyy

Sunday 28,06,2009

dddd dd-MM-yyyy

Sunday 28-06-2009

dd.MM.yyyy hh:mm

28.06.2009 05:00

MMMM,dddd-yyyy h:mm tt

June,Sunday-2009 4:59 PM

MMMM,dddd-yyyy h:mm:ss tt

June,Sunday-2009 4:59:09 PM

 

I have attached the source code discussed in this article in download section. You can download and see it in action.

 

Points to Consider

Ø       As any other value type, DateTime object will not allow null to be assigned. If you are assigning a datetime value from database column that allows null then you can declare the DateTime object as Nullable Datetime object.

            Declaring nullable DateTime,

       DateTime? dt = new DateTime();

            OR

       Nullable<DateTime> dt = new Nullable<DateTime>();

Ø       When assigning DateTime.MinValue to a DateTime object, remember the DateTime object minimum value of .net and sql server 2000 database are different. Read this for more info.

 

Reference

http://msdn.microsoft.com/en-us/library/system.datetime.aspx

http://msdn.microsoft.com/en-au/library/fht0f5be.aspx

 

Downloads

Download Source 

Conclusion

DateTime object is one of the most frequently object and we do lot of operation over this object.  After reading this article, you will be familiar in all the DateTime operations and formatting that can be done over the DateTime object. If there is a different format or format pattern that I have missed, please comment those in this article’s comment section.

 

Similar Articles
  • You can contribute to CodeDigest.Com:
    Article Feedback
    Title  
    Submitted By  
    Comment  
    Enter the verification number
     
    Comments