Arrao4u

…a blog by Rama Rao

Archive for the ‘Date time conversion in .net’ Category

Date time Conversion in .net

Posted by arrao4u on January 5, 2010

DateTime Value Manipulation

The previous articles in the C# Fundamentals tutorial have examined the creation and reading of DateTime data and the structure’s constituent parts. In this article, the manipulation of DateTime information is described, starting with the methods by which DateTime values can be adjusted. This can be achieved using simple operators or, for more detailed control, using the provided DateTime methods.

Addition and Subtraction Operators

Two arithmetic operators are provided for use with the DateTime structure. These are the addition (+) and subtraction (-) operators. Each operator requires two operands. The first operand is the DateTime value to be modified and the second is a TimeSpan value containing the duration of time to add or remove from the value. In the following examples, a TimeSpan value is created as required using the new keyword and a TimeSpan constructor.

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate = theDate + new TimeSpan(1, 1, 1);    // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate = theDate - new TimeSpan(25, 0, 0, 0);  // theDate = 8 Dec 2006 21:16:01

The two arithmetic operators may also be used as compound assignment operators. This is achieved by appending an equals sign (=) to the operator. The following examples demonstrate this after using the Parse method to create a TimeSpan value. This method operates in a similar manner to the DateTime’s Parse method.

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");

// Add one hour, one minute and one second
theDate += TimeSpan.Parse("01:01:01");        // theDate = 2 Jan 2007 21:16:01

// Subtract twenty-five days
theDate -= TimeSpan.Parse("25.00:00:00");     // theDate = 8 Dec 2006 21:16:01

Add Methods

The Add methods allow more control over the processing of DateTime values. They do not require the use of a TimeSpan value, which means that adjustment of greater values for individual elements of a date or time value are possible. For example, it is simple to add more than sixty minutes to a DateTime value without calculating how many hours or days are involved in the calculation.

The first Add method to look at is the Add method itself. This provides the same functionality as the addition operator, simply increasing a DateTime value using a duration held as a TimeSpan.

DateTime theDate = DateTime.Parse("2 Jan 2007 20:15:00");
TimeSpan duration = TimeSpan.Parse("1.01:01:01");

theDate = theDate.Add(duration);              // theDate = 3 Jan 2007 21:16:01

The Add method provides no greater control over the calculation than the simple arithmetic operators. To gain flexibility, we can use methods for adding a number of years, months, etc. There is even an Add method to allow us to add ticks; a single tick being one ten-millionth of a second. These methods are all named Add followed by the type of DateTime element to be added. Values may also be subtracted by passing a negative parameter to the appropriate Add method. Each of the methods accepts a single double-precision number as a parameter except for AddTicks, which requires a long integer parameter.

DateTime theDate = DateTime.Parse("2 Jan 2007");

theDate = theDate.AddYears(1);                // theDate = 2 Jan 2008
theDate = theDate.AddMonths(2);               // theDate = 2 Mar 2008
theDate = theDate.AddDays(1.5);               // theDate = 3 Mar 2008 12:00:00
theDate = theDate.AddHours(-6);               // theDate = 2 Mar 2008 06:00:00
theDate = theDate.AddMinutes(150);            // theDate = 2 Mar 2008 08:30:00
theDate = theDate.AddSeconds(10.5);           // theDate = 2 Mar 2008 08:30:10.5
theDate = theDate.AddMilliseconds(499);       // theDate = 2 Mar 2008 08:30:10.999
theDate = theDate.AddTicks(10000);            // theDate = 2 Mar 2008 08:30:11

Subtract Method

The Subtract method provides similar function to the basic Add method. However, it can be used in two ways. Firstly, a TimeSpan may be subtracted from a DateTime to return a new DateTime. Secondly, one DateTime value may be subtracted from another resulting in a TimeSpan value that describes the difference between the two original values.

DateTime theDate = DateTime.Parse("2 Jan 2007");
TimeSpan subtract = TimeSpan.Parse("1.01:00:00");
DateTime startDate = DateTime.Parse("1 Jan 2007");
DateTime endDate = DateTime.Parse("2 Jan 2007 12:00:00");
TimeSpan diff;

// Subtract a TimeSpan from a DateTime
theDate = theDate.Subtract(subtract);         // theDate = 31 Dec 2006 23:00:00

// Find the difference between two dates
diff = endDate.Subtract(startDate);           // diff = 1.12:00:00

NB: In the above example the difference between the dates is positive because the DateTime being subtracted is earlier than that being subtracted from. If the reverse was true then the result would be negative.

UTC and Local DateTime Conversion

