#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; } } }
Development Class
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); } }
Get Day Of Week
//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 GetDayOfWeek(this DateTime dt) { if (dt.DayOfWeek == DayOfWeek.Monday) return 1; if (dt.DayOfWeek == DayOfWeek.Tuesday) return 2; if (dt.DayOfWeek == DayOfWeek.Wednesday) return 3; if (dt.DayOfWeek == DayOfWeek.Thursday) return 4; if (dt.DayOfWeek == DayOfWeek.Friday) return 5; if (dt.DayOfWeek == DayOfWeek.Saturday) return 6; if (dt.DayOfWeek == DayOfWeek.Sunday) return 7; return 0; } }
Add Business Days
//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 AddBusinessDays(this DateTime date, int days)
{
int sign = Math.Sign(days);
int unsignedDays = Math.Abs(days);
for (int i = 0; i < unsignedDays; i++)
{
do
{
date = date.AddDays(sign);
} while (date.DayOfWeek == DayOfWeek.Saturday || date.DayOfWeek == DayOfWeek.Sunday);
}
return date;
}
}
[/csharp]
Return true if the number of seconds has elapsed since the last check
// crudwork // Copyright 2004 by Steve T. Pham (http://www.crudwork.com) // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with This program. If not, see <http://www.gnu.org/licenses/>. using System; using System.Collections.Generic; using System.Text; namespace crudwork.Utilities { /// <summary> /// Date Utility /// </summary> public class DateUtil { /// <summary> /// create new instance with default attributes /// </summary> public DateUtil() { } #region HasElapsed method private DateTime? then = null; /// <summary> /// <para>return true if the number of seconds has elapsed since the last check; otherwise return false.</para> /// <para>Use this method to raise a status report event to the GUI (for example, every 1 second) to prevent /// clogging the message pump.</para> /// </summary> /// <param name="seconds">specify number of seconds to check</param> /// <returns></returns> public bool HasElapsed(double seconds) { return HasElapsed(seconds, true); } /// <summary> /// <para>return true if the number of seconds has elapsed since the last check; otherwise return false.</para> /// <para>Use this method to raise a status report event to the GUI (for example, every 1 second) to prevent /// clogging the message pump.</para> /// </summary> /// <param name="seconds">specify number of seconds to check</param> /// <param name="mark">set true to mark the time if time has elapsed; or set false to do a test only</param> /// <returns></returns> public bool HasElapsed(double seconds, bool mark) { var now = DateTime.Now; if (!then.HasValue) { then = now; return false; // return false, because this is the very first check } if (then.Value.AddSeconds(seconds) >= now) return false; // the # of seconds has NOT elapsed... // yes, it has. mark new time for next check if (mark) then = now; return true; } #endregion } }