Section19.1:DateTimeFormatting
StandardDateTimeFormatting
DateTimeFormatInfo specifies a set of specifiers for simple date and time formatting. Every specifier correspond to a particular DateTimeFormatInfo format pattern.
//Createdatetime
DateTimedt=newDateTime(2016,08,01,18,50,23,230);
var t = String.Format(“{0:t}”, dt); // “6:50PM” ShortTime
var d = String.Format(“{0:d}”, dt); // “8/1/2016” ShortDate
var T = String.Format(“{0:T}”, dt); // “6:50:23PM” LongTime
var D = String.Format(“{0:D}”, dt); // “Monday,August1,2016” LongDate
var f = String.Format(“{0:f}”, dt); // “Monday,August1,20166:50PM” LongDate+ShortTime
var F = String.Format(“{0:F}”, dt); // “Monday,August1,20166:50:23PM” FullDateTime
var g = String.Format(“{0:g}”, dt); // “8/1/20166:50PM” ShortDate+ShortTime
var G = String.Format(“{0:G}”, dt); // “8/1/20166:50:23PM” ShortDate+LongTime
var m = String.Format(“{0:m}”, dt); // “August1” MonthDay
var y = String.Format(“{0:y}”, dt); // “August2016” YearMonth
var r = String.Format(“{0:r}”, dt); // “SMon,01Aug201618:50:23GMT” RFC1123
var s = String.Format(“{0:s}”, dt); // “2016-08-01T18:50:23” SortableDateTime
var u = String.Format(“{0:u}”, dt); // “2016-08-0118:50:23Z”
CustomDateTimeFormatting
Therearefollowingcustomformatspecifiers:
var year= String.Format(“{0:y yyyyyyyyy}”, dt); // “161620162016” year
var month= String.Format(“{0:M MMMMMMMMM}”, dt); // “808AugAugust” month
var day= String.Format(“{0:d ddddddddd}”, dt); // “101MonMonday” day
var hour= String.Format(“{0:h hhHHH}”, dt); // “6061818” hour12/24
var minute= String.Format(“{0:m mm}”, dt); // “5050” minute
var secound= String.Format(“{0:s ss}”, dt); // “2323” second
var fraction= String.Format(“{0:f fffffffff}”, dt); // “2232302300” sec.fraction
var fraction2= String.Format(“{0:F FFFFFFFFF}”, dt); // “2232323” withoutzeroes
var period= String.Format(“{0:t tt}”, dt); // “PPM” A.M.orP.M.
var zone= String.Format(“{0:z zzzzz}”, dt); // “+0+00+00:00” timezone
Youcanusealsodateseparator/(slash)andtimesepatator:(colon).
Forcodeexample
FormoreinformationMSDN.
Section19.2:DateTime.AddDays(Double)
AdddaysintoadateTimeobject.
DateTimetoday=DateTime.Now;
DateTimeanswer=today.AddDays(36);
Console.WriteLine(“Today:{0:dddd}”,today);
Console.WriteLine(“36daysfromtoday:{0:dddd}”,answer);
Youalsocansubtractdayspassinganegativevalue:
DateTimetoday=DateTime.Now;
DateTimeanswer=today.AddDays(-3);
Console.WriteLine(“Today:{0:dddd}”,today);
0Console.WriteLine(“-3daysfromtoday:{0:dddd}”,answer);
Section19.3:DateTime.AddHours(Double)
double[]hours={.08333,.16667,.25,.33333,.5,.66667,1,2,
29,30,31,90,365};
DateTimedateValue=newDateTime(2009,3,1,12,0,0);
foreach(doublehourinhours)
Console.WriteLine(“{0}+{1}hour(s)={2}”,dateValue,hour,
dateValue.AddHours(hour));
Section19.4:DateTime.Parse(String)
//ConvertsthestringrepresentationofadateandtimetoitsDateTimeequivalent
vardateTime=DateTime.Parse(“14:2322Jul2016”);
Console.WriteLine(dateTime.ToString());
Section19.5:DateTime.TryParse(String,DateTime)
//ConvertsthespecifiedstringrepresentationofadateandtimetoitsDateTimeequivalentand returnsavaluethatindicateswhethertheconversionsucceeded
string[]dateTimeStrings=new[]{
“14:2322Jul2016”,
“99:232xJul2016”,
“22/7/201614:23:00”
};
foreach(vardateTimeStringindateTimeStrings){
DateTimedateTime;
boolwasParsed=DateTime.TryParse(dateTimeString,outdateTime);
stringresult=dateTimeString+ (wasParsed
?$”wasparsedto{dateTime}”
:”can’tbeparsedtoDateTime”);
Console.WriteLine(result);
}
Section19.6:DateTime.AddMilliseconds(Double)
stringdateFormat=”MM/dd/yyyyhh:mm:ss.fffffff”;
DateTimedate1=newDateTime(2010,9,8,16,0,0);
Console.WriteLine(“Originaldate:{0}({1:N0}ticks)\n“,
date1.ToString(dateFormat),date1.Ticks);
DateTimedate2=date1.AddMilliseconds(1);
Console.WriteLine(“Seconddate:Â Â Â Â Â Â Â Â Â Â Â Â Â {0}({1:N0}ticks)”,
date2.ToString(dateFormat),date2.Ticks);
Console.WriteLine(“Differencebetweendates:{0}({1:N0}ticks)\n“,
date2-date1,date2.Ticks-date1.Ticks);
DateTimedate3=date1.AddMilliseconds(1.5);
Console.WriteLine(“Thirddate:Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â {0}({1:N0}ticks)”,
date3.ToString(dateFormat),date3.Ticks);
Console.WriteLine(“Differencebetweendates:{0}({1:N0}ticks)”,
date3-date1,date3.Ticks-date1.Ticks);
Section19.7:DateTime.Compare(DateTimet1,DateTimet2)
DateTimedate1=newDateTime(2009,8,1,0,0,0);
DateTimedate2=newDateTime(2009,8,1,12,0,0);
intresult=DateTime.Compare(date1,date2);
stringrelationship;
if(result<0)
relationship=”isearlierthan”; else
if(result==0)
relationship=”isthesametimeas”;
elserelationship=”islaterthan”;
Console.WriteLine(“{0}{1}{2}”,date1,relationship,date2);
Section19.8:DateTime.DaysInMonth(Int32, Int32)
constintJuly=7; constintFeb=2;
intdaysInJuly=System.DateTime.DaysInMonth(2001,July);
Console.WriteLine(daysInJuly);
//daysInFebgets28becausetheyear1998wasnotaleapyear. intdaysInFeb=System.DateTime.DaysInMonth(1998,Feb);
Console.WriteLine(daysInFeb);
//daysInFebLeapgets29becausetheyear1996wasaleapyear. intdaysInFebLeap=System.DateTime.DaysInMonth(1996,Feb);
Console.WriteLine(daysInFebLeap);
Section19.9:DateTime.AddYears(Int32)
AddyearsonthedateTimeobject:
DateTimebaseDate=newDateTime(2000,2,29);
Console.WriteLine(“BaseDate: {0:d}\n“,baseDate);
//Showdatesofpreviousfifteenyears.
for(intctr=-1;ctr>=-15;ctr–)
Console.WriteLine(“{0,2}year(s)ago:{1:d}”,
Math.Abs(ctr),baseDate.AddYears(ctr));
Console.WriteLine();
//Showdatesofnextfifteenyears.
for(intctr=1;ctr<=15;ctr++)
Console.WriteLine(“{0,2}year(s)fromnow:{1:d}”,
ctr,baseDate.AddYears(ctr));
Section 19.10: Pure functions warning when dealing with DateTime
Wikipedia currently definesa purefunction asfollows:
- 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 .
- 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:
DateTimesample=newDateTime(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.Add Days(1);
Section19.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.
ForExample
CultureInfoenUS=newCultureInfo(“en-US”);
stringdateString;
System.DateTimedateValue;
Parsedatewithnostyleflags.
dateString=”5/01/20098:30AM”;
if(DateTime.TryParseExact(dateString,”g”,enUS,DateTimeStyles.None,outdateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
//Allowaleadingspaceinthedatestring.
if(DateTime.TryParseExact(dateString,”g”,enUS,DateTimeStyles.AllowLeadingWhite,outdateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind); else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
UsecustomformatswithMandMM.
dateString=”5/01/200909:00″;
if(DateTime.TryParseExact(dateString,”M/dd/yyyyhh:mm”,enUS,DateTimeStyles.None,outdateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
//Allowaleadingspaceinthedatestring.
if(DateTime.TryParseExact(dateString,”MM/dd/yyyyhh:mm”,enUS,DateTimeStyles.None,out dateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
Parseastringwithtimezoneinformation.
dateString=”05/01/200901:30:42PM-05:00″;
if(DateTime.TryParseExact(dateString,”MM/dd/yyyyhh:mm:ssttzzz”,enUS,DateTimeStyles.None,out dateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
//Allowaleadingspaceinthedatestring.
if (DateTime.TryParseExact(dateString, “MM/dd/yyyy hh:mm:ss tt zzz”, enUS, DateTimeStyles.AdjustToUniversal,outdateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
ParseastringrepresengtingUTC.
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}’isnotinanacceptableformat.”,dateString);
}
if(DateTime.TryParseExact(dateString,”o”,CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind,outdateValue))
{
Console.WriteLine(“Converted'{0}’to{1}({2}).”,dateString,dateValue,dateValue.Kind);
}
else
{
Console.WriteLine(“‘{0}’isnotinanacceptableformat.”,dateString);
}
Outputs
‘ 5/01/2009 8:30 AM’ is not in an acceptable format.
Converted’5/01/20098:30AM’to5/1/20098:30:00AM(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/200901:30:42PM-05:00’to5/1/200911:30:42AM(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’to6/11/20089:11:20AM(Local). Converted ‘2008-06-11T16:11:20.0904778Z’ to 6/11/2008 4:11:20 PM (Utc).
Section19.12:DateTime.Add(TimeSpan)
//Calculatewhatdayoftheweekis36daysfromthisinstant.
System.DateTimetoday=System.DateTime.Now;
System.TimeSpanduration=newSystem.TimeSpan(36,0,0,0); System.DateTimeanswer=today.Add(duration);
System.Console.WriteLine(“{0:dddd}”,answer);
Section19.13:ParseandTryParsewithcultureinfo
You might want to use it when parsing DateTimes from different cultures (languages), following example parses Dutch date.
DateTimedateResult;
vardutchDateString=”31oktober199904:20″;
vardutchCulture=CultureInfo.CreateSpecificCulture(“nl-NL”); DateTime.TryParse(dutchDateString, dutchCulture, styles, out dateResult);
//output{31/10/199904:20:00}
ExampleofParse:
DateTime.Parse(dutchDateString,dutchCulture)
//output{31/10/199904:20:00}
Section19.14:DateTimeasinitializerinfor-loop
//ThisiteratesthrougharangebetweentwoDateTimes
//withthegiveniterator(anyoftheAddmethods)
DateTimestart=newDateTime(2016,01,01);
DateTimeuntil=newDateTime(2016,02,01);
//NOTICE:AstheaddmethodsreturnanewDateTimeyouhave
//tooverwritedtintheiteratorlikedt=dt.Add()
for(DateTimedt=start;dt<until;dt=dt.AddDays(1))
{
Console.WriteLine(“Added{0}days.ResultingDateTime:{1}”, (dt-
start).Days,dt.ToString());
}
IteratingonaTimeSpanworksthesameway.
Section 19.15: DateTime.ParseExact(String, String, IFormatProvider)
ConvertsthespecifiedstringrepresentationofadateandtimetoitsDateTimeequivalentusingthespecified formatandculture-specificformatinformation.Theformatofthestringrepresentationmustmatchthespecified format exactly.
ConvertaspecificformatstringtoequivalentDateTime
Let’ssaywehaveaculture-specificDateTimestring08-07-201611:30:12PMasMM-dd-yyyyhh:mm:ssttformat and we want it to convert to equivalent DateTimeobject
stringstr=”08-07-201611:30:12PM”;
DateTimedate=DateTime.ParseExact(str,”MM-dd-yyyyhh:mm:sstt”,CultureInfo.CurrentCulture);
ConvertadatetimestringtoequivalentDateTimeobjectwithoutanyspecificcultureformat
Let’ssaywehaveaDateTimestringindd-MM-yyhh:mm:ssttformatandwewantittoconverttoequivalent
DateTimeobject,withoutanyspecificcultureinformation
stringstr=”17-06-1611:30:12PM”;
DateTimedate=DateTime.ParseExact(str,”dd-MM-yyhh:mm:sstt”,CultureInfo.InvariantCulture);
Convert a date time string to equivalent DateTime object without any specific culture format with different format
Let’ssaywehaveaDatestring,examplelike’23-12-2016’or’12/23/2016’andwewantittoconverttoequivalent
DateTimeobject,withoutanyspecificcultureinformation
stringdate= ’23-12-2016’ordate=12/23/2016′;
string[]formats=newstring[]{“dd-MM-yyyy”,”MM/dd/yyyy”};//evencanaddmorepossible formats.
DateTimedate=DateTime.ParseExact(date,formats,
CultureInfo.InvariantCulture,DateTimeStyles.None);
NOTE:System.GlobalizationneedstobeaddedforCultureInfoClass
Section 19.16: DateTime ToString, ToShortDateString,ToLongDateStringandToStringformatted
usingSystem;
publicclassProgram
{
publicstaticvoidMain()
{
vardate=newDateTime(2016,12,31);
Console.WriteLine(date.ToString()); //Outputs:12/31/201612:00:00AM
Console.WriteLine(date.ToShortDateString());//Outputs:12/31/2016Console.WriteLine(date.ToLong
DateString());//Outputs:Saturday,December31,2016 Console.WriteLine(date.ToString(“dd/MM/yyyy”));Â Â Â Â Â Â Â Â Â Â Â Â Â Â Â //Outputs:31/12/2016
}
}
TogetthecurrentdateyouusetheDateTime.Todayproperty.ThisreturnsaDateTimeobjectwithtoday’sdate. Whenthisisthenconverted.ToString()itisdonesoinyoursystem’slocalitybydefault.
Forexample:
Console.WriteLine(DateTime.Today);
Writestoday’sdate,inyourlocalformattotheconsole.
About us and this blog
We are a digital marketing company with a focus on helping our customers achieve great results across several key areas.
Request a free quote
We offer professional SEO services that help websites increase their organic search score drastically in order to compete for the highest rankings even when it comes to highly competitive keywords.
Subscribe to our newsletter!
More from our blog
See all postsRecent Posts
- Chapter120:YieldKeyword 20/05/2024
- Chapter119:LockStatement 19/05/2024
- Chapter118:Makingavariablethreadsafe 18/05/2024