0% found this document useful (0 votes)
158 views5 pages

Date Time in C#

The document provides examples and explanations of various DateTime methods in C#, including: 1. AddMilliseconds() which adds milliseconds to a DateTime and outputs the original and new dates. 2. Compare() which compares two DateTime objects and outputs the relationship between them. 3. DaysInMonth() which outputs the number of days in a given month and year, accounting for leap years. 4. AddYears() which adds years to a DateTime and outputs dates from previous and future years. 5. Warnings about pure functions when working with DateTime, as methods like AddDays() do not modify the original object.

Uploaded by

mihaelahristea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
158 views5 pages

Date Time in C#

The document provides examples and explanations of various DateTime methods in C#, including: 1. AddMilliseconds() which adds milliseconds to a DateTime and outputs the original and new dates. 2. Compare() which compares two DateTime objects and outputs the relationship between them. 3. DaysInMonth() which outputs the number of days in a given month and year, accounting for leap years. 4. AddYears() which adds years to a DateTime and outputs dates from previous and future years. 5. Warnings about pure functions when working with DateTime, as methods like AddDays() do not modify the original object.

Uploaded by

mihaelahristea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Section 19.6: DateTime.

AddMilliseconds(Double)
string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff";
DateTime date1 = new DateTime(2010, 9, 8, 16, 0, 0);
Console.WriteLine("Original date: {0} ({1:N0} ticks)\n",
date1.ToString(dateFormat), date1.Ticks);
DateTime date2 = date1.AddMilliseconds(1);
Console.WriteLine("Second date: {0} ({1:N0} ticks)",
date2.ToString(dateFormat), date2.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)\n",
date2 - date1, date2.Ticks - date1.Ticks);
DateTime date3 = date1.AddMilliseconds(1.5);
Console.WriteLine("Third date: {0} ({1:N0} ticks)",
date3.ToString(dateFormat), date3.Ticks);
Console.WriteLine("Difference between dates: {0} ({1:N0} ticks)",
date3 - date1, date3.Ticks - date1.Ticks);

Section 19.7: DateTime.Compare(DateTime t1,


DateTime t2 )
DateTime date1 = new DateTime(2009, 8, 1, 0, 0, 0);
DateTime date2 = new DateTime(2009, 8, 1, 12, 0, 0);
int result = DateTime.Compare(date1, date2);
string relationship;
if (result < 0)
relationship = "is earlier than";
else if (result == 0)
relationship = "is the same time as";
else relationship = "is later than";
Console.WriteLine("{0} {1} {2}", date1, relationship, date2);

Section 19.8: DateTime.DaysInMonth(Int32, Int32)


const int July = 7;
const int Feb = 2;
int daysInJuly = System.DateTime.DaysInMonth(2001, July);
Console.WriteLine(daysInJuly);
// daysInFeb gets 28 because the year 1998 was not a leap year.
int daysInFeb = System.DateTime.DaysInMonth(1998, Feb);
Console.WriteLine(daysInFeb);
// daysInFebLeap gets 29 because the year 1996 was a leap year.
int daysInFebLeap = System.DateTime.DaysInMonth(1996, Feb);
Console.WriteLine(daysInFebLeap);
GoalKicker.com – C# Notes for Professionals 84
Section 19.9: DateTime.AddYears(Int32)
Add years on the dateTime object:
DateTime baseDate = new DateTime(2000, 2, 29);
Console.WriteLine("Base Date: {0:d}\n", baseDate);
// Show dates of previous fifteen years.
for (int ctr = -1; ctr >= -15; ctr--)
Console.WriteLine("{0,2} year(s) ago:{1:d}",
Math.Abs(ctr), baseDate.AddYears(ctr));
Console.WriteLine();
// Show dates of next fifteen years.
for (int ctr = 1; ctr <= 15; ctr++)
Console.WriteLine("{0,2} year(s) from now: {1:d}",
ctr, baseDate.AddYears(ctr));