The DateTime structure allows the storage of both Co-ordinated Universal Time (UTC) and local values for times. The UTC value is ideal when it is necessary to track the exact time and ordering of events that may span time zones or daylight savings time changes. However, the local time value is preferred when displaying a time to a user. Luckily, the DateTime structure provides two methods that allow conversion between the two standards to be performed using the user’s local system settings to achieve the correct results. These methods are ToUniversalTime and ToLocalTime. For the following example, Rangoon has been selected in the Window’s time zone settings for its interesting six and a half hour offset from UTC.

DateTime localDate = DateTime.Parse("1 Jul 2007 12:00");

DateTime utcDate = localDate.ToUniversalTime();     // 1 Jul 2007 05:30
DateTime rangoon = utcDate.ToLocalTime();           // 1 Jul 2007 12:00

It is important to note that the DateTime structure itself does not have any knowledge of which type of date (UTC or local) is held. The two methods simply add or subtract the time zone offset as instructed. If used incorrectly, the methods return invalid results.

Conversion from DateTime to String

Once a DateTime value has been calculated it is usually necessary to display it to the user. Ideally, the date and time will be displayed in a format recognisable by the user and dependant upon the preferences that they have expressed, either in the software’s configuration or, more usually, in their system configuration. The DateTime structure provides several methods to achieve a conversion of date and time information to strings, which may then be used for display purposes.

Basic Conversions

When a Microsoft Windows operating system is installed on a personal computer, the user selects the region of the world where they live and this information is used to determine how dates and times are formatted. Some users may further customise their settings to achieve their preferences for long and short dates and times. As developers, we should honour their selections by ensuring that output from our programs uses these settings.

The DateTime structure provides four standard methods for converting DateTime values to strings. These allow the automatic generation of a string containing a long or short date or time. The names of the methods are ToLongDateString, ToShortDateString, ToLongTimeString and ToShortTimeString. None of the four functions requires the use of parameters.

NB: The following example assumes that the code is executing on a UK machine. The results in other countries or on customised systems may differ.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToLongDateString();          // result = "03 January 2007"
result = theDate.ToShortDateString();         // result = "03/01/2007"
result = theDate.ToLongTimeString();          // result = "21:25:30"
result = theDate.ToShortTimeString();         // result = "21:25"

Using ToString with Format Specifiers

The basic formatting provided by the four conversion methods described above is useful in many cases. For greater control, using the ToString method allows the programmer to specify a format specifier as a parameter. This format specifier permits the use of a wider range of date and time styles. It does, however, limit the user’s control over how they view an application’s output.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d");       // result = "03/01/2007"
result = theDate.ToString("f");       // result = "03 January 2007 21:25"
result = theDate.ToString("y");       // result = "January 2007"

Available Format Specifiers

The full list of format specifiers for DateTime conversion is as follows:

Specifier Description Example
d Short date format. This is equivalent to using ToShortDateString. “03/01/2007”
D Long date format. This is equivalent to using ToLongDateString. “03 January 2007”
f Date and time using long date and short time format. “03 January 2007 21:25”
F Date and time using long date and time format. “03 January 2007 21:25:30”
g Date and time using short date and time format. “03/01/2007 21:25”
G Date and time using short date and long time format. “03/01/2007 21:25:30”
m Day and month only. “03 January”
r Date and time in standard Greenwich Mean Time (GMT) format. “Wed, 03 Jan 2007 21:25:30 GMT”
s Sortable date and time format. The date elements start at the highest magnitude (year) and reduce along the string to the smallest magnitude (seconds). “2007-01-03T21:25:30”
t Short time format. This is equivalent to using ToShortTimeString. “21:25”
T Long time format. This is equivalent to using ToLongTimeString. “21:25:30”
u Short format, sortable co-ordinated universal time. “2007-01-03 21:25:30Z”
U Long format date and time. “03 January 2007 17:25:30”
y Month and year only. “January 2007”

Using Picture Formats for Custom Formatting

The standard format specifiers are useful in most cases whilst still maintaining the correct style of date and time for the user’s location. On some occasions however, it is necessary to have complete control over the positioning and styling of each element of date and time information. For this, picture formats must be used. These allow an exact format to be created using any combination of elements from a DateTime.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d-MM-yy");       // result = "3-01-07"
result = theDate.ToString("HH:mm");         // result = "21:25"
result = theDate.ToString("h:mm tt");       // result = "9:25 PM"

Available Picture Formatting Codes

The above example shows several formats and the results. The full list of available formatting codes is as follows:

