using System; using System.Collections.Generic; using System.Text; public static class TimingUtilities { private static long ticks; public static void startTimer() { ticks = DateTime.Now.Ticks; } public static double GetElapsedTime() { return (DateTime.Now.Ticks - ticks) / Math.Pow(10, 4); } }
Author: coder
Convert Unix Seconds
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections.Generic; using System.Globalization; using System.Text; using System.Data.SqlTypes; namespace Newtonsoft.Utilities.Time { public static class DateTimeUtils { public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, 0); public static DateTime ToSqlServerPrecision(DateTime value) { SqlDateTime sqlValue = new SqlDateTime(value); return sqlValue.Value; } public static DateTime ConvertUnixSeconds(long unixSeconds, long residualNanoseconds) { DateTime actualDateTime = ConvertUnixSeconds(unixSeconds); long ticks = residualNanoseconds / 100; return actualDateTime.AddTicks(ticks); } public static DateTime ConvertUnixSeconds(long unixSeconds) { return UnixEpoch.AddSeconds(unixSeconds); } public static string ToFileSortableDateTime(DateTime value) { return value.ToString("yyyyMMdd'T'HHmmss", CultureInfo.CurrentCulture); } public static DateTime FromFileSortableDateTime(string value) { return DateTime.ParseExact(value, "yyyyMMdd'T'HHmmss", CultureInfo.CurrentCulture); } } }
Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value.
//http://www.bouncycastle.org/ //MIT X11 License using System; namespace Org.BouncyCastle.Utilities.Date { public class DateTimeUtilities { public static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1); private DateTimeUtilities() { } /// <summary> /// Return the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC) for a given DateTime value. /// </summary> /// <param name="dateTime">A UTC DateTime value not before epoch.</param> /// <returns>Number of whole milliseconds after epoch.</returns> /// <exception cref="ArgumentException">'dateTime' is before epoch.</exception> public static long DateTimeToUnixMs(DateTime dateTime) { if (dateTime.CompareTo(UnixEpoch) < 0) throw new ArgumentException("DateTime value may not be before the epoch", "dateTime"); return (dateTime.Ticks - UnixEpoch.Ticks) / TimeSpan.TicksPerMillisecond; } /// <summary> /// Create a DateTime value from the number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). /// </summary> /// <param name="unixMs">Number of milliseconds since the epoch.</param> /// <returns>A UTC DateTime value</returns> public static DateTime UnixMsToDateTime(long unixMs) { return new DateTime(unixMs * TimeSpan.TicksPerMillisecond + UnixEpoch.Ticks); } /// <summary> /// Return the current number of milliseconds since the Unix epoch (1 Jan., 1970 UTC). /// </summary> public static long CurrentUnixMs() { return DateTimeToUnixMs(DateTime.UtcNow); } } }
Date and time To Words
#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Globalization; namespace Newtonsoft.Utilities.Text { public class FormatUtils { private static readonly string[] fuzzyHours = new string[] { "midnight", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "noon", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven" }; private static readonly string[] fuzzyMinutes = new string[] { "five", "ten", "a quarter", "twenty", "twenty five", "half" }; public static string DateTimeToWords(DateTime date) { return DateTimeToWords(date, DateTime.Now); } public static string DateTimeToWords(DateTime dateTime, DateTime currentDate) { string result; TimeSpan t1 = new TimeSpan(currentDate.Ticks); TimeSpan t2 = new TimeSpan(dateTime.Ticks); int daysElapsed = t1.Days - t2.Days; if (daysElapsed < -7 || daysElapsed >= 14) result = DateToWords(dateTime, currentDate); else if (daysElapsed == 0) result = "this " + GetPeriod(dateTime.Hour); else result = DateToWords(dateTime, currentDate) + " " + GetPeriod(dateTime.Hour); return (result + " at " + TimeToWords(dateTime)); } public static string DateToWords(DateTime date) { return DateToWords(date, DateTime.Now); } public static string DateToWords(DateTime date, DateTime currentDate) { TimeSpan t1 = new TimeSpan(currentDate.Ticks); TimeSpan t2 = new TimeSpan(date.Ticks); int daysElapsed = t1.Days - t2.Days; if (daysElapsed < -1 && daysElapsed >= -7) return ("next " + date.ToString("dddd")); if (daysElapsed == -1) return "tomorrow"; if (daysElapsed == 0) return "today"; if (daysElapsed == 1) return "yesterday"; if (daysElapsed > 1 && daysElapsed < 7) return date.ToString("dddd"); if (daysElapsed >= 7 && daysElapsed < 14) return "last " + date.ToString("dddd"); return (date.ToString("MMMM") + " " + GetOrdinal(date.Day) + ((date.Year != currentDate.Year) ? (" " + date.ToString("yyyy")) : string.Empty)); } public static string GetOrdinal(int value) { string[] _suffixes = new string[] { "th", "st", "nd", "rd" }; int tenth = value % 10; if (tenth >= _suffixes.Length) { return _suffixes[0]; } else { // special case for 11, 12, 13 int hundredth = value % 100; if (hundredth >= 11 && hundredth <= 13) return _suffixes[0]; return _suffixes[tenth]; } } private static string GetPeriod(int hour) { if (hour > 18) return "evening"; if (hour > 12) return "afternoon"; if (hour > 3) return "morning"; return "night"; } public static string TimeToWords(DateTime time) { string result; int minutes = time.Minute; int hours = time.Hour; bool toHour = false; int remainder = time.Minute % 5; if (remainder < 3) minutes -= remainder; else minutes += 5 - remainder; if (minutes > 30) { hours = (hours + 1) % 24; minutes = 60 - minutes; toHour = true; } if (minutes != 0) result = fuzzyMinutes[minutes / 6] + " " + (toHour ? "to" : "past") + " " + fuzzyHours[hours]; else result = fuzzyHours[hours] + ((hours != 0 && hours != 12) ? " o'clock" : string.Empty); if (hours > 0 && hours < 12) return result + " am"; if (hours > 12) result = result + " pm"; return result; } } }
Get the week number
//Octavalent Extension Methods //http://sdfasdf.codeplex.com/ //Library of extension methods for .Net create by Octavalent (www.octavalent.nl) using System; namespace System.OctavalentExtensions { public static class DateTimeExtensions { #region Week public static int GetWeekNumber(this DateTime date) { // Updated 2004.09.27. Cleaned the code and fixed abug. Compared the algorithm with // code published here . Tested code successfully against the other algorithm // for all dates in all years between 1900 and 2100. // Thanks to Marcus Dahlberg for pointing out the deficient logic. // Calculates the ISO 8601 Week Number // In this scenario the first day of the week is monday, // and the week rule states that: // [...] the first calendar week of a year is the one // that includes the first Thursday of that year and // [...] the last calendar week of a calendar year is // the week immediately preceding the first // calendar week of the next year. // The first week of the year may thus start in the // preceding year const int JAN = 1; const int DEC = 12; const int LASTDAYOFDEC = 31; const int FIRSTDAYOFJAN = 1; const int THURSDAY = 4; bool ThursdayFlag = false; // Get the day number since the beginning of the year int DayOfYear = date.DayOfYear; // Get the numeric weekday of the first day of the // year (using sunday as FirstDay) var StartWeekDayOfYear = (int) (new DateTime(date.Year, JAN, FIRSTDAYOFJAN)).DayOfWeek; var EndWeekDayOfYear = (int) (new DateTime(date.Year, DEC, LASTDAYOFDEC)).DayOfWeek; // Compensate for the fact that we are using monday // as the first day of the week if (StartWeekDayOfYear == 0) StartWeekDayOfYear = 7; if (EndWeekDayOfYear == 0) EndWeekDayOfYear = 7; // Calculate the number of days in the first and last week int DaysInFirstWeek = 8 - (StartWeekDayOfYear); // If the year either starts or ends on a thursday it will have a 53rd week if (StartWeekDayOfYear == THURSDAY || EndWeekDayOfYear == THURSDAY) ThursdayFlag = true; // We begin by calculating the number of FULL weeks between the start of the year and // our date. The number is rounded up, so the smallest possible value is 0. var FullWeeks = (int) Math.Ceiling((DayOfYear - (DaysInFirstWeek))/7.0); int WeekNumber = FullWeeks; // If the first week of the year has at least four days, then the actual week number for our date // can be incremented by one. if (DaysInFirstWeek >= THURSDAY) WeekNumber = WeekNumber + 1; // If week number is larger than week 52 (and the year doesn't either start or end on a thursday) // then the correct week number is 1. if (WeekNumber > 52 && !ThursdayFlag) WeekNumber = 1; // If week number is still 0, it means that we are trying to evaluate the week number for a // week that belongs in the previous year (since that week has 3 days or less in our date's year). // We therefore make a recursive call using the last day of the previous year. if (WeekNumber == 0) WeekNumber = new DateTime(date.Year - 1, DEC, LASTDAYOFDEC).GetWeekNumber(); return WeekNumber; } #endregion } }
Get the quarter number for the DateTime
//Octavalent Extension Methods //http://sdfasdf.codeplex.com/ //Library of extension methods for .Net create by Octavalent (www.octavalent.nl) using System; public static class DateTimeExtensions { public static int Quarter(this DateTime dateTime) { return Convert.ToInt16((dateTime.Month - 1)/3) + 1; } }
Add week to a DateTime
//Octavalent Extension Methods //http://sdfasdf.codeplex.com/ //Library of extension methods for .Net create by Octavalent (www.octavalent.nl) using System; public static class DateTimeExtensions { public static DateTime AddWeek(this DateTime dateTime, int count) { return dateTime.AddDays(7*count); } }