Section 19.10: Pure functions warning when dealing


with
DateTime
Wikipedia currently defines a pure function as follows:
1. The function always evaluates the same result value given the same argument value(s). The
function result
value cannot depend on any hidden information or state that may change while program execution
proceeds
or between different executions of the program, nor can it depend on any external input from I/O
devices .
2. Evaluation of the result does not cause any semantically observable side effect or output, such as
mutation
of mutable objects or output to I/O devices
As a developer you need to be aware of pure methods and you will stumble upon these a lot in many
areas. One I
have seen that bites many junior developers is working with DateTime class methods. A lot of these
are pure and if
you are unaware of these you can be in for a suprise. An example:
DateTime sample = new DateTime(2016, 12, 25);
sample.AddDays(1);
Console.WriteLine(sample.ToShortDateString());
Given the example above one may expect the result printed to console to be '26/12/2016' but in reality
you end up
with the same date. This is because AddDays is a pure method and does not affect the original date.
To get the
expected output you would have to modify the AddDays call to the following:
sample = sample.AddDays(1);

Section 19.11:
DateTime.TryParseExact(String, String,
IFormatProvider, D
ateTimeStyles, DateTime)
Converts the specified string representation of a date and time to its DateTime equivalent using the
specified
format, culture-specific format information, and style. The format of the string representation must
match the
specified format exactly. The method returns a value that indicates whether the conversion
succeeded.
For Example
CultureInfo enUS = new CultureInfo("en-US");
GoalKicker.com – C# Notes for Professionals 85
string dateString;
System.DateTime dateValue;
Parse date with no style flags.
dateString = " 5/01/2009 8:30 AM";
if (DateTime.TryParseExact(dateString, "g", enUS, DateTimeStyles.None, out dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
// Allow a leading space in the date string.
if(DateTime.TryParseExact(dateString, "g", enUS, DateTimeStyles.AllowLeadingWhite, out dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
Use custom formats with M and MM.
dateString = "5/01/2009 09:00";
if(DateTime.TryParseExact(dateString, "M/dd/yyyy hh:mm", enUS, DateTimeStyles.None, out dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
// Allow a leading space in the date string.
if(DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm", enUS, DateTimeStyles.None, out
dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
Parse a string with time zone information.
dateString = "05/01/2009 01:30:42 PM -05:00";
if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS, DateTimeStyles.None, out
dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
GoalKicker.com – C# Notes for Professionals 86
// Allow a leading space in the date string.
if (DateTime.TryParseExact(dateString, "MM/dd/yyyy hh:mm:ss tt zzz", enUS,
DateTimeStyles.AdjustToUniversal, out dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
Parse a string represengting UTC.
dateString = "2008-06-11T16:11:20.0904778Z";
if(DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture, DateTimeStyles.None, out
dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
if (DateTime.TryParseExact(dateString, "o", CultureInfo.InvariantCulture,
DateTimeStyles.RoundtripKind, out dateValue))
{
Console.WriteLine("Converted '{0}' to {1} ({2}).", dateString, dateValue, dateValue.Kind);
}
else
{
Console.WriteLine("'{0}' is not in an acceptable format.", dateString);
}
Outputs
' 5/01/2009 8:30 AM' is not in an acceptable format.
Converted ' 5/01/2009 8:30 AM' to 5/1/2009 8:30:00 AM (Unspecified).
Converted '5/01/2009 09:00' to 5/1/2009 9:00:00 AM (Unspecified).
'5/01/2009 09:00' is not in an acceptable format.
Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 11:30:42 AM (Local).
Converted '05/01/2009 01:30:42 PM -05:00' to 5/1/2009 6:30:42 PM (Utc).
Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 9:11:20 AM (Local).
Converted '2008-06-11T16:11:20.0904778Z' to 6/11/2008 4:11:20 PM (Utc).

Section 19.12: DateTime.Add(TimeSpan)


// Calculate what day of the week is 36 days from this instant.
System.DateTime today = System.DateTime.Now;
System.TimeSpan duration = new System.TimeSpan(36, 0, 0, 0);
System.DateTime answer = today.Add(duration);
System.Console.WriteLine("{0:dddd}", answer);

Section 19.13: Parse and TryParse with culture info


You might want to use it when parsing DateTimes from different cultures (languages), following
example parses
Dutch date.
GoalKicker.com – C# Notes for Professionals 87
DateTime dateResult;
var dutchDateString = "31 oktober 1999 04:20";
var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
DateTime.TryParse(dutchDateString, dutchCulture, styles, out dateResult);
// output {31/10/1999 04:20:00}
Example of Parse:
DateTime.Parse(dutchDateString, dutchCulture)
// output {31/10/1999 04:20:00}

Section 19.14: DateTime as initializer in for-loop


// This iterates through a range between two DateTimes
// with the given iterator (any of the Add methods)
DateTime start = new DateTime(2016, 01, 01);
DateTime until = new DateTime(2016, 02, 01);
// NOTICE: As the add methods return a new DateTime you have
// to overwrite dt in the iterator like dt = dt.Add()
for (DateTime dt = start; dt < until; dt = dt.AddDays(1))
{
Console.WriteLine("Added {0} days. Resulting DateTime: {1}",
(dt - start).Days, dt.ToString());
}
Iterating on a TimeSpan works the same way.
Section 19.15:
DateTime.ParseExact(String, String,
IFormatProvider)
Converts the specified string representation of a date and time to its DateTime equivalent using the
specified
format and culture-specific format information. The format of the string representation must match the
specified
format exactly.
Convert a specific format string to equivalent DateTime
Let's say we have a culture-specific DateTime string 08-07-2016 11:30:12 PM as MM-dd-yyyy hh:mm:ss tt
format
and we want it to convert to equivalent DateTime object
string str = "08-07-2016 11:30:12 PM";
DateTime date = DateTime.ParseExact(str, "MM-dd-yyyy hh:mm:ss tt", CultureInfo.CurrentCulture);
Convert a date time string to equivalent DateTime object without any specific culture format
Let's say we have a DateTime string in dd-MM-yy hh:mm:ss tt format and we want it to convert to
equivalent
DateTime object, without any specific culture information
string str = "17-06-16 11:30:12 PM";
DateTime date = DateTime.ParseExact(str, "dd-MM-yy hh:mm:ss tt", CultureInfo.InvariantCulture);
Convert a date time string to equivalent DateTime object without any specific culture format
with different
format
GoalKicker.com – C# Notes for Professionals 88
Let's say we have a Date string , example like '23-12-2016' or '12/23/2016' and we want it to convert
to equivalent
DateTime object, without any specific culture information
string date = '23-12-2016' or date = 12/23/2016';
string[] formats = new string[] {"dd-MM-yyyy","MM/dd/yyyy"}; // even can add more possible
formats.
DateTime date = DateTime.ParseExact(date,formats,
CultureInfo.InvariantCulture,DateTimeStyles.None);
NOTE : System.Globalization needs to be added for CultureInfo Class
Section 19.16: DateTime ToString,
ToShortDateString,
ToLongDateString and ToString formatted
using System;
public class Program
{
public static void Main()
{
var date = new DateTime(2016,12,31);
Console.WriteLine(date.ToString()); //Outputs: 12/31/2016 12:00:00 AM
Console.WriteLine(date.ToShortDateString()); //Outputs: 12/31/2016
Console.WriteLine(date.ToLongDateString()); //Outputs: Saturday, December 31, 2016
Console.WriteLine(date.ToString("dd/MM/yyyy")); //Outputs: 31/12/2016
}
}

Section 19.17: Current Date


To get the current date you use the DateTime.Today property. This returns a DateTime object with
today's date.
When this is then converted .ToString() it is done so in your system's locality by default.
For example:
Console.WriteLine(DateTime.Today);
Writes today's date, in your local format to the console.

You might also like