Specifier Description Examples
y One-digit year. If the year cannot be specified in one digit then two digits are used automatically. “7”
“95”
yy Two-digit year with leading zeroes if required. “07”
yyyy Full four-digit year. “2007”
g or gg Indicator of Anno Domini (AD). “A.D.”
M One-digit month number. If the month cannot be specified in one digit then two digits are used automatically. “1”
“12”
MM Two-digit month number with leading zeroes if required. “01”
MMM Three letter month abbreviation. “Jan”
MMMM Month name. “January”
d One-digit day number. If the day cannot be specified in one digit then two digits are used automatically. “3”
“31”
dd Two-digit day number with leading zeroes if required. “03”
ddd Three letter day name abbreviation. “Wed”
dddd Day name. “Wednesday”
h One-digit hour using the twelve hour clock. If the hour cannot be specified in one digit then two digits are used automatically. “9”
“12”
hh Two-digit hour using the twelve hour clock with leading zeroes if required. “09”
H One-digit hour using the twenty four hour clock. If the hour cannot be specified in one digit then two digits are used automatically. “1”
“21”
HH Two-digit hour using the twenty four hour clock with leading zeroes if required. “09”
t Single letter indicator of AM or PM, generally for use with twelve hour clock values. “A”
“P”
tt Two letter indicator of AM or PM, generally for use with twelve hour clock values. “AM”
“PM”
m One-digit minute. If the minute cannot be specified in one digit then two digits are used automatically. “1”
“15”
mm Two-digit minute with leading zeroes if required. “01”
s One-digit second. If the second cannot be specified in one digit then two digits are used automatically. “1”
“59”
ss Two-digit second with leading zeroes if required. “01”
f Fraction of a second. Up to seven f’s can be included to determine the number of decimal places to display. “0”
“0000000”
z One-digit time zone offset indicating the difference in hours between local time and UTC time. If the offset cannot be specified in one digit then two digits are used automatically. “+6”
“-1”
zz Two-digit time zone offset indicating the difference in hours between local time and UTC time with leading zeroes if required. “+06”

Some of the formatting codes use the same letter as a format specifier. When used within a format string that is greater than one character in length this does not present a problem. If you need to use a single character picture format string, the letter must be preceded by a percentage sign (%) to indicate that the standard format specifier is not to be used.

DateTime theDate = DateTime.Parse("3 Jan 2007 21:25:30");
string result;

result = theDate.ToString("d");       // result = "03/01/2007"
result = theDate.ToString("%d");      // result = "3"

ref:http://www.blackwasp.co.uk/CSharpDateManipulation.aspx

http://www.codeproject.com/KB/dotnet/datetimeformat.aspx

Response.Write(DateTime.Now.ToShortDateString());–>1/5/2010
Response.Write(DateTime.Now.ToShortTimeString());

1/5/201011:20 PM(mon/date/year time)

Question: how to get 11:23  from  1/5/201011:23 PM

Ans: string[] strTemp = DateTime.Now.ToShortTimeString().Split(‘ ‘);
txtOutput6.Text = strTemp[0].ToString();

Question: Convert 01/30/2008(mm/dd/yyyy) to dd/mm/yyyy format

txtInput1.Text = “01/30/2008”;
DateTime tempDate;
tempDate = Convert.ToDateTime(txtInput1.Text);
txtOutput1.Text = tempDate.ToString(“dd/MM/yyyy”);

Question: Convert dd/mm/yyyy to mm/dd/yyyy

CultureInfo Ggformat = new CultureInfo(“en-GB”, true);
txtInput2.Text = “21/02/2008”;
DateTime tempDate1;
tempDate1 = DateTime.Parse(txtInput2.Text,Ggformat);
txtOutput2.Text = tempDate1.ToShortDateString();

or

txtInput3.Text = “21/02/2008”;
string strtemp = DateTime.ParseExact(txtInput3.Text, “dd/MM/yyyy”, null).ToString(“d”);
txtOutput3.Text = strtemp;

Question : mm/dd/yyyy to Thursday, February 21, 2008

TextBox3.Text = “21/02/2008″;
DateTime dt = DateTime.ParseExact(TextBox3.Text,”dd/MM/yyyy”,null);
Response.Write(dt.ToLongDateString());

Question: 26-mar-2008 to mm/dd/yyyy

TextBox4.Text = “26-mar-2008″;
DateTime ds= DateTime.ParseExact(TextBox4.Text,”dd-MMM-yyyy”,null);// mm/dd/yyyy time
TextBox5.Text = ds.ToString();

Posted in Date time conversion in .net | Leave a Comment »