C#
  Home arrow C# arrow Page 3 - Working with Dates and Times in C#
ASP Free Forums 
.NET  
ASP  
ASP Code  
ASP.NET  
ASP.NET Code  
BrainDump  
C#  
Code Examples  
Database  
Database Code  
IIS  
Microsoft Access  
MS SQL Server  
Silverlight  
Visual Basic.NET  
Windows Scripting  
Windows Security  
XML  
Mobile Linux 
App Generation ROI 
IBM® developerWorks 
ASP Web Hosting  
ASP.NET Web Hosting 
Windows Web Hosting
 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid 
Request Media Kit
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
C#

Working with Dates and Times in C#
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 9
    2008-12-30

    Table of Contents:
  • Working with Dates and Times in C#
  • Brief Overview
  • Putting DateTime into Action
  • Final Words

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     
    ADVERTISEMENT


    Working with Dates and Times in C# - Putting DateTime into Action


    (Page 3 of 4 )

    Performing various operations with dates is something that we encounter during our programming endeavors. First, let's understand the basics. There are two functions, namely Add() and Subtract(), which we are going to present on this page. The similarity between these two is that neither actually modifies the current DateTime structure; rather, they just return another DateTime structure with new values.

    In order to get around this, often when the specific DateTime structure ought to be modified, we apply this technique in the following fashion (code sample below). Please notice that we're introducing a new TimeSpan structure, which is going to be used as the parameter of Add. The TimeSpan structure behaves just like DateTime. Its purpose is to represent time intervals. We're adding that interval to our DateTime structure.

    The major difference between the DateTime and TimeSpan structures is that the former describes an exact time and date at a given moment-it's instant; while the latter represents a time interval-it's an amount. Subtracting two DateTime structures from each other becomes instantly a TimeSpan structure.

    DateTime objDate1 = new DateTime.Now;

    DateTime objDate2 = new DateTime.UtcNow;

    TimeSpan tsDiff = new tsDiff.Parse(objDate1 - objDate2);

    objDate1 = objDate1.Add(tsDiff);

    There are numerous other variations of the Add method, such as the AddYears(), AddMonths(), AddDays(), AddHours(), AddMinutes(), AddSeconds(), AddTicks(), and so forth. The same applies to the Subtract() methods, too. Additionally, you can use simple arithmetic operators. For example:

    objDate1 = objDate1 + objDate2; // using traditional assignment

    objDate1 += objDate2; // using compact compound assignment i.e. +=

    Lately it's become quite common to be working within multinational corporations that are outsourcing dozens of projects literally everywhere. Multi-language support has become necessary, as well as the seamless integration of numerous time zones.

    In order to maintain our successful edge, we also need to learn how to accomplish conversions between local times and UTC. There are two universal methods which can help us out: ToLocalTime() and ToUniversalTime(), respectively. These methods work based on offsets; the structure itself cannot store whether a DateTime object is UTC or LocalTime. Therefore, be sure to double check the ways in which you rely on them.

    These methods as well as the LocalTime and UTC properties grab the settings out of your operating system, and if that is configured incorrectly, then the entire sand castle falls apart. Another important concept that we would find useful to know is formatting. There are various scenarios where we must adhere to strict rules according to which we need to print out or read in dates and times. So let's see what we can do.

    First, as we have already seen, the DateTime structure is composed of a date and time segment. These two segments have roughly three elements, meaning year, month, day, and hour, minutes, seconds, respectively (ignoring things like milliseconds). To format the output the way we need, we almost always need to begin with breaking these two main segments into individual parts, the date and the time.

    Once we end up with these as stand-alone parts, we can rely on numerous formatting methods to explicitly specify the style, fashion, trend, or simply culture to which we want the output to conform. The ToString() method converts the DateTime object into its exact full string representation. This is great when we want both parts. It also supports lots of extra formatting options if we rely on its formatting specifiers.

    Here's the entire list of specifiers - for a more detailed explanation, read the MSDN.

    Specifier : Example

    d : 10/28/2008

    D : Sunday, September 28, 2008

    f : Sunday, September 28, 2008 10:35 PM

    F : Sunday, September 28, 2008 10:35:23 PM

    g : 9/28/2008 10:35 PM

    G : 9/28/2008 10:35:23 PM

    m : September 28

    o : 2008-09-28T22:35:07.0000000

    R : Sun, 28 Sep 2008 22:35:23 GMT

    s : 2008-09-28T22:35:23

    t : 10:35 PM

    T : 10:35:23 PM

    u : 2008-09-28 22:35:23Z

    U : Sunday, September 28, 2008 7:35:23 PM

    y : September, 2008

    'h:mm:ss.ff t': 10:35:23.00 P

    'd MMM yyyy': 28 Sep 2008

    'HH:mm:ss.f': 22:35:23.0

    'dd MMM HH:mm:ss': 28 Sep 22:35:23

    'Month: M': Month: 9

    'HH:mm:ss.ffffzzz': 22:35:23.0000+03:00

    However, this method has a few variations: ToLongDateString() - converts the object to long date string representation; ToShortDateString() - converts it to short date string; ToLongTimeString() - does the conversion to long time string representation; ToShortTimeString() - does the same, but to short time string. These methods focus on either of the segments (date and time, respectively).

    Check out the example below; and as always make sure to check out the MSDN.

    Long date pattern: "dddd, MMMM dd, yyyy"

    Long date string: "Sunday, September 29, 2008"

    Long time pattern: "h:mm:ss tt"

    Long time string: "1:21:30 AM"

    Short date pattern: "M/d/yyyy"

    Short date string: "9/29/2008"

    Short time pattern: "h:mm tt"

    Short time string: "1:21 AM"

    And finally, you should thoroughly examine the entire list of custom date and time format specifiers from this page at MSDN. Basically, you will gain an enormous amount of flexibility, because you can format your dates and times as far as your imagination stretches.

    More C# Articles
    More By Barzan "Tony" Antal


       · Thank you for reading this article. In this part I've shown you how to work with...
       · The information was useful but when i put your code in my main method, I got errors....
     

    C# ARTICLES

    - Coding a CRC-Generating Algorithm in C
    - Cyclic Redundancy Check
    - Handling Methods and Functions
    - Destroying Objects in C#
    - Creating Objects in C-Sharp
    - Classes and Objects
    - Programming Languages: Managed versus Native
    - LINQ-to-MySQL with DbLinq in C#
    - Working with Dates and Times in C#
    - Generics, Dictionaries, and More
    - More About Generics
    - Working with C# Collections
    - Generics
    - C# and XML
    - Pointers and Arrays in C#





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek