DateTime object facilitates to perform addition, subtraction, equality, greater than using operators like “+”, “-”, “==” etc. Here are couples of examples:
Parse string to DateTime object
Sometimes we do parsing from string to DateTime object to perform operations like date difference, weekday, month name etc. For instance, there is a string value (“12/10/2015”) and our requirement is to find out weekday (Sunday or Monday and so on) of date. In this scenario we need to convert string value to DateTime object and then use WeekDay property(obj.WeekDay) to find out weekday. We can accomplish the same by built-in methods like Convert.ToDateTime(), DateTime.Parse(),DateTime.ParseExact(), DateTime.TryParse(), DateTime.TryParseExact(). Here are a few examples of how to parse a string to DateTime object:
- CultureInfo culture = new CultureInfo("en-US");
-
- DateTime dateTimeObj = Convert.ToDateTime("10/22/2015 12:10:15 PM", culture);
- DateTime dateTimeObj = DateTime.Parse("10/22/2015 12:10:15 PM");
- DateTime dateTimeObj = DateTime.ParseExact("10-22-2015", "MM-dd-yyyy", provider);
-
- DateTime dateTimeObj;
- bool isSuccess = DateTime.TryParse("10-22-2015", out dateTimeObj);
-
- DateTime dateTimeObj;
- CultureInfo provider = CultureInfo.InvariantCulture;
- bool isSuccess = DateTime.TryParseExact("10-22-2015", "MM-dd-yyyy", provider, DateTimeStyles.None, out dateTimeObj);
Now a question arises in your mind, that is, why do we have so many methods for parsing? The reason is every method is for a different purpose. Use TryParse() when you want to be able to attempt a parse and handle invalid data immediately (instead of throwing the exception), and ParseExact() when the format you are expecting is not a standard format, or when you want to limit to one particular standard format for efficiency. If you're sure the string is a valid DateTime, and you know the format, you could also consider the DateTime.ParseExact() or DateTime.TryParseExact() methods.
Working with Calendars
Although DateTime object stores Date and Time information but it also depends on Calendar. Calendar class is an abstract class which is present in System.Globalization namespace. There are different types of Calendar available in .Net framework. These are ChineseLunisolarCalendar, GregorianCalendar, HebrewCalendar, HijriCalendar, JapaneseCalendar, JapaneseLunisolarCalendar, JulianCalendar, KoreanCalendar, KoreanLunisolarCalendar, PersianCalendar, TaiwanCalendar, TaiwanLunisolarCalendar, ThaiBuddhistCalendar, UmAlQuraCalendar.
Calendar can be used in two ways:
- Using CultureInfo object
- Using Calendar object. It is for Calendars that are independent of culture: ChineseLunisolarCalendar, JapaneseLunisolarCalendar, JulianCalendar, KoreanLunisolarCalendar,PersianCalendar and TaiwanLunisolarCalendar.
You can know your current Calendar information using following code:
- CultureInfo currentCulture = Thread.CurrentThread.CurrentCulture;
- Calendar cl = currentCulture.Calendar;
- string temip = cl.ToString().Replace("System.Globalization.", "");
-
-
- Calendar calendar = new HijriCalendar();
- DateTime dt10 = new DateTime(2016, 01, 04, calendar);
- Console.WriteLine("HijriCalendar year: " + dt10.Year);
- Console.WriteLine("HijriCalendar month: " + dt10.Month);
- Console.WriteLine("HijriCalendar total date: " + dt10.ToString("d"));
-
-
- var calendar1 = new HijriCalendar();
- var hijriYear = calendar1.GetYear(DateTime.Now);
- var hijriMonth = calendar1.GetMonth(DateTime.Now);
- var hijriDay = calendar1.GetDayOfMonth(DateTime.Now);
-
-
- DateTime utc = DateTime.Now;
- var ci = CultureInfo.CreateSpecificCulture("ar-SA");
- string s = utc.ToString(ci);
- A calendar divides into multiple eras. In .Net framework it supports only one era except JapaneseCalendar (supports multiple).
- Calendar cal = new JapaneseCalendar();
- foreach (int era in cal.Eras) {
- DateTime date2 = cal.ToDateTime(year, month, day, 0, 0, 0, 0, era);
-
- Console.WriteLine("{0}/{1}/{2} era {3} in Japanese Calendar -> {4:d} in Gregorian",
- cal.GetMonth(date2), cal.GetDayOfMonth(date2),
- cal.GetYear(date2), cal.GetEra(date2), date2);
Working with TimeZone object
TimeZoneInfo class represents world time like Indian Standard Time (IST), US Eastern Standard Time, Tokyo Standard Time etc. It is present in System namespace. It recognizes Local Time Zone and converts times between Coordinated Universal Time (UTC) and local time. It helps to get time in Time Zone (Indis or Japan or USA), converts time between two Time Zone(Australia time zone to India Standard time) and serializes a Date Time.
It is a sealed class and you can’t create an instance of this class. You need to call static members and methods. Static methods like CreateCustomTimeZone(), FindSystemTimeZoneById(), FromSerializedString(), GetSystemTimeZonesand properties like Utc and Local. Here area couple examples:
-
- DateTime now = DateTime.UtcNow;
- DateTime tempD = TimeZone.CurrentTimeZone.ToLocalTime(now);
-
- string current = TimeZone.CurrentTimeZone.StandardName;
-
-
- foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
- {
- Console.WriteLine(z.Id);
- }
-
-
- DateTime tempD1 = TimeZone.CurrentTimeZone.ToUniversalTime(DateTime.Now);
-
-
- TimeZoneInfo tzObject = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
- DateTime tstTime = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, tzObject);
- Console.WriteLine("1. Time in {0} zone: {1}", tzObject.IsDaylightSavingTime(tstTime) ?
- tzObject.DaylightName : tzObject.StandardName, tstTime);
-
-
- TimeZoneInfo tzObject1 = TimeZoneInfo.FindSystemTimeZoneById("AUS Central Standard Time");
- DateTime tstTime2 = TimeZoneInfo.ConvertTime(DateTime.Now, TimeZoneInfo.Local, tzObject1);
- Console.WriteLine("2. Time in {0} zone: {1}", tzObject1.IsDaylightSavingTime(tstTime2) ?
- tzObject1.DaylightName : tzObject1.StandardName, tstTime2);
-
-
- DateTime ut1 = TimeZoneInfo.ConvertTimeToUtc(tstTime2, tzObject1);
-
- TimeZoneInfo tzObject2 = TimeZoneInfo.FindSystemTimeZoneById("India Standard Time");
- DateTime tstTime3 = TimeZoneInfo.ConvertTime(ut1, TimeZoneInfo.Utc, tzObject2);
- Console.WriteLine("3. Time in {0} zone: {1}", tzObject2.IsDaylightSavingTime(tstTime3) ?
- tzObject2.DaylightName : tzObject2.StandardName, tstTime3);
DateTime with Different Culture
.Net uses CultureInfo class for providing information about specific culture. The information is writing system, date, number, string, and calendar. It is present in System.Globalization namespace.
-
- string currentCulture = Thread.CurrentThread.CurrentCulture.DisplayName;
-
- DateTime currentTime = DateTime.Now;
-
- string dateInUSA = currentTime.ToString("D", new CultureInfo("en-US"));
- string dateInHindi = currentTime.ToString("D", new CultureInfo("hi-IN"));
- string dateInJapan = currentTime.ToString("D", new CultureInfo("ja-JP"));
- string dateInFrench = currentTime.ToString("D", new CultureInfo("fr-FR"));
-
- string dateInOriya = currentTime.ToString("D", new CultureInfo("or"));
-
- DateTime originalResult = new DateTime(2016, 01, 09);
-
- bool success = DateTime.TryParse(dateInHindi, new System.Globalization.CultureInfo("hi-IN"),
- System.Globalization.DateTimeStyles.None, out originalResult);
-
-
- string frenchTDate = originalResult.ToString("D", new CultureInfo("fr-FR"));
-
-
- CultureInfo fr = new CultureInfo("fr-FR");
- string shortUsDateFormatString = fr.DateTimeFormat.LongDatePattern;
- string shortUsTimeFormatString = fr.DateTimeFormat.ShortTimePattern;
-
-
- foreach (CultureInfo ci in CultureInfo.GetCultures(CultureTypes. AllCultures))
- {
- Console.WriteLine(ci.Name + ", " + ci.EnglishName);
- }
-
What is DateTimeOffset?
It is a structure type like DateTime. It is introduced in .Net framework 3.5 and present in System namespace. It is mostly relative to Universal Coordinated Time (UTC).
DateTimeOffset is Date + Time + Offset. It provides precise information because it contains offset from Date and Time is taken. DateTimeOffset provides same properties as DateTime structure like Day, Month, Year, Hour, Minute, Second etc. However DateTimeOffset has some new properties:
- DateTime
Gets the DateTime portion of the value without regard to the offset.
- LocalDateTime
Returns a DateTime representing the value in respect to the local time zone.
- Offset
Returns the time offset from UTC.
- UtcDateTime
Returns a DateTime representing the value in respect to UTC time.
Follow example, we declare date variable of DateTimeOffset type and assign current DateTime to it. You will get a result like: 1/9/2016 2:27:00 PM +05:30. Here “1/9/2016 2:27:00 PM” is datetime and “+05:30” (5 hours 30 minutes) is your Offset value. Means if you add offset value to date time (1/9/2016 2:27:00 PM) you will get UTC time. It provides a better way to work with different times from different time zones.
-
- DateTimeOffset date = DateTimeOffset.Now;
-
-
- DateTimeOffset dateTimeObj = DateTime.Now;
- dateTimeObj.Offset.Hours
- dateTimeObj.Offset.Minutes
- dateTimeObj.Offset.Seconds
-
-
- dateTimeObj.DateTime
-
-
- dateTimeObj.UtcDateTime.ToString()
-
-
- DateTime utcTimeObj = DateTimeOffset.Parse(DateTime.Now.ToString()).UtcDateTime;
-
-
- DateTime utcTimeObj = DateTime.Now.ToUniversalTime();
-
-
- DateTime localVersion = DateTime.UtcNow.ToLocalTime();
-
-
- localVersion = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("India Standard Time"));
DateTime is a more powerful structure for manipulating datetime but it is less portable when working with times from different time zones. The DateTimeOffset is much more portable in that it preserves the offset from UTC. So choose as per your requirement.
Working with TimeSpan
It is a structure type which is present in System namespace. It represents time interval and can be expressed as days, hours, minutes, and seconds. It helps to fetch days, hour, minutes and seconds between two dates.
You can create instance of TimeSpan object. It contains 4 parameterized constructors which take days, hours, minutes, seconds, and milliseconds as parameter. Here is the example:
- TimeSpan ts = new TimeSpan(10, 40, 20);
- TimeSpan ts1 = new TimeSpan(1, 2, 5, 10);
-
-
- TimeSpan ts = new TimeSpan(10, 40, 20);
- TimeSpan ts1 = new TimeSpan(1, 2, 5, 10);
-
- DateTime tt = DateTime.Now + ts;
- ts.Add(ts1);
A single tick represents one hundred nanoseconds or one ten-millionth of a second. There are 10,000 ticks in a millisecond, or 10 million ticks in a second.
- TimeSpan ts3 = new TimeSpan(10000000);
- double secondFromTs = ts3.TotalSeconds;
- Console.WriteLine(secondFromTs);
Below is the example of how to get the exact date difference between them using TimeSpan:
-
- DateTime date1 = new DateTime(2016, 1, 10, 11, 20, 30);
- DateTime date2 = new DateTime(2016, 2, 20, 12, 25, 35);
-
-
- TimeSpan interval = date2 - date1;
-
-
- Console.WriteLine("No of Days:", interval.Days);
- Console.WriteLine("Total No of Days:", interval.TotalDays);
- Console.WriteLine("No of Hours:", interval.Hours);
- Console.WriteLine("Total No of Hours:", interval.TotalHours);
- Console.WriteLine("No of Minutes:", interval.Minutes);
- Console.WriteLine("Total No of Minutes:", interval.TotalMinutes);
- Console.WriteLine("No of Seconds:", interval.Seconds);
- Console.WriteLine("Total No of Seconds:", interval.TotalSeconds);
- Console.WriteLine("No of Milliseconds:", interval.Milliseconds);
- Console.WriteLine("Total No of Milliseconds:", interval.TotalMilliseconds);
- Console.WriteLine("Ticks:", interval.Ticks);
Here you will get one doubt as to the difference between Hours and TotalHours. Hours property represents difference between two dates hours value (12-11). However TotalHours represents total number of hours difference between two dates. First it calculates days between two and then multiplies 24 hours into it.