qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
sequence
4
<p>I want to assign the decimal variable &quot;trans&quot; to the double variable &quot;this.Opacity&quot;.</p> <pre class="lang-cs prettyprint-override"><code>decimal trans = trackBar1.Value / 5000; this.Opacity = trans; </code></pre> <p>When I build the app it gives the following error:</p> <blockquote> <p>Cannot implicitly convert type decimal to double</p> </blockquote>
[ { "answer_id": 7, "author": "Kevin Dente", "author_id": 9, "author_profile": "https://Stackoverflow.com/users/9", "pm_score": 10, "selected": true, "text": "double double trans = (double) trackBar1.Value / 5000.0;\n 5000.0 5000d double trans = trackBar1.Value / 5000.0;\ndouble trans = trackBar1.Value / 5000d;\n" }, { "answer_id": 78, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 6, "selected": false, "text": "this.Opacity" }, { "answer_id": 2791, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 6, "selected": false, "text": ".0 decimal.ToDouble() // Example 1\ndouble transparency = trackBar1.Value/5000;\nthis.Opacity = decimal.ToDouble(transparency);\n\n// Example 2 - with inline temp\nthis.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n" }, { "answer_id": 7263, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 7, "selected": false, "text": "decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n (double)" }, { "answer_id": 110198, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 7, "selected": false, "text": "private void Form1_Load(object sender, System.EventArgs e)\n{\n TrackBar1.Minimum = 20;\n TrackBar1.Maximum = 100;\n\n TrackBar1.LargeChange = 10;\n TrackBar1.SmallChange = 1;\n TrackBar1.TickFrequency = 5;\n}\n\nprivate void TrackBar1_Scroll(object sender, System.EventArgs e)\n{\n this.Opacity = TrackBar1.Value / 100;\n}\n" }, { "answer_id": 305467, "author": "Dinah", "author_id": 356, "author_profile": "https://Stackoverflow.com/users/356", "pm_score": 6, "selected": false, "text": "5000.0 5000" }, { "answer_id": 594436, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": false, "text": "Opacity TrackBar.Value trackBar.Value trackBar.Value trackBar.Opacity = (double)trackBar.Value / 5000.0;\n" }, { "answer_id": 7262112, "author": "Darin Dimitrov", "author_id": 29407, "author_profile": "https://Stackoverflow.com/users/29407", "pm_score": 6, "selected": false, "text": "double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n this.Opacity = trackBar1.Value / 5000.0;\n this.Opacity = trackBar1.Value / 5000d;\n 5000.0 5000d trackBar1.Value" }, { "answer_id": 7262131, "author": "ChrisF", "author_id": 59303, "author_profile": "https://Stackoverflow.com/users/59303", "pm_score": 6, "selected": false, "text": "Form.Opacity double double trans = trackBar1.Value / 5000.0;\nthis.Opacity = trans;\n this.Opacity = trackBar1.Value / 5000.0;\n double trans = trackbar1.Value / 5000;\n 5000 trackbar1.Value trans .0" }, { "answer_id": 9579950, "author": "Danny Fox", "author_id": 1091828, "author_profile": "https://Stackoverflow.com/users/1091828", "pm_score": 6, "selected": false, "text": "this.Opacity = decimal.ToDouble(trackBar1.Value/5000);\n" }, { "answer_id": 10568821, "author": "Darryl", "author_id": 1391700, "author_profile": "https://Stackoverflow.com/users/1391700", "pm_score": 6, "selected": false, "text": "Opacity Opacity = trackBar1.Value / 5000.0;\n" }, { "answer_id": 71840515, "author": "Arnold Brown", "author_id": 5049244, "author_profile": "https://Stackoverflow.com/users/5049244", "pm_score": 1, "selected": false, "text": "decimal d1 = 3234.3434m;\n double r1 = Decimal.ToDouble(d1);\n" }, { "answer_id": 72996737, "author": "David Rodrigues", "author_id": 5768360, "author_profile": "https://Stackoverflow.com/users/5768360", "pm_score": 1, "selected": false, "text": "Double Decimal decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = (double) trans;\n decimal trans = trackBar1.Value / 5000m;\nthis.Opacity = decimal.ToDouble(trans);\n 5000d 5000.0 decimal 1.0 1d" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/4", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8/" ]
6
<p>I have an absolutely positioned <code>div</code> containing several children, one of which is a relatively positioned <code>div</code>. When I use a <code>percentage-based width</code> on the child <code>div</code>, it collapses to <code>0 width</code> on IE7, but not on Firefox or Safari.</p> <p>If I use <code>pixel width</code>, it works. If the parent is relatively positioned, the percentage width on the child works.</p> <ol> <li>Is there something I'm missing here?</li> <li>Is there an easy fix for this besides the <code>pixel-based width</code> on the child?</li> <li>Is there an area of the CSS specification that covers this?</li> </ol>
[ { "answer_id": 31, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "div width div width div" }, { "answer_id": 1948, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": 6, "selected": false, "text": "#absdiv {\n position: absolute; \n left: 100px; \n top: 100px; \n width: 80%; \n height: 60%; \n background: #999;\n}\n\n#pctchild {\n width: 60%; \n height: 40%; \n background: #CCC;\n}\n\n#reldiv {\n position: relative;\n left: 20px;\n top: 20px;\n height: 25px;\n width: 40%;\n background: red;\n} <div id=\"absdiv\">\n <div id=\"reldiv\"></div>\n <div id=\"pctchild\"></div>\n</div>" }, { "answer_id": 43377, "author": "Evil Andy", "author_id": 4431, "author_profile": "https://Stackoverflow.com/users/4431", "pm_score": 5, "selected": false, "text": "div div" }, { "answer_id": 856615, "author": "lock", "author_id": 24744, "author_profile": "https://Stackoverflow.com/users/24744", "pm_score": 5, "selected": false, "text": "em em" }, { "answer_id": 3998843, "author": "Mike", "author_id": 484413, "author_profile": "https://Stackoverflow.com/users/484413", "pm_score": 5, "selected": false, "text": "hasLayout" }, { "answer_id": 52225050, "author": "Mohamed El Mrabet", "author_id": 1314885, "author_profile": "https://Stackoverflow.com/users/1314885", "pm_score": 3, "selected": false, "text": "div <div id=\"parent\" style=\"width:230px;\">\n <div id=\"child1\"></div>\n <div id=\"child2\"></div>\n</div>\n" }, { "answer_id": 64219066, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<div> <div> <div id=\"MainDiv\" style=\"width:60%;\">\n <div id=\"Div1\">\n ...\n </div>\n <div id=\"Div2\">\n ...\n </div>\n ...\n</div>\n" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/6", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9/" ]
9
<p>Given a <code>DateTime</code> representing a person's birthday, how do I calculate their age in years?</p>
[ { "answer_id": 22, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 6, "selected": false, "text": "DateTime birthDate = new DateTime(2000,3,1);\nint age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D);\n" }, { "answer_id": 229, "author": "Michael Stum", "author_id": 91, "author_profile": "https://Stackoverflow.com/users/91", "pm_score": 7, "selected": false, "text": "public static int GetAge(DateTime birthDate)\n{\n DateTime n = DateTime.Now; // To avoid a race condition around midnight\n int age = n.Year - birthDate.Year;\n\n if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day))\n age--;\n\n return age;\n}\n" }, { "answer_id": 1404, "author": "Mike Polen", "author_id": 212, "author_profile": "https://Stackoverflow.com/users/212", "pm_score": 12, "selected": true, "text": "// Save today's date.\nvar today = DateTime.Today;\n\n// Calculate the age.\nvar age = today.Year - birthdate.Year;\n\n// Go back to the year in which the person was born in case of a leap year\nif (birthdate.Date > today.AddYears(-age)) age--;\n" }, { "answer_id": 3261, "author": "David Wengier", "author_id": 489, "author_profile": "https://Stackoverflow.com/users/489", "pm_score": 6, "selected": false, "text": "public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt)\n{\n return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1);\n}\n DateTime DateTime.Now" }, { "answer_id": 11942, "author": "ScArcher2", "author_id": 1310, "author_profile": "https://Stackoverflow.com/users/1310", "pm_score": 10, "selected": false, "text": "yyyymmdd 20080814 - 19800703 = 280111 \n 28 int now = int.Parse(DateTime.Now.ToString(\"yyyyMMdd\"));\nint dob = int.Parse(dateOfBirth.ToString(\"yyyyMMdd\"));\nint age = (now - dob) / 10000;\n public static Int32 GetAge(this DateTime dateOfBirth)\n{\n var today = DateTime.Today;\n\n var a = (today.Year * 100 + today.Month) * 100 + today.Day;\n var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day;\n\n return (a - b) / 10000;\n}\n" }, { "answer_id": 24242, "author": "user2601", "author_id": 2601, "author_profile": "https://Stackoverflow.com/users/2601", "pm_score": 5, "selected": false, "text": "using System;\nusing System.Data;\nusing System.Data.Sql;\nusing System.Data.SqlClient;\nusing System.Data.SqlTypes;\nusing Microsoft.SqlServer.Server;\n\npublic partial class UserDefinedFunctions\n{\n [SqlFunction(DataAccess = DataAccessKind.Read)]\n public static SqlInt32 CalculateAge(string strBirthDate)\n {\n DateTime dtBirthDate = new DateTime();\n dtBirthDate = Convert.ToDateTime(strBirthDate);\n DateTime dtToday = DateTime.Now;\n\n // get the difference in years\n int years = dtToday.Year - dtBirthDate.Year;\n\n // subtract another year if we're before the\n // birth day in the current year\n if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day))\n years=years-1;\n\n int intCustomerAge = years;\n return intCustomerAge;\n }\n};\n" }, { "answer_id": 141644, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DateTime myBD = new DateTime(1980, 10, 10);\nTimeSpan difference = DateTime.Now.Subtract(myBD);\n\ntextBox1.Text = difference.Years + \" years \" + difference.Months + \" Months \" + difference.Days + \" days\";\n" }, { "answer_id": 168703, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 7, "selected": false, "text": "int age = (int) ((DateTime.Now - bday).TotalDays/365.242199);\n" }, { "answer_id": 877247, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "public void LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n\n days +=\n DateTime.DaysInMonth(\n FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month\n ) + FutureDate.Day - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if (FutureDate >= new DateTime(FutureDate.Year, 3, 1))\n days++;\n }\n\n}\n" }, { "answer_id": 877516, "author": "SillyMonkey", "author_id": 88600, "author_profile": "https://Stackoverflow.com/users/88600", "pm_score": 6, "selected": false, "text": "int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1;\n" }, { "answer_id": 1011981, "author": "Rajeshwaran S P", "author_id": 21995, "author_profile": "https://Stackoverflow.com/users/21995", "pm_score": 4, "selected": false, "text": "DateTime dateOfBirth = new DateTime(2000, 4, 18);\nDateTime currentDate = DateTime.Now;\n\nint ageInYears = 0;\nint ageInMonths = 0;\nint ageInDays = 0;\n\nageInDays = currentDate.Day - dateOfBirth.Day;\nageInMonths = currentDate.Month - dateOfBirth.Month;\nageInYears = currentDate.Year - dateOfBirth.Year;\n\nif (ageInDays < 0)\n{\n ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month);\n ageInMonths = ageInMonths--;\n\n if (ageInMonths < 0)\n {\n ageInMonths += 12;\n ageInYears--;\n }\n}\n\nif (ageInMonths < 0)\n{\n ageInMonths += 12;\n ageInYears--;\n}\n\nConsole.WriteLine(\"{0}, {1}, {2}\", ageInYears, ageInMonths, ageInDays);\n" }, { "answer_id": 1595311, "author": "RMA", "author_id": 193184, "author_profile": "https://Stackoverflow.com/users/193184", "pm_score": 9, "selected": false, "text": "DateTime bDay = new DateTime(2000, 2, 29);\nDateTime now = new DateTime(2009, 2, 28);\nMessageBox.Show(string.Format(\"Test {0} {1} {2}\",\n CalculateAgeWrong1(bDay, now), // outputs 9\n CalculateAgeWrong2(bDay, now), // outputs 9\n CalculateAgeCorrect(bDay, now), // outputs 8\n CalculateAgeCorrect2(bDay, now))); // outputs 8\n public int CalculateAgeWrong1(DateTime birthDate, DateTime now)\n{\n return new DateTime(now.Subtract(birthDate).Ticks).Year - 1;\n}\n\npublic int CalculateAgeWrong2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now < birthDate.AddYears(age))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day))\n age--;\n\n return age;\n}\n\npublic int CalculateAgeCorrect2(DateTime birthDate, DateTime now)\n{\n int age = now.Year - birthDate.Year;\n\n // For leap years we need this\n if (birthDate > now.AddYears(-age)) \n age--;\n // Don't use:\n // if (birthDate.AddYears(age) > now) \n // age--;\n\n return age;\n}\n" }, { "answer_id": 1811311, "author": "azamsharp", "author_id": 3797, "author_profile": "https://Stackoverflow.com/users/3797", "pm_score": 2, "selected": false, "text": "public override bool IsValid(DateTime value)\n{\n _dateOfBirth = value;\n var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365);\n if (yearsOld > 18)\n return true;\n return false;\n}\n" }, { "answer_id": 1913553, "author": "Frederik Gheysels", "author_id": 55774, "author_profile": "https://Stackoverflow.com/users/55774", "pm_score": 2, "selected": false, "text": "public struct Age : IEquatable<Age>, IComparable<Age>\n{\n private readonly int _years;\n private readonly int _months;\n private readonly int _days;\n\n public int Years { get { return _years; } }\n public int Months { get { return _months; } }\n public int Days { get { return _days; } }\n\n public Age( int years, int months, int days ) : this()\n {\n _years = years;\n _months = months;\n _days = days;\n }\n\n public static Age CalculateAge( DateTime dateOfBirth, DateTime date )\n {\n // Here is some logic that ressembles Mike's solution, although it\n // also takes into account months & days.\n // Ommitted for brevity.\n return new Age (years, months, days);\n }\n\n // Ommited Equality, Comparable, GetHashCode, functionality for brevity.\n}\n" }, { "answer_id": 1928680, "author": "Jon", "author_id": 234611, "author_profile": "https://Stackoverflow.com/users/234611", "pm_score": 2, "selected": false, "text": "public string LoopAge(DateTime myDOB, DateTime FutureDate)\n{\n int years = 0;\n int months = 0;\n int days = 0;\n\n DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1);\n\n DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1);\n\n while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (FutureDate.Day >= myDOB.Day)\n {\n days = days + FutureDate.Day - myDOB.Day;\n }\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day;\n\n }\n\n //add an extra day if the dob is a leap day\n if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29)\n {\n //but only if the future date is less than 1st March\n if(FutureDate >= new DateTime(FutureDate.Year, 3,1))\n days++;\n }\n\n return \"Years: \" + years + \" Months: \" + months + \" Days: \" + days;\n}\n" }, { "answer_id": 2280982, "author": "Elmer", "author_id": 173109, "author_profile": "https://Stackoverflow.com/users/173109", "pm_score": 5, "selected": false, "text": "public static class DateTimeExtensions\n{\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Now);\n }\n\n public static int Age(this DateTime birthDate, DateTime offsetDate)\n {\n int result=0;\n result = offsetDate.Year - birthDate.Year;\n\n if (offsetDate.DayOfYear < birthDate.DayOfYear)\n {\n result--;\n }\n\n return result;\n }\n}\n" }, { "answer_id": 3513146, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00);\nTimeSpan ts = DateTime.Now - birth;\nConsole.WriteLine(\"You are approximately \" + ts.TotalSeconds.ToString() + \" seconds old.\");\n" }, { "answer_id": 3652116, "author": "AEMLoviji", "author_id": 440670, "author_profile": "https://Stackoverflow.com/users/440670", "pm_score": 4, "selected": false, "text": "private int GetAge(int _year, int _month, int _day\n{\n DateTime yourBirthDate= new DateTime(_year, _month, _day);\n\n DateTime todaysDateTime = DateTime.Today;\n int noOfYears = todaysDateTime.Year - yourBirthDate.Year;\n\n if (DateTime.Now.Month < yourBirthDate.Month ||\n (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day))\n {\n noOfYears--;\n }\n\n return noOfYears;\n}\n" }, { "answer_id": 3869003, "author": "Nicholas Carey", "author_id": 467473, "author_profile": "https://Stackoverflow.com/users/467473", "pm_score": 4, "selected": false, "text": "public int AgeInYears(DateTime birthDate, DateTime referenceDate)\n{\n Debug.Assert(referenceDate >= birthDate, \n \"birth date must be on or prior to the reference date\");\n\n DateTime birth = birthDate.Date;\n DateTime reference = referenceDate.Date;\n int years = (reference.Year - birth.Year);\n\n //\n // an offset of -1 is applied if the birth date has \n // not yet occurred in the current year.\n //\n if (reference.Month > birth.Month);\n else if (reference.Month < birth.Month) \n --years;\n else // in birth month\n {\n if (reference.Day < birth.Day)\n --years;\n }\n\n return years ;\n}\n public enum LeapDayRule\n{\n OrdinalDay = 1 ,\n LastDayOfMonth = 2 ,\n}\n\nstatic int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect)\n{\n bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day);\n DateTime cutoff;\n\n if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year))\n {\n switch (ruleInEffect)\n {\n case LeapDayRule.OrdinalDay:\n cutoff = new DateTime(reference.Year, 1, 1)\n .AddDays(birth.DayOfYear - 1);\n break;\n\n case LeapDayRule.LastDayOfMonth:\n cutoff = new DateTime(reference.Year, birth.Month, 1)\n .AddMonths(1)\n .AddDays(-1);\n break;\n\n default:\n throw new InvalidOperationException();\n }\n }\n else\n {\n cutoff = new DateTime(reference.Year, birth.Month, birth.Day);\n }\n\n int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1);\n return age < 0 ? 0 : age;\n}\n" }, { "answer_id": 5054317, "author": "camelCasus", "author_id": 624612, "author_profile": "https://Stackoverflow.com/users/624612", "pm_score": 7, "selected": false, "text": "AddYears DateTime public static class DateTimeExtensions\n{\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object today.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <returns>Age in years today. 0 is returned for a future date of birth.</returns>\n public static int Age(this DateTime birthDate)\n {\n return Age(birthDate, DateTime.Today);\n }\n\n /// <summary>\n /// Calculates the age in years of the current System.DateTime object on a later date.\n /// </summary>\n /// <param name=\"birthDate\">The date of birth</param>\n /// <param name=\"laterDate\">The date on which to calculate the age.</param>\n /// <returns>Age in years on a later day. 0 is returned as minimum.</returns>\n public static int Age(this DateTime birthDate, DateTime laterDate)\n {\n int age;\n age = laterDate.Year - birthDate.Year;\n\n if (age > 0)\n {\n age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age));\n }\n else\n {\n age = 0;\n }\n\n return age;\n }\n}\n class Program\n{\n static void Main(string[] args)\n {\n RunTest();\n }\n\n private static void RunTest()\n {\n DateTime birthDate = new DateTime(2000, 2, 28);\n DateTime laterDate = new DateTime(2011, 2, 27);\n string iso = \"yyyy-MM-dd\";\n\n for (int i = 0; i < 3; i++)\n {\n for (int j = 0; j < 3; j++)\n {\n Console.WriteLine(\"Birth date: \" + birthDate.AddDays(i).ToString(iso) + \" Later date: \" + laterDate.AddDays(j).ToString(iso) + \" Age: \" + birthDate.AddDays(i).Age(laterDate.AddDays(j)).ToString());\n }\n }\n\n Console.ReadKey();\n }\n}\n {\n Birth date: 2000-02-28 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-28 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-28 Later date: 2011-03-01 Age: 11\n Birth date: 2000-02-29 Later date: 2011-02-27 Age: 10\n Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2011-03-01 Age: 11\n Birth date: 2000-03-01 Later date: 2011-02-27 Age: 10\n Birth date: 2000-03-01 Later date: 2011-02-28 Age: 10\n Birth date: 2000-03-01 Later date: 2011-03-01 Age: 11\n}\n {\n Birth date: 2000-02-28 Later date: 2012-02-28 Age: 12\n Birth date: 2000-02-28 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-28 Later date: 2012-03-01 Age: 12\n Birth date: 2000-02-29 Later date: 2012-02-28 Age: 11\n Birth date: 2000-02-29 Later date: 2012-02-29 Age: 12\n Birth date: 2000-02-29 Later date: 2012-03-01 Age: 12\n Birth date: 2000-03-01 Later date: 2012-02-28 Age: 11\n Birth date: 2000-03-01 Later date: 2012-02-29 Age: 11\n Birth date: 2000-03-01 Later date: 2012-03-01 Age: 12\n}\n" }, { "answer_id": 5229568, "author": "Doron", "author_id": 649407, "author_profile": "https://Stackoverflow.com/users/649407", "pm_score": 4, "selected": false, "text": "static string CalcAge(DateTime birthDay)\n{\n DateTime currentDate = DateTime.Now; \n int approximateAge = currentDate.Year - birthDay.Year;\n int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - \n (currentDate.Month * 30 + currentDate.Day) ;\n\n if (approximateAge == 0 || approximateAge == 1)\n { \n int month = Math.Abs(daysToNextBirthDay / 30);\n int days = Math.Abs(daysToNextBirthDay % 30);\n\n if (month == 0)\n return \"Your age is: \" + daysToNextBirthDay + \" days\";\n\n return \"Your age is: \" + month + \" months and \" + days + \" days\"; ;\n }\n\n if (daysToNextBirthDay > 0)\n return \"Your age is: \" + --approximateAge + \" Years\";\n\n return \"Your age is: \" + approximateAge + \" Years\"; ;\n}\n" }, { "answer_id": 5623077, "author": "Marcel Toth", "author_id": 702199, "author_profile": "https://Stackoverflow.com/users/702199", "pm_score": 6, "selected": false, "text": "DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today; //we usually don't care about birth time\nTimeSpan age = today - birth; //.NET FCL should guarantee this as precise\ndouble ageInDays = age.TotalDays; //total number of days ... also precise\ndouble daysInYear = 365.2425; //statistical value for 400 years\ndouble ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise\n DateTime birth = DateTime.Parse(\"1.1.2000\");\nDateTime today = DateTime.Today;\nint age = today.Year - birth.Year; //people perceive their age in years\n\nif (today.Month < birth.Month ||\n ((today.Month == birth.Month) && (today.Day < birth.Day)))\n{\n age--; //birthday in current year not yet reached, we are 1 year younger ;)\n //+ no birthday for 29.2. guys ... sorry, just wrong date for birth\n}\n public static int GetAge(DateTime bithDay, DateTime today) \n{ \n //chosen solution method body\n}\n\npublic static int GetAge(DateTime birthDay) \n{ \n return GetAge(birthDay, DateTime.Now);\n}\n" }, { "answer_id": 5989087, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2 )\n{\n return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar );\n} // YearDiff\n\n// ----------------------------------------------------------------------\nprivate static int YearDiff( DateTime date1, DateTime date2, Calendar calendar )\n{\n if ( date1.Equals( date2 ) )\n {\n return 0;\n }\n\n int year1 = calendar.GetYear( date1 );\n int month1 = calendar.GetMonth( date1 );\n int year2 = calendar.GetYear( date2 );\n int month2 = calendar.GetMonth( date2 );\n\n // find the the day to compare\n int compareDay = date2.Day;\n int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 );\n if ( compareDay > compareDaysPerMonth )\n {\n compareDay = compareDaysPerMonth;\n }\n\n // build the compare date\n DateTime compareDate = new DateTime( year1, month2, compareDay,\n date2.Hour, date2.Minute, date2.Second, date2.Millisecond );\n if ( date2 > date1 )\n {\n if ( compareDate < date1 )\n {\n compareDate = compareDate.AddYears( 1 );\n }\n }\n else\n {\n if ( compareDate > date1 )\n {\n compareDate = compareDate.AddYears( -1 );\n }\n }\n return year2 - calendar.GetYear( compareDate );\n} // YearDiff\n // ----------------------------------------------------------------------\npublic void CalculateAgeSamples()\n{\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years\n PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) );\n // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years\n} // CalculateAgeSamples\n\n// ----------------------------------------------------------------------\npublic void PrintAge( DateTime birthDate, DateTime moment )\n{\n Console.WriteLine( \"Birthdate={0:d}, Age at {1:d} is {2} years\", birthDate, moment, YearDiff( birthDate, moment ) );\n} // PrintAge\n" }, { "answer_id": 6075141, "author": "B2K", "author_id": 763112, "author_profile": "https://Stackoverflow.com/users/763112", "pm_score": 2, "selected": false, "text": "public static class AgeExtender\n{\n public static int GetAge(this DateTime dt)\n {\n int d = int.Parse(dt.ToString(\"yyyyMMdd\"));\n int t = int.Parse(DateTime.Today.ToString(\"yyyyMMdd\"));\n return (t-d)/10000;\n }\n}\n" }, { "answer_id": 6719204, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "public int AgeInYears(DateTime bday)\n{\n DateTime now = DateTime.Today;\n int age = now.Year - bday.Year; \n if (bday.AddYears(age) > now) \n age--;\n return age;\n}\n" }, { "answer_id": 7046204, "author": "Dylan Hayes", "author_id": 892460, "author_profile": "https://Stackoverflow.com/users/892460", "pm_score": 3, "selected": false, "text": " public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate)\n {\n //----------------------------------------------------------------------\n // Can't determine age if we don't have a dates.\n //----------------------------------------------------------------------\n if (ndtBirthDate == null) return null;\n if (ndtReferralDate == null) return null;\n\n DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate);\n DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate);\n\n //----------------------------------------------------------------------\n // Create our Variables\n //----------------------------------------------------------------------\n Dictionary<string, int> dYMD = new Dictionary<string,int>();\n int iNowDate, iBirthDate, iYears, iMonths, iDays;\n string sDif = \"\";\n\n //----------------------------------------------------------------------\n // Store off current date/time and DOB into local variables\n //---------------------------------------------------------------------- \n iNowDate = int.Parse(dtReferralDate.ToString(\"yyyyMMdd\"));\n iBirthDate = int.Parse(dtBirthDate.ToString(\"yyyyMMdd\"));\n\n //----------------------------------------------------------------------\n // Calculate Years\n //----------------------------------------------------------------------\n sDif = (iNowDate - iBirthDate).ToString();\n iYears = int.Parse(sDif.Substring(0, sDif.Length - 4));\n\n //----------------------------------------------------------------------\n // Store Years in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Years\", iYears);\n\n //----------------------------------------------------------------------\n // Calculate Months\n //----------------------------------------------------------------------\n if (dtBirthDate.Month > dtReferralDate.Month)\n iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1;\n else\n iMonths = dtBirthDate.Month - dtReferralDate.Month;\n\n //----------------------------------------------------------------------\n // Store Months in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Months\", iMonths);\n\n //----------------------------------------------------------------------\n // Calculate Remaining Days\n //----------------------------------------------------------------------\n if (dtBirthDate.Day > dtReferralDate.Day)\n //Logic: Figure out the days in month previous to the current month, or the admitted month.\n // Subtract the birthday from the total days which will give us how many days the person has lived since their birthdate day the previous month.\n // then take the referral date and simply add the number of days the person has lived this month.\n\n //If referral date is january, we need to go back to the following year's December to get the days in that month.\n if (dtReferralDate.Month == 1)\n iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day; \n else\n iDays = dtReferralDate.Day - dtBirthDate.Day; \n\n //----------------------------------------------------------------------\n // Store Days in Return Value\n //----------------------------------------------------------------------\n dYMD.Add(\"Days\", iDays);\n\n return dYMD;\n}\n" }, { "answer_id": 8816564, "author": "Moshe L", "author_id": 1056259, "author_profile": "https://Stackoverflow.com/users/1056259", "pm_score": 2, "selected": false, "text": "Public Shared Function CalculateAge(BirthDate As DateTime) As Integer\n Dim HebCal As New System.Globalization.HebrewCalendar ()\n Dim now = DateTime.Now()\n Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate)\n Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate)\n If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1\n Return iAge\nEnd Function\n" }, { "answer_id": 9431192, "author": "musefan", "author_id": 838807, "author_profile": "https://Stackoverflow.com/users/838807", "pm_score": 3, "selected": false, "text": "DateTime now = DateTime.Today;\nDateTime birthday = new DateTime(1991, 02, 03);//3rd feb\n\nint age = now.Year - birthday.Year;\n\nif (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet\n age--;\n\nreturn age;\n" }, { "answer_id": 11328202, "author": "Narasimha", "author_id": 254790, "author_profile": "https://Stackoverflow.com/users/254790", "pm_score": 2, "selected": false, "text": "int age = (Int32.Parse(DateTime.Today.ToString(\"yyyyMMdd\")) - \n Int32.Parse(birthday.ToString(\"yyyyMMdd rawrrr\"))) / 10000;\n" }, { "answer_id": 13531544, "author": "flindeberg", "author_id": 691294, "author_profile": "https://Stackoverflow.com/users/691294", "pm_score": 4, "selected": false, "text": "second DateTime var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor;\n var then = ... // Then, in this case the birthday\nvar now = DateTime.UtcNow;\nint age = now.Year - then.Year;\nif (now.AddYears(-age) < then) age--;\n DateTime start, end = .... // Whatever, assume start is before end\n\ndouble startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365);\ndouble endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365);\ndouble middleContribution = (double) (end.Year - start.Year - 1);\n\ndouble DCF = startYearContribution + endYearContribution + middleContribution;\n DateTime start, end = .... // Whatever, assume start is before end\nint days = (end - start).Days;\n" }, { "answer_id": 13645039, "author": "rockXrock", "author_id": 1254006, "author_profile": "https://Stackoverflow.com/users/1254006", "pm_score": 4, "selected": false, "text": "public static string HowOld(DateTime birthday, DateTime now)\n{\n if (now < birthday)\n throw new ArgumentOutOfRangeException(\"birthday must be less than now.\");\n\n TimeSpan diff = now - birthday;\n int diffDays = (int)diff.TotalDays;\n\n if (diffDays > 7)//year, month and week\n {\n int age = now.Year - birthday.Year;\n\n if (birthday > now.AddYears(-age))\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" years\" : \" year\");\n }\n else\n {// month and week\n DateTime d = birthday;\n int diffMonth = 1;\n\n while (d.AddMonths(diffMonth) <= now)\n {\n diffMonth++;\n }\n\n age = diffMonth-1;\n\n if (age == 1 && d.Day > now.Day)\n age--;\n\n if (age > 0)\n {\n return age + (age > 1 ? \" months\" : \" month\");\n }\n else\n {\n age = diffDays / 7;\n return age + (age > 1 ? \" weeks\" : \" week\");\n }\n }\n }\n else if (diffDays > 0)\n {\n int age = diffDays;\n return age + (age > 1 ? \" days\" : \" day\");\n }\n else\n {\n int age = diffDays;\n return \"just born\";\n }\n}\n [TestMethod]\npublic void TestAge()\n{\n string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 years\", age);\n\n age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"10 months\", age);\n\n age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"11 months\", age);\n\n age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28));\n Assert.AreEqual(\"1 year\", age);\n\n age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n // NOTE.\n // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28);\n // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28);\n age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"1 month\", age);\n\n age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"3 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"4 weeks\", age);\n\n age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 week\", age);\n\n age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"5 days\", age);\n\n age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"1 day\", age);\n\n age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30));\n Assert.AreEqual(\"just born\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28));\n Assert.AreEqual(\"8 years\", age);\n\n age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1));\n Assert.AreEqual(\"9 years\", age);\n\n Exception e = null;\n\n try\n {\n age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30));\n }\n catch (ArgumentOutOfRangeException ex)\n {\n e = ex;\n }\n\n Assert.IsTrue(e != null);\n}\n" }, { "answer_id": 14125249, "author": "Stranger", "author_id": 1462452, "author_profile": "https://Stackoverflow.com/users/1462452", "pm_score": 2, "selected": false, "text": "private int CalculateAge()\n{\n//get birthdate\n DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value);\n int byear = dtBirth.Year;\n int bmonth = dtBirth.Month;\n int bday = dtBirth.Day;\n DateTime dtToday = DateTime.Now;\n int tYear = dtToday.Year;\n int tmonth = dtToday.Month;\n int tday = dtToday.Day;\n int age = tYear - byear;\n if (bmonth < tmonth)\n age--;\n else if (bmonth == tmonth && bday>tday)\n {\n age--;\n }\nreturn age;\n}\n" }, { "answer_id": 16142434, "author": "Matthew Watson", "author_id": 106159, "author_profile": "https://Stackoverflow.com/users/106159", "pm_score": 5, "selected": false, "text": "public static int AgeInYears(DateTime birthday, DateTime today)\n{\n return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;\n}\n Yn = DateTime.Now.Year, Yb = birthday.Year, Mn = DateTime.Now.Month, Mb = birthday.Month, Dn = DateTime.Now.Day, Db = birthday.Day age = Yn - Yb + (31*(Mn - Mb) + (Dn - Db)) / 372 Yn-Yb Yn-Yb-1 Mn<Mb -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30 -371 <= 31*(Mn - Mb) + (Dn - Db) <= -1 (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 Mn=Mb Dn<Db 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1 (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 Mn>Mb 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30 1 <= 31*(Mn - Mb) + (Dn - Db) <= 371 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 Mn=Mb Dn>Db 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 3 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 Mn=Mb Dn=Db 31*(Mn - Mb) + Dn-Db = 0 (31*(Mn - Mb) + (Dn - Db)) / 372 = 0" }, { "answer_id": 18682920, "author": "vulcan raven", "author_id": 863980, "author_profile": "https://Stackoverflow.com/users/863980", "pm_score": 2, "selected": false, "text": "public int GetAge(DateTime DateOfBirth)\n{\n var Now = DateTime.UtcNow;\n return Now.Year - DateOfBirth.Year -\n (\n (\n Now.Month > DateOfBirth.Month ||\n (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)\n ) ? 0 : 1\n );\n}\n" }, { "answer_id": 18895699, "author": "Archit", "author_id": 2435287, "author_profile": "https://Stackoverflow.com/users/2435287", "pm_score": 1, "selected": false, "text": "System.DateTime birthTime = AskTheUser(myUser); // :-)\nSystem.DateTime now = System.DateTime.Now;\nSystem.TimeSpan age = now - birthTime; // As simple as that\ndouble ageInDays = age.TotalDays; // Will you convert to whatever you want yourself?\n" }, { "answer_id": 18898663, "author": "Dakotah Hicock", "author_id": 1226335, "author_profile": "https://Stackoverflow.com/users/1226335", "pm_score": 4, "selected": false, "text": "TimeSpan diff = DateTime.Now - birthdayDateTime;\nstring age = String.Format(\"{0:%y} years, {0:%M} months, {0:%d}, days old\", diff);\n" }, { "answer_id": 18924226, "author": "Jacqueline Loriault", "author_id": 2778315, "author_profile": "https://Stackoverflow.com/users/2778315", "pm_score": 5, "selected": false, "text": "DateTime birth = new DateTime(1974, 8, 29);\nDateTime today = DateTime.Now;\nTimeSpan span = today - birth;\nDateTime age = DateTime.MinValue + span;\n\n// Make adjustment due to MinValue equalling 1/1/1\nint years = age.Year - 1;\nint months = age.Month - 1;\nint days = age.Day - 1;\n\n// Print out not only how many years old they are but give months and days as well\nConsole.Write(\"{0} years, {1} months, {2} days\", years, months, days);\n" }, { "answer_id": 20348258, "author": "Dhaval Panchal", "author_id": 2368967, "author_profile": "https://Stackoverflow.com/users/2368967", "pm_score": -1, "selected": false, "text": "var ts = DateTime.Now - new DateTime(1988, 3, 19);\nvar age = Math.Round(ts.Days / 365.0);\n" }, { "answer_id": 20715576, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 4, "selected": false, "text": "static int GetAge(LocalDate dateOfBirth)\n{\n Instant now = SystemClock.Instance.Now;\n\n // The target time zone is important.\n // It should align with the *current physical location* of the person\n // you are talking about. When the whereabouts of that person are unknown,\n // then you use the time zone of the person who is *asking* for the age.\n // The time zone of birth is irrelevant!\n\n DateTimeZone zone = DateTimeZoneProviders.Tzdb[\"America/New_York\"];\n\n LocalDate today = now.InZone(zone).Date;\n\n Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years);\n\n return (int) period.Years;\n}\n LocalDate dateOfBirth = new LocalDate(1976, 8, 27);\nint age = GetAge(dateOfBirth);\n IClock SystemClock.Instance DateTimeZone" }, { "answer_id": 21276626, "author": "DareDevil", "author_id": 1147352, "author_profile": "https://Stackoverflow.com/users/1147352", "pm_score": 4, "selected": false, "text": "public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days)\n{\n years = 0;\n months = 0;\n days = 0;\n\n DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1);\n DateTime tmpnow = new DateTime(now.Year, now.Month, 1);\n\n while (tmpdob.AddYears(years).AddMonths(months) < tmpnow)\n {\n months++;\n if (months > 12)\n {\n years++;\n months = months - 12;\n }\n }\n\n if (now.Day >= dob.Day)\n days = days + now.Day - dob.Day;\n else\n {\n months--;\n if (months < 0)\n {\n years--;\n months = months + 12;\n }\n days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day;\n }\n\n if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1))\n days++;\n\n} \n\nprivate string ValidateDate(DateTime dob) //This method will validate the date\n{\n int Years = 0; int Months = 0; int Days = 0;\n\n GetAge(dob, DateTime.Now, out Years, out Months, out Days);\n\n if (Years < 18)\n message = Years + \" is too young. Please try again on your 18th birthday.\";\n else if (Years >= 65)\n message = Years + \" is too old. Date of Birth must not be 65 or older.\";\n else\n return null; //Denotes validation passed\n}\n DateTime dob = DateTime.Parse(\"03/10/1982\"); \n\nstring message = ValidateDate(dob);\n\nlbldatemessage.Visible = !StringIsNullOrWhitespace(message);\nlbldatemessage.Text = message ?? \"\"; //Ternary if message is null then default to empty string\n" }, { "answer_id": 25014539, "author": "Pratik Bhoir", "author_id": 2772550, "author_profile": "https://Stackoverflow.com/users/2772550", "pm_score": -1, "selected": false, "text": "DateTime dateOfBirth = Convert.ToDateTime(\"01/16/1990\");\nvar age = ((DateTime.Now - dateOfBirth).Days) / 365;\n" }, { "answer_id": 26529035, "author": "mjb", "author_id": 520848, "author_profile": "https://Stackoverflow.com/users/520848", "pm_score": 4, "selected": false, "text": "public int GetAge(DateTime birthDate)\n{\n int age = DateTime.Now.Year - birthDate.Year;\n\n if (birthDate.DayOfYear > DateTime.Now.DayOfYear)\n age--;\n\n return age;\n}\n\n\n\n\n" }, { "answer_id": 28567336, "author": "dav_i", "author_id": 1185053, "author_profile": "https://Stackoverflow.com/users/1185053", "pm_score": 2, "selected": false, "text": "public static int GetAgeByLoop(DateTime birthday)\n{\n var age = -1;\n\n for (var date = birthday; date < DateTime.Today; date = date.AddYears(1))\n {\n age++;\n }\n\n return age;\n}\n" }, { "answer_id": 30145502, "author": "mind_overflow", "author_id": 3889784, "author_profile": "https://Stackoverflow.com/users/3889784", "pm_score": -1, "selected": false, "text": "TimeSpan ts = DateTime.Now.Subtract(Birthdate);\nage = (byte)(ts.TotalDays / 365.25);\n" }, { "answer_id": 31025282, "author": "user1210708", "author_id": 1210708, "author_profile": "https://Stackoverflow.com/users/1210708", "pm_score": 2, "selected": false, "text": " public static string ToAge(this DateTime dob, DateTime? toDate = null)\n {\n if (!toDate.HasValue)\n toDate = DateTime.Now;\n var now = toDate.Value;\n\n if (now.CompareTo(dob) < 0)\n return \"Future date\";\n\n int years = now.Year - dob.Year;\n int months = now.Month - dob.Month;\n int days = now.Day - dob.Day;\n\n if (days < 0)\n {\n months--;\n days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day;\n }\n\n if (months < 0)\n {\n years--;\n months = 12 + months;\n }\n\n\n return string.Format(\"{0} year(s), {1} month(s), {2} days(s)\",\n years,\n months,\n days);\n }\n [Test]\n public void ToAgeTests()\n {\n var date = new DateTime(2000, 1, 1);\n Assert.AreEqual(\"0 year(s), 0 month(s), 1 days(s)\", new DateTime(1999, 12, 31).ToAge(date));\n Assert.AreEqual(\"0 year(s), 0 month(s), 0 days(s)\", new DateTime(2000, 1, 1).ToAge(date));\n Assert.AreEqual(\"1 year(s), 0 month(s), 0 days(s)\", new DateTime(1999, 1, 1).ToAge(date));\n Assert.AreEqual(\"0 year(s), 11 month(s), 0 days(s)\", new DateTime(1999, 2, 1).ToAge(date));\n Assert.AreEqual(\"0 year(s), 10 month(s), 25 days(s)\", new DateTime(1999, 2, 4).ToAge(date));\n Assert.AreEqual(\"0 year(s), 10 month(s), 1 days(s)\", new DateTime(1999, 2, 28).ToAge(date));\n\n date = new DateTime(2000, 2, 15);\n Assert.AreEqual(\"0 year(s), 0 month(s), 28 days(s)\", new DateTime(2000, 1, 18).ToAge(date));\n }\n" }, { "answer_id": 31077562, "author": "Lukas", "author_id": 593388, "author_profile": "https://Stackoverflow.com/users/593388", "pm_score": 3, "selected": false, "text": "int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1;\n" }, { "answer_id": 31178328, "author": "BrunoVT", "author_id": 4090831, "author_profile": "https://Stackoverflow.com/users/4090831", "pm_score": 2, "selected": false, "text": "DateTime birthDay = new DateTime(1990, 05, 23);\nDateTime age = DateTime.Now - birthDay;\n" }, { "answer_id": 32954095, "author": "VhsPiceros", "author_id": 581783, "author_profile": "https://Stackoverflow.com/users/581783", "pm_score": 2, "selected": false, "text": "DateTime zeroTime = new DateTime(1, 1, 1);\nvar date1 = new DateTime(1983, 03, 04);\nvar date2 = DateTime.Now;\nvar dif = date2 - date1;\nint years = (zeroTime + dif).Year - 1;\nLog.DebugFormat(\"Years -->{0}\", years);\n" }, { "answer_id": 33082044, "author": "Ahmed Sabry", "author_id": 4707576, "author_profile": "https://Stackoverflow.com/users/4707576", "pm_score": 2, "selected": false, "text": "public string GetAge(this DateTime birthdate, string ageStrinFormat = null)\n{\n var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day);\n return string.Format(ageStrinFormat ?? \"{0}/{1}/{2}\",\n (date.Year - birthdate.Year), date.Month, date.Day);\n}\n" }, { "answer_id": 36893577, "author": "CathalMF", "author_id": 1680271, "author_profile": "https://Stackoverflow.com/users/1680271", "pm_score": 3, "selected": false, "text": "DateTime Dob = DateTime.Parse(\"1985-04-24\");\n \nint Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1;\n" }, { "answer_id": 37022367, "author": "John Jang", "author_id": 3634867, "author_profile": "https://Stackoverflow.com/users/3634867", "pm_score": 3, "selected": false, "text": "DateTime today = DateTime.Today;\nDateTime bday = DateTime.Parse(\"2016-2-14\");\nint age = today.Year - bday.Year;\nvar unit = \"\";\n\nif (bday > today.AddYears(-age))\n{\n age--;\n}\nif (age == 0) // Under one year old\n{\n age = today.Month - bday.Month;\n\n age = age <= 0 ? (12 + age) : age; // The next year before birthday\n\n age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day\n\n unit = \"month\";\n}\nelse {\n unit = \"year\";\n}\n\nif (age > 1)\n{\n unit = unit + \"s\";\n}\n The birthday: 2016-2-14\n\n2016-2-15 => age=0, unit=month;\n2016-5-13 => age=2, unit=months;\n2016-5-14 => age=3, unit=months; \n2016-6-13 => age=3, unit=months; \n2016-6-15 => age=4, unit=months; \n2017-1-13 => age=10, unit=months; \n2017-1-14 => age=11, unit=months; \n2017-2-13 => age=11, unit=months; \n2017-2-14 => age=1, unit=year; \n2017-2-15 => age=1, unit=year; \n2017-3-13 => age=1, unit=year;\n2018-1-13 => age=1, unit=year; \n2018-1-14 => age=1, unit=year; \n2018-2-13 => age=1, unit=year; \n2018-2-14 => age=2, unit=years; \n" }, { "answer_id": 38121726, "author": "xenedia", "author_id": 836565, "author_profile": "https://Stackoverflow.com/users/836565", "pm_score": 3, "selected": false, "text": "declare @dd smalldatetime = '1980-04-01'\ndeclare @age int = YEAR(GETDATE())-YEAR(@dd)\nif (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1\n\nprint @age \n" }, { "answer_id": 39779195, "author": "André Sobreiro", "author_id": 3177959, "author_profile": "https://Stackoverflow.com/users/3177959", "pm_score": 3, "selected": false, "text": "private int CalcularIdade(DateTime dtNascimento)\n {\n var nHoje = Convert.ToInt32(DateTime.Today.ToString(\"yyyyMMdd\"));\n var nAniversario = Convert.ToInt32(dtNascimento.ToString(\"yyyyMMdd\"));\n\n double diff = (nHoje - nAniversario) / 10000;\n\n var ret = Convert.ToInt32(Math.Truncate(diff));\n\n return ret;\n }\n" }, { "answer_id": 40196001, "author": "K1laba", "author_id": 1591350, "author_profile": "https://Stackoverflow.com/users/1591350", "pm_score": 3, "selected": false, "text": "private int GetYearDiff(DateTime start, DateTime end)\n{\n int diff = end.Year - start.Year;\n if (end.DayOfYear < start.DayOfYear) { diff -= 1; }\n return diff;\n}\n[Fact]\npublic void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff()\n{\n //arrange\n var now = DateTime.Now;\n //act\n //assert\n Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed\n Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed\n Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed\n}\n" }, { "answer_id": 45127603, "author": "Sean Kearon", "author_id": 2608, "author_profile": "https://Stackoverflow.com/users/2608", "pm_score": 2, "selected": false, "text": "int AgeNow(DateTime birthday)\n{\n return AgeAt(DateTime.Now, birthday);\n}\n\nint AgeAt(DateTime now, DateTime birthday)\n{\n return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar);\n}\n\nint AgeAt(DateTime now, DateTime birthday, Calendar calendar)\n{\n // My age has increased on the morning of my\n // birthday even though I was born in the evening.\n now = now.Date;\n birthday = birthday.Date;\n\n var age = 0;\n if (now <= birthday) return age; // I am zero now if I am to be born tomorrow.\n\n while (calendar.AddYears(birthday, age + 1) <= now)\n {\n age++;\n }\n return age;\n}\n PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968\nPASSED: someone born on 29 February 1964 is age 3 on 28 February 1968\nPASSED: someone born on 31 December 2016 is age 0 on 01 January 2017\n" }, { "answer_id": 46968983, "author": "Sunny Jangid", "author_id": 6803066, "author_profile": "https://Stackoverflow.com/users/6803066", "pm_score": 2, "selected": false, "text": " var birthYear=1993;\n var age = DateTime.Now.AddYears(-birthYear).Year;\n" }, { "answer_id": 47035067, "author": "Kaval Patel", "author_id": 6629154, "author_profile": "https://Stackoverflow.com/users/6629154", "pm_score": 0, "selected": false, "text": "DateTime dateOfBirth;\n\nint ageInYears = DateTime.Now.Year - dateOfBirth.Year;\n\nif (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --;\n" }, { "answer_id": 47837162, "author": "Moises Conejo", "author_id": 4155324, "author_profile": "https://Stackoverflow.com/users/4155324", "pm_score": 2, "selected": false, "text": "(DateTime.Now - myDate).TotalHours / 8766.0\n myDate = TimeSpan" }, { "answer_id": 48688691, "author": "wild coder", "author_id": 9106094, "author_profile": "https://Stackoverflow.com/users/9106094", "pm_score": 2, "selected": false, "text": " C#\n // get the difference in years\n int years = DateTime.Now.Year - BirthDate.Year; \n // subtract another year if we're before the\n // birth day in the current year\n if (DateTime.Now.Month < BirthDate.Month || \n (DateTime.Now.Month == BirthDate.Month && \n DateTime.Now.Day < BirthDate.Day)) \n years--;\n VB.NET\n ' get the difference in years\n Dim years As Integer = DateTime.Now.Year - BirthDate.Year\n ' subtract another year if we're before the\n ' birth day in the current year\n If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then \n years = years - 1\n End If\n" }, { "answer_id": 48805951, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "var birthDate = ... // DOB\nvar resultDate = DateTime.Now - birthDate;\n resultDate TimeSpan" }, { "answer_id": 60541141, "author": "Alexander", "author_id": 11841521, "author_profile": "https://Stackoverflow.com/users/11841521", "pm_score": 0, "selected": false, "text": " DateTime dob = new DateTime(1991, 3, 4); \n DateTime now = DateTime.Now; \n int dobDay = dob.Day, dobMonth = dob.Month; \n int add = -1; \n if (dobMonth < now.Month)\n {\n add = 0;\n }\n else if (dobMonth == now.Month)\n {\n if(dobDay <= now.Day)\n {\n add = 0;\n }\n else\n {\n add = -1;\n }\n }\n else\n {\n add = -1;\n } \n int age = now.Year - dob.Year + add;\n" }, { "answer_id": 64085367, "author": "Alexander Díaz", "author_id": 11120141, "author_profile": "https://Stackoverflow.com/users/11120141", "pm_score": 0, "selected": false, "text": "int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1;\nConsole.WriteLine(\"Age {0}\", Age);\n" }, { "answer_id": 64135345, "author": "Abrar Jahin", "author_id": 2193439, "author_profile": "https://Stackoverflow.com/users/2193439", "pm_score": -1, "selected": false, "text": "using System;\n\nnamespace TSA\n{\n class BirthDay\n {\n double ageDay;\n public BirthDay(int day, int month, int year)\n {\n DateTime birthDate = new DateTime(year, month, day);\n ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow\n }\n\n internal int GetAgeYear()\n {\n return (int)Math.Truncate(ageDay / 365);\n }\n\n internal int GetAgeMonth()\n {\n return (int)Math.Truncate((ageDay % 365) / 30);\n }\n }\n}\n BirthDay b = new BirthDay(1,12,1990);\nint year = b.GetAgeYear();\nint month = b.GetAgeMonth();\n" }, { "answer_id": 64220001, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "DateTime using System;\n \npublic class Program\n{\n public static int getAge(int month, int day, int year) {\n DateTime today = DateTime.Today;\n int currentDay = today.Day;\n int currentYear = today.Year;\n int currentMonth = today.Month;\n int age = 0;\n if (currentMonth < month) {\n age -= 1;\n } else if (currentMonth == month) {\n if (currentDay < day) {\n age -= 1;\n }\n }\n currentYear -= year;\n age += currentYear;\n return age;\n }\n public static void Main()\n {\n int ageInYears = getAge(8, 10, 2007);\n Console.WriteLine(ageInYears);\n }\n}\n" }, { "answer_id": 68783776, "author": "Wylan Osorio", "author_id": 2249897, "author_profile": "https://Stackoverflow.com/users/2249897", "pm_score": 0, "selected": false, "text": "var startDate = new DateTime(2015, 04, 05);//your start date\nvar endDate = DateTime.Now;\nvar years = 0;\nwhile(startDate < endDate) \n{\n startDate = startDate.AddYears(1);\n if(startDate < endDate) \n {\n years++;\n }\n}\n" }, { "answer_id": 69123059, "author": "Rob", "author_id": 3178666, "author_profile": "https://Stackoverflow.com/users/3178666", "pm_score": 0, "selected": false, "text": "public static int AgeInYears(this System.DateTime source, System.DateTime target)\n => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age;\n public static double AgeInTotalYears(this System.DateTime source, System.DateTime target)\n{\n var sign = (source <= target ? 1 : -1);\n\n var ageInYears = AgeInYears(source, target); // The method above.\n\n var last = source.AddYears(ageInYears);\n var next = source.AddYears(ageInYears + sign);\n\n var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign;\n\n return ageInYears + fractionalAge;\n}\n" }, { "answer_id": 69981159, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year;\n" }, { "answer_id": 70659202, "author": "Wouter", "author_id": 4491768, "author_profile": "https://Stackoverflow.com/users/4491768", "pm_score": 0, "selected": false, "text": "public int GetAge(DateOnly birthDate, DateOnly today)\n{\n return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31);\n}\n" }, { "answer_id": 71185870, "author": "subcoder", "author_id": 8227155, "author_profile": "https://Stackoverflow.com/users/8227155", "pm_score": 1, "selected": false, "text": "public static int getAge(DateTime birthDate)\n{\n var today = DateTime.Today;\n var age = today.Year - birthDate.Year;\n var monthDiff = today.Month - birthDate.Month;\n var dayDiff = today.Day - birthDate.Day;\n\n if (dayDiff < 0)\n {\n monthDiff--;\n }\n if (monthDiff < 0)\n {\n age--;\n }\n return age;\n}\n" }, { "answer_id": 73211429, "author": "Ruchir Gupta", "author_id": 3832403, "author_profile": "https://Stackoverflow.com/users/3832403", "pm_score": 0, "selected": false, "text": " ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate);\n using Microsoft.VisualBasic;" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/9", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
11
<p>Given a specific <code>DateTime</code> value, how do I display relative time, like:</p> <ul> <li><code>2 hours ago</code></li> <li><code>3 days ago</code></li> <li><code>a month ago</code></li> </ul>
[ { "answer_id": 12, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 8, "selected": false, "text": "var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 60)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 60 * 2)\n{\n return \"a minute ago\";\n}\nif (delta < 45 * 60)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90 * 60)\n{\n return \"an hour ago\";\n}\nif (delta < 24 * 60 * 60)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48 * 60 * 60)\n{\n return \"yesterday\";\n}\nif (delta < 30 * 24 * 60 * 60)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12 * 30 * 24 * 60 * 60)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nint years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\nreturn years <= 1 ? \"one year ago\" : years + \" years ago\";\n" }, { "answer_id": 27, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 5, "selected": false, "text": "public static string ToLongString(this TimeSpan time)\n{\n string output = String.Empty;\n\n if (time.Days > 0)\n output += time.Days + \" days \";\n\n if ((time.Days == 0 || time.Days == 1) && time.Hours > 0)\n output += time.Hours + \" hr \";\n\n if (time.Days == 0 && time.Minutes > 0)\n output += time.Minutes + \" min \";\n\n if (output.Length == 0)\n output += time.Seconds + \" sec\";\n\n return output.Trim();\n}\n" }, { "answer_id": 1248, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 11, "selected": true, "text": "const int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nvar ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\ndouble delta = Math.Abs(ts.TotalSeconds);\n\nif (delta < 1 * MINUTE)\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n\nif (delta < 2 * MINUTE)\n return \"a minute ago\";\n\nif (delta < 45 * MINUTE)\n return ts.Minutes + \" minutes ago\";\n\nif (delta < 90 * MINUTE)\n return \"an hour ago\";\n\nif (delta < 24 * HOUR)\n return ts.Hours + \" hours ago\";\n\nif (delta < 48 * HOUR)\n return \"yesterday\";\n\nif (delta < 30 * DAY)\n return ts.Days + \" days ago\";\n\nif (delta < 12 * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n" }, { "answer_id": 1752, "author": "Wedge", "author_id": 332, "author_profile": "https://Stackoverflow.com/users/332", "pm_score": 4, "selected": false, "text": "public class RelativeTimeRange : IComparable\n{\n public TimeSpan UpperBound { get; set; }\n\n public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta);\n\n public RelativeTimeTextDelegate MessageCreator { get; set; }\n\n public int CompareTo(object obj)\n {\n if (!(obj is RelativeTimeRange))\n {\n return 1;\n }\n // note that this sorts in reverse order to the way you'd expect, \n // this saves having to reverse a list later\n return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound);\n }\n}\n\npublic class PrintRelativeTime\n{\n private static List<RelativeTimeRange> timeRanges;\n\n static PrintRelativeTime()\n {\n timeRanges = new List<RelativeTimeRange>{\n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(1),\n MessageCreator = (delta) => \n { return \"one second ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromSeconds(60),\n MessageCreator = (delta) => \n { return delta.Seconds + \" seconds ago\"; }\n\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(2),\n MessageCreator = (delta) => \n { return \"one minute ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromMinutes(60),\n MessageCreator = (delta) => \n { return delta.Minutes + \" minutes ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(2),\n MessageCreator = (delta) => \n { return \"one hour ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromHours(24),\n MessageCreator = (delta) => \n { return delta.Hours + \" hours ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.FromDays(2),\n MessageCreator = (delta) => \n { return \"yesterday\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)),\n MessageCreator = (delta) => \n { return delta.Days + \" days ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)),\n MessageCreator = (delta) => \n { return \"one month ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)),\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 30) + \" months ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)),\n MessageCreator = (delta) => \n { return \"one year ago\"; }\n }, \n new RelativeTimeRange\n {\n UpperBound = TimeSpan.MaxValue,\n MessageCreator = (delta) => \n { return (int)Math.Floor(delta.TotalDays / 365.24D) + \" years ago\"; }\n }\n };\n\n timeRanges.Sort();\n }\n\n public static string GetRelativeTimeMessage(TimeSpan ago)\n {\n RelativeTimeRange postRelativeDateRange = timeRanges[0];\n\n foreach (var timeRange in timeRanges)\n {\n if (ago.CompareTo(timeRange.UpperBound) <= 0)\n {\n postRelativeDateRange = timeRange;\n }\n }\n\n return postRelativeDateRange.MessageCreator(ago);\n }\n}\n" }, { "answer_id": 10705, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 7, "selected": false, "text": "public static string RelativeDate(DateTime theDate)\n{\n Dictionary<long, string> thresholds = new Dictionary<long, string>();\n int minute = 60;\n int hour = 60 * minute;\n int day = 24 * hour;\n thresholds.Add(60, \"{0} seconds ago\");\n thresholds.Add(minute * 2, \"a minute ago\");\n thresholds.Add(45 * minute, \"{0} minutes ago\");\n thresholds.Add(120 * minute, \"an hour ago\");\n thresholds.Add(day, \"{0} hours ago\");\n thresholds.Add(day * 2, \"yesterday\");\n thresholds.Add(day * 30, \"{0} days ago\");\n thresholds.Add(day * 365, \"{0} months ago\");\n thresholds.Add(long.MaxValue, \"{0} years ago\");\n long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000;\n foreach (long threshold in thresholds.Keys) \n {\n if (since < threshold) \n {\n TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks));\n return string.Format(thresholds[threshold], (t.Days > 365 ? t.Days / 365 : (t.Days > 0 ? t.Days : (t.Hours > 0 ? t.Hours : (t.Minutes > 0 ? t.Minutes : (t.Seconds > 0 ? t.Seconds : 0))))).ToString());\n }\n }\n return \"\";\n}\n Latest()" }, { "answer_id": 12279, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 4, "selected": false, "text": "var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks);\n DateTime TimeSpan (DateTime.UtcNow - dt).TotalSeconds\n" }, { "answer_id": 13690, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "public string GetRelativeTime(DateTime timeStamp)\n{\n return string.Format(\"<script>printdate({0});</script>\", timeStamp.ToFileTimeUtc());\n}\n" }, { "answer_id": 18393, "author": "icco", "author_id": 1063, "author_profile": "https://Stackoverflow.com/users/1063", "pm_score": 4, "selected": false, "text": "<?php\nfunction timesince($original) {\n // array of time period chunks\n $chunks = array(\n array(60 * 60 * 24 * 365 , 'year'),\n array(60 * 60 * 24 * 30 , 'month'),\n array(60 * 60 * 24 * 7, 'week'),\n array(60 * 60 * 24 , 'day'),\n array(60 * 60 , 'hour'),\n array(60 , 'minute'),\n );\n\n $today = time(); /* Current unix time */\n $since = $today - $original;\n\n if($since > 604800) {\n $print = date(\"M jS\", $original);\n\n if($since > 31536000) {\n $print .= \", \" . date(\"Y\", $original);\n }\n\n return $print;\n}\n\n// $j saves performing the count function each time around the loop\nfor ($i = 0, $j = count($chunks); $i < $j; $i++) {\n\n $seconds = $chunks[$i][0];\n $name = $chunks[$i][1];\n\n // finding the biggest chunk (if the chunk fits, break)\n if (($count = floor($since / $seconds)) != 0) {\n break;\n }\n}\n\n$print = ($count == 1) ? '1 '.$name : \"$count {$name}s\";\n\nreturn $print . \" ago\";\n\n} ?>\n" }, { "answer_id": 25709, "author": "Cebjyre", "author_id": 1612, "author_profile": "https://Stackoverflow.com/users/1612", "pm_score": 2, "selected": false, "text": "if (delta < 5400) // 90 * 60\n{\n return \"an hour ago\";\n}\n if (delta < 7200) // 120 * 60\n{\n return \"an hour ago\";\n}\n" }, { "answer_id": 79601, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "public static string ToRelativeDate(DateTime input)\n{\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n var aValue = new SortedList<double, Func<string>>();\n aValue.Add(0.75, () => \"less than a minute\");\n aValue.Add(1.5, () => \"about a minute\");\n aValue.Add(45, () => string.Format(\"{0} minutes\", Math.Round(TotalMinutes)));\n aValue.Add(90, () => \"about an hour\");\n aValue.Add(1440, () => string.Format(\"about {0} hours\", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24\n aValue.Add(2880, () => \"a day\"); // 60 * 48\n aValue.Add(43200, () => string.Format(\"{0} days\", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30\n aValue.Add(86400, () => \"about a month\"); // 60 * 24 * 60\n aValue.Add(525600, () => string.Format(\"{0} months\", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 \n aValue.Add(1051200, () => \"about a year\"); // 60 * 24 * 365 * 2\n aValue.Add(double.MaxValue, () => string.Format(\"{0} years\", Math.Floor(Math.Abs(oSpan.TotalDays / 365))));\n\n return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix;\n}\n static readonly SortedList<double, Func<TimeSpan, string>> offsets = \n new SortedList<double, Func<TimeSpan, string>>\n{\n { 0.75, _ => \"less than a minute\"},\n { 1.5, _ => \"about a minute\"},\n { 45, x => $\"{x.TotalMinutes:F0} minutes\"},\n { 90, x => \"about an hour\"},\n { 1440, x => $\"about {x.TotalHours:F0} hours\"},\n { 2880, x => \"a day\"},\n { 43200, x => $\"{x.TotalDays:F0} days\"},\n { 86400, x => \"about a month\"},\n { 525600, x => $\"{x.TotalDays / 30:F0} months\"},\n { 1051200, x => \"about a year\"},\n { double.MaxValue, x => $\"{x.TotalDays / 365:F0} years\"}\n};\n\npublic static string ToRelativeDate(this DateTime input)\n{\n TimeSpan x = DateTime.Now - input;\n string Suffix = x.TotalMinutes > 0 ? \" ago\" : \" from now\";\n x = new TimeSpan(Math.Abs(x.Ticks));\n return offsets.First(n => x.TotalMinutes < n.Key).Value(x) + Suffix;\n}\n" }, { "answer_id": 111303, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 9, "selected": false, "text": "jQuery(document).ready(function() {\n jQuery('abbr.timeago').timeago();\n});\n abbr <abbr class=\"timeago\" title=\"2008-07-17T09:24:17Z\">July 17, 2008</abbr>\n <abbr class=\"timeago\" title=\"July 17, 2008\">4 months ago</abbr>\n" }, { "answer_id": 118569, "author": "dreeves", "author_id": 4234, "author_profile": "https://Stackoverflow.com/users/4234", "pm_score": 3, "selected": false, "text": "agoify($delta)\n local($y, $mo, $d, $h, $m, $s);\n $s = floor($delta);\n if($s<=1) return \"a second ago\";\n if($s<60) return \"$s seconds ago\";\n $m = floor($s/60);\n if($m==1) return \"a minute ago\";\n if($m<45) return \"$m minutes ago\";\n $h = floor($m/60);\n if($h==1) return \"an hour ago\";\n if($h<24) return \"$h hours ago\";\n $d = floor($h/24);\n if($d<2) return \"yesterday\";\n if($d<30) return \"$d days ago\";\n $mo = floor($d/30);\n if($mo<=1) return \"a month ago\";\n $y = floor($mo/12);\n if($y<1) return \"$mo months ago\";\n if($y==1) return \"a year ago\";\n return \"$y years ago\";\n" }, { "answer_id": 229285, "author": "Jauder Ho", "author_id": 26366, "author_profile": "https://Stackoverflow.com/users/26366", "pm_score": 5, "selected": false, "text": "/*\n * Javascript Humane Dates\n * Copyright (c) 2008 Dean Landolt (deanlandolt.com)\n * Re-write by Zach Leatherman (zachleat.com)\n * \n * Adopted from the John Resig's pretty.js\n * at http://ejohn.org/blog/javascript-pretty-date\n * and henrah's proposed modification \n * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458\n * \n * Licensed under the MIT license.\n */\n\nfunction humane_date(date_str){\n var time_formats = [\n [60, 'just now'],\n [90, '1 minute'], // 60*1.5\n [3600, 'minutes', 60], // 60*60, 60\n [5400, '1 hour'], // 60*60*1.5\n [86400, 'hours', 3600], // 60*60*24, 60*60\n [129600, '1 day'], // 60*60*24*1.5\n [604800, 'days', 86400], // 60*60*24*7, 60*60*24\n [907200, '1 week'], // 60*60*24*7*1.5\n [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7\n [3942000, '1 month'], // 60*60*24*(365/12)*1.5\n [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12)\n [47304000, '1 year'], // 60*60*24*365*1.5\n [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365\n [4730400000, '1 century'] // 60*60*24*365*100*1.5\n ];\n\n var time = ('' + date_str).replace(/-/g,\"/\").replace(/[TZ]/g,\" \"),\n dt = new Date,\n seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000),\n token = ' ago',\n i = 0,\n format;\n\n if (seconds < 0) {\n seconds = Math.abs(seconds);\n token = '';\n }\n\n while (format = time_formats[i++]) {\n if (seconds < format[0]) {\n if (format.length == 2) {\n return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago\n } else {\n return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : '');\n }\n }\n }\n\n // overflow for centuries\n if(seconds > 4730400000)\n return Math.round(seconds / 4730400000) + ' centuries' + token;\n\n return date_str;\n};\n\nif(typeof jQuery != 'undefined') {\n jQuery.fn.humane_dates = function(){\n return this.each(function(){\n var date = humane_date(this.title);\n if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to\n jQuery(this).text(date);\n });\n };\n}\n" }, { "answer_id": 501415, "author": "Thomaschaaf", "author_id": 19929, "author_profile": "https://Stackoverflow.com/users/19929", "pm_score": 6, "selected": false, "text": "define(\"SECOND\", 1);\ndefine(\"MINUTE\", 60 * SECOND);\ndefine(\"HOUR\", 60 * MINUTE);\ndefine(\"DAY\", 24 * HOUR);\ndefine(\"MONTH\", 30 * DAY);\nfunction relativeTime($time)\n{ \n $delta = time() - $time;\n\n if ($delta < 1 * MINUTE)\n {\n return $delta == 1 ? \"one second ago\" : $delta . \" seconds ago\";\n }\n if ($delta < 2 * MINUTE)\n {\n return \"a minute ago\";\n }\n if ($delta < 45 * MINUTE)\n {\n return floor($delta / MINUTE) . \" minutes ago\";\n }\n if ($delta < 90 * MINUTE)\n {\n return \"an hour ago\";\n }\n if ($delta < 24 * HOUR)\n {\n return floor($delta / HOUR) . \" hours ago\";\n }\n if ($delta < 48 * HOUR)\n {\n return \"yesterday\";\n }\n if ($delta < 30 * DAY)\n {\n return floor($delta / DAY) . \" days ago\";\n }\n if ($delta < 12 * MONTH)\n {\n $months = floor($delta / DAY / 30);\n return $months <= 1 ? \"one month ago\" : $months . \" months ago\";\n }\n else\n {\n $years = floor($delta / DAY / 365);\n return $years <= 1 ? \"one year ago\" : $years . \" years ago\";\n }\n} \n" }, { "answer_id": 569913, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "java.util.Date import java.util.Date;\nimport javax.management.timer.Timer;\n\nString getRelativeDate(Date date) { \n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * Timer.ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta) + \" seconds ago\";\n }\n if (delta < 2L * Timer.ONE_MINUTE) {\n return \"a minute ago\";\n }\n if (delta < 45L * Timer.ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * Timer.ONE_MINUTE) {\n return \"an hour ago\";\n }\n if (delta < 24L * Timer.ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * Timer.ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * Timer.ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month\n long months = toMonths(delta); \n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n}\n\nprivate long toSeconds(long date) {\n return date / 1000L;\n}\n\nprivate long toMinutes(long date) {\n return toSeconds(date) / 60L;\n}\n\nprivate long toHours(long date) {\n return toMinutes(date) / 60L;\n}\n\nprivate long toDays(long date) {\n return toHours(date) / 24L;\n}\n\nprivate long toMonths(long date) {\n return toDays(date) / 30L;\n}\n\nprivate long toYears(long date) {\n return toMonths(date) / 365L;\n}\n" }, { "answer_id": 628203, "author": "neuracnu", "author_id": 19277, "author_profile": "https://Stackoverflow.com/users/19277", "pm_score": 6, "selected": false, "text": "using System.Text;\n\n/// <summary>\n/// Compares a supplied date to the current date and generates a friendly English \n/// comparison (\"5 days ago\", \"5 days from now\")\n/// </summary>\n/// <param name=\"date\">The date to convert</param>\n/// <param name=\"approximate\">When off, calculate timespan down to the second.\n/// When on, approximate to the largest round unit of time.</param>\n/// <returns></returns>\npublic static string ToRelativeDateString(this DateTime value, bool approximate)\n{\n StringBuilder sb = new StringBuilder();\n\n string suffix = (value > DateTime.Now) ? \" from now\" : \" ago\";\n\n TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks));\n\n if (timeSpan.Days > 0)\n {\n sb.AppendFormat(\"{0} {1}\", timeSpan.Days,\n (timeSpan.Days > 1) ? \"days\" : \"day\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Hours > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty,\n timeSpan.Hours, (timeSpan.Hours > 1) ? \"hours\" : \"hour\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Minutes > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Minutes, (timeSpan.Minutes > 1) ? \"minutes\" : \"minute\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (timeSpan.Seconds > 0)\n {\n sb.AppendFormat(\"{0}{1} {2}\", (sb.Length > 0) ? \", \" : string.Empty, \n timeSpan.Seconds, (timeSpan.Seconds > 1) ? \"seconds\" : \"second\");\n if (approximate) return sb.ToString() + suffix;\n }\n if (sb.Length == 0) return \"right now\";\n\n sb.Append(suffix);\n return sb.ToString();\n}\n" }, { "answer_id": 1141237, "author": "Chris Charabaruk", "author_id": 5697, "author_profile": "https://Stackoverflow.com/users/5697", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic static class RelativeDateHelper\n{\n private static Dictionary<double, Func<double, string>> sm_Dict = null;\n\n private static Dictionary<double, Func<double, string>> DictionarySetup()\n {\n var dict = new Dictionary<double, Func<double, string>>();\n dict.Add(0.75, (mins) => \"less than a minute\");\n dict.Add(1.5, (mins) => \"about a minute\");\n dict.Add(45, (mins) => string.Format(\"{0} minutes\", Math.Round(mins)));\n dict.Add(90, (mins) => \"about an hour\");\n dict.Add(1440, (mins) => string.Format(\"about {0} hours\", Math.Round(Math.Abs(mins / 60)))); // 60 * 24\n dict.Add(2880, (mins) => \"a day\"); // 60 * 48\n dict.Add(43200, (mins) => string.Format(\"{0} days\", Math.Floor(Math.Abs(mins / 1440)))); // 60 * 24 * 30\n dict.Add(86400, (mins) => \"about a month\"); // 60 * 24 * 60\n dict.Add(525600, (mins) => string.Format(\"{0} months\", Math.Floor(Math.Abs(mins / 43200)))); // 60 * 24 * 365 \n dict.Add(1051200, (mins) => \"about a year\"); // 60 * 24 * 365 * 2\n dict.Add(double.MaxValue, (mins) => string.Format(\"{0} years\", Math.Floor(Math.Abs(mins / 525600))));\n\n return dict;\n }\n\n public static string ToRelativeDate(this DateTime input)\n {\n TimeSpan oSpan = DateTime.Now.Subtract(input);\n double TotalMinutes = oSpan.TotalMinutes;\n string Suffix = \" ago\";\n\n if (TotalMinutes < 0.0)\n {\n TotalMinutes = Math.Abs(TotalMinutes);\n Suffix = \" from now\";\n }\n\n if (null == sm_Dict)\n sm_Dict = DictionarySetup();\n\n return sm_Dict.First(n => TotalMinutes < n.Key).Value.Invoke(TotalMinutes) + Suffix;\n }\n}\n" }, { "answer_id": 1379178, "author": "Simon", "author_id": 53158, "author_profile": "https://Stackoverflow.com/users/53158", "pm_score": 4, "selected": false, "text": "var dateTime1 = 2.Hours().Ago();\nvar dateTime2 = 3.Days().Ago();\nvar dateTime3 = 1.Months().Ago();\nvar dateTime4 = 5.Hours().FromNow();\nvar dateTime5 = 2.Weeks().FromNow();\nvar dateTime6 = 40.Seconds().FromNow();\n" }, { "answer_id": 1735172, "author": "antony.trupe", "author_id": 5849, "author_profile": "https://Stackoverflow.com/users/5849", "pm_score": 3, "selected": false, "text": "import java.util.Date;\n\npublic class RelativeDateFormat {\n\n private static final long ONE_MINUTE = 60000L;\n private static final long ONE_HOUR = 3600000L;\n private static final long ONE_DAY = 86400000L;\n private static final long ONE_WEEK = 604800000L;\n\n public static String format(Date date) {\n\n long delta = new Date().getTime() - date.getTime();\n if (delta < 1L * ONE_MINUTE) {\n return toSeconds(delta) == 1 ? \"one second ago\" : toSeconds(delta)\n + \" seconds ago\";\n }\n if (delta < 2L * ONE_MINUTE) {\n return \"one minute ago\";\n }\n if (delta < 45L * ONE_MINUTE) {\n return toMinutes(delta) + \" minutes ago\";\n }\n if (delta < 90L * ONE_MINUTE) {\n return \"one hour ago\";\n }\n if (delta < 24L * ONE_HOUR) {\n return toHours(delta) + \" hours ago\";\n }\n if (delta < 48L * ONE_HOUR) {\n return \"yesterday\";\n }\n if (delta < 30L * ONE_DAY) {\n return toDays(delta) + \" days ago\";\n }\n if (delta < 12L * 4L * ONE_WEEK) {\n long months = toMonths(delta);\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n } else {\n long years = toYears(delta);\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n\n private static long toSeconds(long date) {\n return date / 1000L;\n }\n\n private static long toMinutes(long date) {\n return toSeconds(date) / 60L;\n }\n\n private static long toHours(long date) {\n return toMinutes(date) / 60L;\n }\n\n private static long toDays(long date) {\n return toHours(date) / 24L;\n }\n\n private static long toMonths(long date) {\n return toDays(date) / 30L;\n }\n\n private static long toYears(long date) {\n return toMonths(date) / 365L;\n }\n\n}\n" }, { "answer_id": 2179589, "author": "Buhake Sindi", "author_id": 251173, "author_profile": "https://Stackoverflow.com/users/251173", "pm_score": 3, "selected": false, "text": "function posted(t) {\n var now = new Date();\n var diff = parseInt((now.getTime() - Date.parse(t)) / 1000);\n if (diff < 60) { return 'less than a minute ago'; }\n else if (diff < 120) { return 'about a minute ago'; }\n else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; }\n else if (diff < (5400)) { return 'about an hour ago'; }\n else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; }\n else if (diff < (172800)) { return '1 day ago'; } \n else {return (parseInt(diff / 86400)).toString() + ' days ago'; }\n}\n" }, { "answer_id": 2244324, "author": "0llie", "author_id": 229906, "author_profile": "https://Stackoverflow.com/users/229906", "pm_score": 4, "selected": false, "text": "+ (NSString *)timeAgoString:(NSDate *)date {\n int delta = -(int)[date timeIntervalSinceNow];\n\n if (delta < 60)\n {\n return delta == 1 ? @\"one second ago\" : [NSString stringWithFormat:@\"%i seconds ago\", delta];\n }\n if (delta < 120)\n {\n return @\"a minute ago\";\n }\n if (delta < 2700)\n {\n return [NSString stringWithFormat:@\"%i minutes ago\", delta/60];\n }\n if (delta < 5400)\n {\n return @\"an hour ago\";\n }\n if (delta < 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i hours ago\", delta/3600];\n }\n if (delta < 48 * 3600)\n {\n return @\"yesterday\";\n }\n if (delta < 30 * 24 * 3600)\n {\n return [NSString stringWithFormat:@\"%i days ago\", delta/(24*3600)];\n }\n if (delta < 12 * 30 * 24 * 3600)\n {\n int months = delta/(30*24*3600);\n return months <= 1 ? @\"one month ago\" : [NSString stringWithFormat:@\"%i months ago\", months];\n }\n else\n {\n int years = delta/(12*30*24*3600);\n return years <= 1 ? @\"one year ago\" : [NSString stringWithFormat:@\"%i years ago\", years];\n }\n}\n" }, { "answer_id": 5427203, "author": "Town", "author_id": 54975, "author_profile": "https://Stackoverflow.com/users/54975", "pm_score": 5, "selected": false, "text": "public static class DateTimeHelper\n {\n private const int SECOND = 1;\n private const int MINUTE = 60 * SECOND;\n private const int HOUR = 60 * MINUTE;\n private const int DAY = 24 * HOUR;\n private const int MONTH = 30 * DAY;\n\n /// <summary>\n /// Returns a friendly version of the provided DateTime, relative to now. E.g.: \"2 days ago\", or \"in 6 months\".\n /// </summary>\n /// <param name=\"dateTime\">The DateTime to compare to Now</param>\n /// <returns>A friendly string</returns>\n public static string GetFriendlyRelativeTime(DateTime dateTime)\n {\n if (DateTime.UtcNow.Ticks == dateTime.Ticks)\n {\n return \"Right now!\";\n }\n\n bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks);\n var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks);\n\n double delta = ts.TotalSeconds;\n\n if (delta < 1 * MINUTE)\n {\n return isFuture ? \"in \" + (ts.Seconds == 1 ? \"one second\" : ts.Seconds + \" seconds\") : ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n }\n if (delta < 2 * MINUTE)\n {\n return isFuture ? \"in a minute\" : \"a minute ago\";\n }\n if (delta < 45 * MINUTE)\n {\n return isFuture ? \"in \" + ts.Minutes + \" minutes\" : ts.Minutes + \" minutes ago\";\n }\n if (delta < 90 * MINUTE)\n {\n return isFuture ? \"in an hour\" : \"an hour ago\";\n }\n if (delta < 24 * HOUR)\n {\n return isFuture ? \"in \" + ts.Hours + \" hours\" : ts.Hours + \" hours ago\";\n }\n if (delta < 48 * HOUR)\n {\n return isFuture ? \"tomorrow\" : \"yesterday\";\n }\n if (delta < 30 * DAY)\n {\n return isFuture ? \"in \" + ts.Days + \" days\" : ts.Days + \" days ago\";\n }\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return isFuture ? \"in \" + (months <= 1 ? \"one month\" : months + \" months\") : months <= 1 ? \"one month ago\" : months + \" months ago\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return isFuture ? \"in \" + (years <= 1 ? \"one year\" : years + \" years\") : years <= 1 ? \"one year ago\" : years + \" years ago\";\n }\n }\n }\n" }, { "answer_id": 5835905, "author": "Owen Blacker", "author_id": 205245, "author_profile": "https://Stackoverflow.com/users/205245", "pm_score": 4, "selected": false, "text": "Grammar FuzzyDateExtensions public class Grammar\n{\n /// <summary> Gets or sets the term for \"just now\". </summary>\n public string JustNow { get; set; }\n /// <summary> Gets or sets the term for \"X minutes ago\". </summary>\n /// <remarks>\n /// This is a <see cref=\"String.Format\"/> pattern, where <c>{0}</c>\n /// is the number of minutes.\n /// </remarks>\n public string MinutesAgo { get; set; }\n public string OneHourAgo { get; set; }\n public string HoursAgo { get; set; }\n public string Yesterday { get; set; }\n public string DaysAgo { get; set; }\n public string LastMonth { get; set; }\n public string MonthsAgo { get; set; }\n public string LastYear { get; set; }\n public string YearsAgo { get; set; }\n /// <summary> Gets or sets the term for \"ages ago\". </summary>\n public string AgesAgo { get; set; }\n\n /// <summary>\n /// Gets or sets the threshold beyond which the fuzzy date should be\n /// considered \"ages ago\".\n /// </summary>\n public TimeSpan AgesAgoThreshold { get; set; }\n\n /// <summary>\n /// Initialises a new <see cref=\"Grammar\"/> instance with the\n /// specified properties.\n /// </summary>\n private void Initialise(string justNow, string minutesAgo,\n string oneHourAgo, string hoursAgo, string yesterday, string daysAgo,\n string lastMonth, string monthsAgo, string lastYear, string yearsAgo,\n string agesAgo, TimeSpan agesAgoThreshold)\n { ... }\n}\n FuzzyDateString public static class FuzzyDateExtensions\n{\n public static string ToFuzzyDateString(this TimeSpan timespan)\n {\n return timespan.ToFuzzyDateString(new Grammar());\n }\n\n public static string ToFuzzyDateString(this TimeSpan timespan,\n Grammar grammar)\n {\n return GetFuzzyDateString(timespan, grammar);\n }\n\n public static string ToFuzzyDateString(this DateTime datetime)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString();\n }\n\n public static string ToFuzzyDateString(this DateTime datetime,\n Grammar grammar)\n {\n return (DateTime.Now - datetime).ToFuzzyDateString(grammar);\n }\n\n\n private static string GetFuzzyDateString(TimeSpan timespan,\n Grammar grammar)\n {\n timespan = timespan.Duration();\n\n if (timespan >= grammar.AgesAgoThreshold)\n {\n return grammar.AgesAgo;\n }\n\n if (timespan < new TimeSpan(0, 2, 0)) // 2 minutes\n {\n return grammar.JustNow;\n }\n\n if (timespan < new TimeSpan(1, 0, 0)) // 1 hour\n {\n return String.Format(grammar.MinutesAgo, timespan.Minutes);\n }\n\n if (timespan < new TimeSpan(1, 55, 0)) // 1 hour 55 minutes\n {\n return grammar.OneHourAgo;\n }\n\n if (timespan < new TimeSpan(12, 0, 0) // 12 hours\n && (DateTime.Now - timespan).IsToday())\n {\n return String.Format(grammar.HoursAgo, timespan.RoundedHours());\n }\n\n if ((DateTime.Now.AddDays(1) - timespan).IsToday())\n {\n return grammar.Yesterday;\n }\n\n if (timespan < new TimeSpan(32, 0, 0, 0) // 32 days\n && (DateTime.Now - timespan).IsThisMonth())\n {\n return String.Format(grammar.DaysAgo, timespan.RoundedDays());\n }\n\n if ((DateTime.Now.AddMonths(1) - timespan).IsThisMonth())\n {\n return grammar.LastMonth;\n }\n\n if (timespan < new TimeSpan(365, 0, 0, 0, 0) // 365 days\n && (DateTime.Now - timespan).IsThisYear())\n {\n return String.Format(grammar.MonthsAgo, timespan.RoundedMonths());\n }\n\n if ((DateTime.Now - timespan).AddYears(1).IsThisYear())\n {\n return grammar.LastYear;\n }\n\n return String.Format(grammar.YearsAgo, timespan.RoundedYears());\n }\n}\n IsToday IsThisMonth IsThisYear public static bool IsToday(this DateTime date)\n{\n return date.DayOfYear == DateTime.Now.DayOfYear && date.IsThisYear();\n}\n RoundedMonths public static int RoundedDays(this TimeSpan timespan)\n{\n return (timespan.Hours > 12) ? timespan.Days + 1 : timespan.Days;\n}\n\npublic static int RoundedMonths(this TimeSpan timespan)\n{\n DateTime then = DateTime.Now - timespan;\n\n // Number of partial months elapsed since 1 Jan, AD 1 (DateTime.MinValue)\n int nowMonthYears = DateTime.Now.Year * 12 + DateTime.Now.Month;\n int thenMonthYears = then.Year * 12 + then.Month; \n\n return nowMonthYears - thenMonthYears;\n}\n" }, { "answer_id": 10775917, "author": "JoeyFur62", "author_id": 1420406, "author_profile": "https://Stackoverflow.com/users/1420406", "pm_score": 3, "selected": false, "text": "var ts = new TimeSpan(DateTime.Now.Ticks - dt.Ticks);\n" }, { "answer_id": 12406029, "author": "tugberk", "author_id": 463785, "author_profile": "https://Stackoverflow.com/users/463785", "pm_score": 3, "selected": false, "text": "Int32 public static class TimeSpanExtensions {\n\n public static TimeSpan Days(this int value) {\n\n return new TimeSpan(value, 0, 0, 0);\n }\n\n public static TimeSpan Hours(this int value) {\n\n return new TimeSpan(0, value, 0, 0);\n }\n\n public static TimeSpan Minutes(this int value) {\n\n return new TimeSpan(0, 0, value, 0);\n }\n\n public static TimeSpan Seconds(this int value) {\n\n return new TimeSpan(0, 0, 0, value);\n }\n\n public static TimeSpan Milliseconds(this int value) {\n\n return new TimeSpan(0, 0, 0, 0, value);\n }\n\n public static DateTime Ago(this TimeSpan value) {\n\n return DateTime.Now - value;\n }\n}\n DateTime public static class DateTimeExtensions {\n\n public static DateTime Ago(this DateTime dateTime, TimeSpan delta) {\n\n return dateTime - delta;\n }\n}\n var date = DateTime.Now;\ndate.Ago(2.Days()); // 2 days ago\ndate.Ago(7.Hours()); // 7 hours ago\ndate.Ago(567.Milliseconds()); // 567 milliseconds ago\n" }, { "answer_id": 15446338, "author": "Prashant Gupta", "author_id": 985335, "author_profile": "https://Stackoverflow.com/users/985335", "pm_score": 3, "selected": false, "text": "public string RelativeDateTimeCount(DateTime inputDateTime)\n{\n string outputDateTime = string.Empty;\n TimeSpan ts = DateTime.Now - inputDateTime;\n\n if (ts.Days > 7)\n { outputDateTime = inputDateTime.ToString(\"MMMM d, yyyy\"); }\n\n else if (ts.Days > 0)\n {\n outputDateTime = ts.Days == 1 ? (\"about 1 Day ago\") : (\"about \" + ts.Days.ToString() + \" Days ago\");\n }\n else if (ts.Hours > 0)\n {\n outputDateTime = ts.Hours == 1 ? (\"an hour ago\") : (ts.Hours.ToString() + \" hours ago\");\n }\n else if (ts.Minutes > 0)\n {\n outputDateTime = ts.Minutes == 1 ? (\"1 minute ago\") : (ts.Minutes.ToString() + \" minutes ago\");\n }\n else outputDateTime = \"few seconds ago\";\n\n return outputDateTime;\n}\n" }, { "answer_id": 18074585, "author": "string.Empty", "author_id": 2027232, "author_profile": "https://Stackoverflow.com/users/2027232", "pm_score": 2, "selected": false, "text": "public string getRelativeDateTime(DateTime date)\n{\n TimeSpan ts = DateTime.Now - date;\n if (ts.TotalMinutes < 1)//seconds ago\n return \"just now\";\n if (ts.TotalHours < 1)//min ago\n return (int)ts.TotalMinutes == 1 ? \"1 Minute ago\" : (int)ts.TotalMinutes + \" Minutes ago\";\n if (ts.TotalDays < 1)//hours ago\n return (int)ts.TotalHours == 1 ? \"1 Hour ago\" : (int)ts.TotalHours + \" Hours ago\";\n if (ts.TotalDays < 7)//days ago\n return (int)ts.TotalDays == 1 ? \"1 Day ago\" : (int)ts.TotalDays + \" Days ago\";\n if (ts.TotalDays < 30.4368)//weeks ago\n return (int)(ts.TotalDays / 7) == 1 ? \"1 Week ago\" : (int)(ts.TotalDays / 7) + \" Weeks ago\";\n if (ts.TotalDays < 365.242)//months ago\n return (int)(ts.TotalDays / 30.4368) == 1 ? \"1 Month ago\" : (int)(ts.TotalDays / 30.4368) + \" Months ago\";\n //years ago\n return (int)(ts.TotalDays / 365.242) == 1 ? \"1 Year ago\" : (int)(ts.TotalDays / 365.242) + \" Years ago\";\n}\n" }, { "answer_id": 19377828, "author": "Premdeep Mohanty", "author_id": 2749766, "author_profile": "https://Stackoverflow.com/users/2749766", "pm_score": 4, "selected": false, "text": "long delta = new Date().getTime() - date.getTime();\nconst int SECOND = 1;\nconst int MINUTE = 60 * SECOND;\nconst int HOUR = 60 * MINUTE;\nconst int DAY = 24 * HOUR;\nconst int MONTH = 30 * DAY;\n\nif (delta < 0L)\n{\n return \"not yet\";\n}\nif (delta < 1L * MINUTE)\n{\n return ts.Seconds == 1 ? \"one second ago\" : ts.Seconds + \" seconds ago\";\n}\nif (delta < 2L * MINUTE)\n{\n return \"a minute ago\";\n}\nif (delta < 45L * MINUTE)\n{\n return ts.Minutes + \" minutes ago\";\n}\nif (delta < 90L * MINUTE)\n{\n return \"an hour ago\";\n}\nif (delta < 24L * HOUR)\n{\n return ts.Hours + \" hours ago\";\n}\nif (delta < 48L * HOUR)\n{\n return \"yesterday\";\n}\nif (delta < 30L * DAY)\n{\n return ts.Days + \" days ago\";\n}\nif (delta < 12L * MONTH)\n{\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months <= 1 ? \"one month ago\" : months + \" months ago\";\n}\nelse\n{\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years <= 1 ? \"one year ago\" : years + \" years ago\";\n}\n" }, { "answer_id": 22961626, "author": "Karl-Henrik", "author_id": 1770846, "author_profile": "https://Stackoverflow.com/users/1770846", "pm_score": 6, "selected": false, "text": "DateTime.UtcNow.AddHours(-30).Humanize() => \"yesterday\"\nDateTime.UtcNow.AddHours(-2).Humanize() => \"2 hours ago\"\n\nDateTime.UtcNow.AddHours(30).Humanize() => \"tomorrow\"\nDateTime.UtcNow.AddHours(2).Humanize() => \"2 hours from now\"\n\nTimeSpan.FromMilliseconds(1299630020).Humanize() => \"2 weeks\"\nTimeSpan.FromMilliseconds(1299630020).Humanize(3) => \"2 weeks, 1 day, 1 hour\"\n" }, { "answer_id": 25677278, "author": "Wai Ho Leung", "author_id": 1418148, "author_profile": "https://Stackoverflow.com/users/1418148", "pm_score": 2, "selected": false, "text": "/** \n * {@code date1} has to be earlier than {@code date2}.\n */\npublic static String relativize(Date date1, Date date2) {\n assert date2.getTime() >= date1.getTime();\n\n long duration = date2.getTime() - date1.getTime();\n long converted;\n\n if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"day\" : \"days\");\n } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"hour\" : \"hours\");\n } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"minute\" : \"minutes\");\n } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) {\n return String.format(\"%d %s ago\", converted, converted == 1 ? \"second\" : \"seconds\");\n } else {\n return \"just now\";\n }\n}\n" }, { "answer_id": 32459883, "author": "Bgl86", "author_id": 5293002, "author_profile": "https://Stackoverflow.com/users/5293002", "pm_score": 3, "selected": false, "text": "\"2 days, 4 hours and 12 minutes ago\" TimeSpan timeDiff = DateTime.Now-CreatedDate;\n timeDiff.Days\ntimeDiff.Hours\n" }, { "answer_id": 32459892, "author": "Piotr Stapp", "author_id": 1749895, "author_profile": "https://Stackoverflow.com/users/1749895", "pm_score": 4, "selected": false, "text": "public static string TimeAgo(this DateTime dateTime)\n{\n string result = string.Empty;\n var timeSpan = DateTime.Now.Subtract(dateTime);\n \n if (timeSpan <= TimeSpan.FromSeconds(60))\n {\n result = string.Format(\"{0} seconds ago\", timeSpan.Seconds);\n }\n else if (timeSpan <= TimeSpan.FromMinutes(60))\n {\n result = timeSpan.Minutes > 1 ? \n String.Format(\"about {0} minutes ago\", timeSpan.Minutes) :\n \"about a minute ago\";\n }\n else if (timeSpan <= TimeSpan.FromHours(24))\n {\n result = timeSpan.Hours > 1 ? \n String.Format(\"about {0} hours ago\", timeSpan.Hours) : \n \"about an hour ago\";\n }\n else if (timeSpan <= TimeSpan.FromDays(30))\n {\n result = timeSpan.Days > 1 ? \n String.Format(\"about {0} days ago\", timeSpan.Days) : \n \"yesterday\";\n }\n else if (timeSpan <= TimeSpan.FromDays(365))\n {\n result = timeSpan.Days > 30 ? \n String.Format(\"about {0} months ago\", timeSpan.Days / 30) : \n \"about a month ago\";\n }\n else\n {\n result = timeSpan.Days > 365 ? \n String.Format(\"about {0} years ago\", timeSpan.Days / 365) : \n \"about a year ago\";\n }\n \n return result;\n}\n" }, { "answer_id": 46029235, "author": "VnDevil", "author_id": 1326699, "author_profile": "https://Stackoverflow.com/users/1326699", "pm_score": 1, "selected": false, "text": "public static string RelativeDate(DateTime theDate)\n{\n var span = DateTime.Now - theDate;\n if (span.Days > 365)\n {\n var years = (span.Days / 365);\n if (span.Days % 365 != 0)\n years += 1;\n return $\"about {years} {(years == 1 ? \"year\" : \"years\")} ago\";\n }\n if (span.Days > 30)\n {\n var months = (span.Days / 30);\n if (span.Days % 31 != 0)\n months += 1;\n return $\"about {months} {(months == 1 ? \"month\" : \"months\")} ago\";\n }\n if (span.Days > 0)\n return $\"about {span.Days} {(span.Days == 1 ? \"day\" : \"days\")} ago\";\n if (span.Hours > 0)\n return $\"about {span.Hours} {(span.Hours == 1 ? \"hour\" : \"hours\")} ago\";\n if (span.Minutes > 0)\n return $\"about {span.Minutes} {(span.Minutes == 1 ? \"minute\" : \"minutes\")} ago\";\n if (span.Seconds > 5)\n return $\"about {span.Seconds} seconds ago\";\n\n return span.Seconds <= 5 ? \"about 5 seconds ago\" : string.Empty;\n}\n" }, { "answer_id": 49300196, "author": "Beingnin", "author_id": 7441056, "author_profile": "https://Stackoverflow.com/users/7441056", "pm_score": -1, "selected": false, "text": " public static string TimeLeft(DateTime utcDate)\n {\n TimeSpan timeLeft = DateTime.UtcNow - utcDate;\n string timeLeftString = \"\";\n if (timeLeft.Days > 0)\n {\n timeLeftString += timeLeft.Days == 1 ? timeLeft.Days + \" day\" : timeLeft.Days + \" days\";\n }\n else if (timeLeft.Hours > 0)\n {\n timeLeftString += timeLeft.Hours == 1 ? timeLeft.Hours + \" hour\" : timeLeft.Hours + \" hours\";\n }\n else\n {\n timeLeftString += timeLeft.Minutes == 1 ? timeLeft.Minutes+\" minute\" : timeLeft.Minutes + \" minutes\";\n }\n return timeLeftString;\n }\n" }, { "answer_id": 54018412, "author": "boyukbas", "author_id": 1051784, "author_profile": "https://Stackoverflow.com/users/1051784", "pm_score": 2, "selected": false, "text": " const int SECOND = 1;\n const int MINUTE = 60 * SECOND;\n const int HOUR = 60 * MINUTE;\n const int DAY = 24 * HOUR;\n const int MONTH = 30 * DAY;\n\n var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks);\n double delta = Math.Abs(ts.TotalSeconds);\n\n if (delta < 1 * MINUTE)\n return ts.Seconds + \" saniye önce\";\n\n if (delta < 45 * MINUTE)\n return ts.Minutes + \" dakika önce\";\n\n if (delta < 24 * HOUR)\n return ts.Hours + \" saat önce\";\n\n if (delta < 48 * HOUR)\n return \"dün\";\n\n if (delta < 30 * DAY)\n return ts.Days + \" gün önce\";\n\n if (delta < 12 * MONTH)\n {\n int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30));\n return months + \" ay önce\";\n }\n else\n {\n int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365));\n return years + \" yıl önce\";\n }\n" }, { "answer_id": 56310196, "author": "Ahmed Osama", "author_id": 5514131, "author_profile": "https://Stackoverflow.com/users/5514131", "pm_score": 2, "selected": false, "text": "// Calculate total days in current year\nint daysInYear;\n\nfor (var i = 1; i <= 12; i++)\n daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i);\n\n// Past date\nDateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582));\n\n// Calculate difference between current date and past date\ndouble diff = (DateTime.Now - dateToCompare).TotalMilliseconds;\n\nTimeSpan ts = TimeSpan.FromMilliseconds(diff);\n\nvar years = ts.TotalDays / daysInYear; // Years\nvar months = ts.TotalDays / (daysInYear / (double)12); // Months\nvar weeks = ts.TotalDays / 7; // Weeks\nvar days = ts.TotalDays; // Days\nvar hours = ts.TotalHours; // Hours\nvar minutes = ts.TotalMinutes; // Minutes\nvar seconds = ts.TotalSeconds; // Seconds\n\nif (years >= 1)\n Console.WriteLine(Math.Round(years, 0) + \" year(s) ago\");\nelse if (months >= 1)\n Console.WriteLine(Math.Round(months, 0) + \" month(s) ago\");\nelse if (weeks >= 1)\n Console.WriteLine(Math.Round(weeks, 0) + \" week(s) ago\");\nelse if (days >= 1)\n Console.WriteLine(Math.Round(days, 0) + \" days(s) ago\");\nelse if (hours >= 1)\n Console.WriteLine(Math.Round(hours, 0) + \" hour(s) ago\");\nelse if (minutes >= 1)\n Console.WriteLine(Math.Round(minutes, 0) + \" minute(s) ago\");\nelse if (seconds >= 1)\n Console.WriteLine(Math.Round(seconds, 0) + \" second(s) ago\");\n\nConsole.ReadLine();\n" }, { "answer_id": 64329743, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DateTime using System;\n\npublic class Program {\n public static string getRelativeTime(DateTime past) {\n DateTime now = DateTime.Today;\n string rt = \"\";\n int time;\n string statement = \"\";\n if (past.Second >= now.Second) {\n if (past.Second - now.Second == 1) {\n rt = \"second ago\";\n }\n rt = \"seconds ago\";\n time = past.Second - now.Second;\n statement = \"\" + time;\n return (statement + rt);\n }\n if (past.Minute >= now.Minute) {\n if (past.Second - now.Second == 1) {\n rt = \"second ago\";\n } else {\n rt = \"minutes ago\";\n }\n time = past.Minute - now.Minute;\n statement = \"\" + time;\n return (statement + rt);\n }\n // This process will go on until years\n }\n public static void Main() {\n DateTime before = new DateTime(1995, 8, 24);\n string date = getRelativeTime(before);\n Console.WriteLine(\"Windows 95 was {0}.\", date);\n }\n}\n" }, { "answer_id": 65238004, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "TimeSpan timeSpan = DateTime.Now - new DateTime(1234, 5, 6, 7, 8, 9);\n\n(string unit, int value) = new Dictionary<string, int>\n{\n {\"year(s)\", (int)(timeSpan.TotalDays / 365.25)}, //https://en.wikipedia.org/wiki/Year#Intercalation\n {\"month(s)\", (int)(timeSpan.TotalDays / 29.53)}, //https://en.wikipedia.org/wiki/Month\n {\"day(s)\", (int)timeSpan.TotalDays},\n {\"hour(s)\", (int)timeSpan.TotalHours},\n {\"minute(s)\", (int)timeSpan.TotalMinutes},\n {\"second(s)\", (int)timeSpan.TotalSeconds},\n {\"millisecond(s)\", (int)timeSpan.TotalMilliseconds}\n}.First(kvp => kvp.Value > 0);\n\nConsole.WriteLine($\"{value} {unit} ago\");\n 786 year(s) ago TimeSpan timeSpan = DateTime.Now - new DateTime(2020, 12, 6, 7, 8, 9);\n 4 day(s) ago TimeSpan timeSpan = DateTime.Now - DateTime.Now.Date;\n 9 hour(s) ago" }, { "answer_id": 69020909, "author": "Shujat Munawar", "author_id": 7849868, "author_profile": "https://Stackoverflow.com/users/7849868", "pm_score": -1, "selected": false, "text": " public string GetTimeSince(DateTime postDate)\n {\n string message = \"\";\n DateTime currentDate = DateTime.Now;\n TimeSpan timegap = currentDate - postDate;\n\n \n if (timegap.Days > 365)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Years\"), (((timegap.Days) / 30) / 12)); \n }\n else if (timegap.Days > 30)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Months\"), timegap.Days/30); \n }\n else if (timegap.Days > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Days\"), timegap.Days);\n } \n else if (timegap.Hours > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Hours\"), timegap.Hours);\n } \n else if (timegap.Minutes > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Minutes\"), timegap.Minutes);\n }\n else if (timegap.Seconds > 0)\n {\n message = string.Format(L(\"Ago\") + \" {0} \" + L(\"Seconds\"), timegap.Seconds);\n }\n\n // let's handle future times..just in case \n else if (timegap.Days < -365)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Years\"), (((Math.Abs(timegap.Days)) / 30) / 12)); \n }\n else if (timegap.Days < -30)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Months\"), ((Math.Abs(timegap.Days)) / 30)); \n }\n else if (timegap.Days < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Days\"), Math.Abs(timegap.Days)); \n } \n \n else if (timegap.Hours < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Hours\"), Math.Abs(timegap.Hours)); \n }\n else if (timegap.Minutes < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Minutes\"), Math.Abs(timegap.Minutes)); \n }\n else if (timegap.Seconds < 0)\n {\n message = string.Format(L(\"In\") + \" {0} \" + L(\"Seconds\"), Math.Abs(timegap.Seconds)); \n }\n\n\n else\n {\n message = \"a bit\";\n }\n\n return message;\n }\n" }, { "answer_id": 73608368, "author": "StudioLE", "author_id": 247218, "author_profile": "https://Stackoverflow.com/users/247218", "pm_score": 0, "selected": false, "text": "TimeSpan.TicksPerSecond /// <summary>\n/// Convert a <see cref=\"TimeSpan\"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// TimeSpan.FromSeconds(10).ToNaturalLanguage();\n/// // 10 seconds\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this TimeSpan @this)\n{\n const int daysInWeek = 7;\n const int daysInMonth = 30;\n const int daysInYear = 365;\n const long threshold = 100 * TimeSpan.TicksPerMillisecond;\n @this = @this.TotalSeconds < 0\n ? TimeSpan.FromSeconds(@this.TotalSeconds * -1)\n : @this;\n return (@this.Ticks + threshold) switch\n {\n < 2 * TimeSpan.TicksPerSecond => \"a second\",\n < 1 * TimeSpan.TicksPerMinute => @this.Seconds + \" seconds\",\n < 2 * TimeSpan.TicksPerMinute => \"a minute\",\n < 1 * TimeSpan.TicksPerHour => @this.Minutes + \" minutes\",\n < 2 * TimeSpan.TicksPerHour => \"an hour\",\n < 1 * TimeSpan.TicksPerDay => @this.Hours + \" hours\",\n < 2 * TimeSpan.TicksPerDay => \"a day\",\n < 1 * daysInWeek * TimeSpan.TicksPerDay => @this.Days + \" days\",\n < 2 * daysInWeek * TimeSpan.TicksPerDay => \"a week\",\n < 1 * daysInMonth * TimeSpan.TicksPerDay => (@this.Days / daysInWeek).ToString(\"F0\") + \" weeks\",\n < 2 * daysInMonth * TimeSpan.TicksPerDay => \"a month\",\n < 1 * daysInYear * TimeSpan.TicksPerDay => (@this.Days / daysInMonth).ToString(\"F0\") + \" months\",\n < 2 * daysInYear * TimeSpan.TicksPerDay => \"a year\",\n _ => (@this.Days / daysInYear).ToString(\"F0\") + \" years\"\n };\n}\n\n/// <summary>\n/// Convert a <see cref=\"DateTime\"/> to a natural language representation.\n/// </summary>\n/// <example>\n/// <code>\n/// (DateTime.Now - TimeSpan.FromSeconds(10)).ToNaturalLanguage()\n/// // 10 seconds ago\n/// </code>\n/// </example>\npublic static string ToNaturalLanguage(this DateTime @this)\n{\n TimeSpan timeSpan = @this - DateTime.Now;\n return timeSpan.TotalSeconds switch\n {\n >= 1 => timeSpan.ToNaturalLanguage() + \" until\",\n <= -1 => timeSpan.ToNaturalLanguage() + \" ago\",\n _ => \"now\",\n };\n}\n [TestCase(\"a second\", 0)]\n[TestCase(\"a second\", 1)]\n[TestCase(\"2 seconds\", 2)]\n[TestCase(\"a minute\", 0, 1)]\n[TestCase(\"5 minutes\", 0, 5)]\n[TestCase(\"an hour\", 0, 0, 1)]\n[TestCase(\"2 hours\", 0, 0, 2)]\n[TestCase(\"a day\", 0, 0, 24)]\n[TestCase(\"a day\", 0, 0, 0, 1)]\n[TestCase(\"6 days\", 0, 0, 0, 6)]\n[TestCase(\"a week\", 0, 0, 0, 7)]\n[TestCase(\"4 weeks\", 0, 0, 0, 29)]\n[TestCase(\"a month\", 0, 0, 0, 30)]\n[TestCase(\"6 months\", 0, 0, 0, 6 * 30)]\n[TestCase(\"a year\", 0, 0, 0, 365)]\n[TestCase(\"68 years\", int.MaxValue)]\npublic void NaturalLanguageHelpers_TimeSpan(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n\n // Act\n string result = timeSpan.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n\n[TestCase(\"now\", 0)]\n[TestCase(\"10 minutes ago\", 0, -10)]\n[TestCase(\"10 minutes until\", 10, 10)]\n[TestCase(\"68 years until\", int.MaxValue)]\n[TestCase(\"68 years ago\", int.MinValue)]\npublic void NaturalLanguageHelpers_DateTime(\n string expected,\n int seconds,\n int minutes = 0,\n int hours = 0,\n int days = 0\n)\n{\n // Arrange\n TimeSpan timeSpan = new(days, hours, minutes, seconds);\n DateTime now = DateTime.Now;\n DateTime dateTime = now + timeSpan;\n\n // Act\n string result = dateTime.ToNaturalLanguage();\n\n // Assert\n Assert.That(result, Is.EqualTo(expected));\n}\n" } ]
2008/07/31
[ "https://Stackoverflow.com/questions/11", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1/" ]
13
<p>Is there a standard way for a web server to be able to determine a user's timezone within a web page? </p> <p>Perhaps from an HTTP header or part of the <code>user-agent</code> string?</p>
[ { "answer_id": 817, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": false, "text": "visitortime.getTimezoneOffset()\n maxmind" }, { "answer_id": 1809974, "author": "JD Isaacks", "author_id": 46011, "author_profile": "https://Stackoverflow.com/users/46011", "pm_score": 8, "selected": false, "text": "-new Date().getTimezoneOffset()/60;\n getTimezoneOffset()" }, { "answer_id": 2901216, "author": "Alek Davis", "author_id": 52545, "author_profile": "https://Stackoverflow.com/users/52545", "pm_score": 4, "selected": false, "text": "getTimezoneOffset" }, { "answer_id": 3724089, "author": "Sanjay Khatri", "author_id": 1026244, "author_profile": "https://Stackoverflow.com/users/1026244", "pm_score": 5, "selected": false, "text": "date date_default_timezone_set <?php\n #http://www.php.net/manual/en/timezones.php List of Time Zones\n function showclienttime()\n {\n if(!isset($_COOKIE['GMT_bias']))\n {\n?>\n\n <script type=\"text/javascript\">\n var Cookies = {};\n Cookies.create = function (name, value, days) {\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n var expires = \"; expires=\" + date.toGMTString();\n }\n else {\n var expires = \"\";\n }\n document.cookie = name + \"=\" + value + expires + \"; path=/\";\n this[name] = value;\n }\n\n var now = new Date();\n Cookies.create(\"GMT_bias\",now.getTimezoneOffset(),1);\n window.location = \"<?php echo $_SERVER['PHP_SELF'];?>\";\n </script>\n\n <?php\n\n }\n else {\n $fct_clientbias = $_COOKIE['GMT_bias'];\n }\n\n $fct_servertimedata = gettimeofday();\n $fct_servertime = $fct_servertimedata['sec'];\n $fct_serverbias = $fct_servertimedata['minuteswest'];\n $fct_totalbias = $fct_serverbias – $fct_clientbias;\n $fct_totalbias = $fct_totalbias * 60;\n $fct_clienttimestamp = $fct_servertime + $fct_totalbias;\n $fct_time = time();\n $fct_year = strftime(\"%Y\", $fct_clienttimestamp);\n $fct_month = strftime(\"%B\", $fct_clienttimestamp);\n $fct_day = strftime(\"%d\", $fct_clienttimestamp);\n $fct_hour = strftime(\"%I\", $fct_clienttimestamp);\n $fct_minute = strftime(\"%M\", $fct_clienttimestamp);\n $fct_second = strftime(\"%S\", $fct_clienttimestamp);\n $fct_am_pm = strftime(\"%p\", $fct_clienttimestamp);\n echo $fct_day.\", \".$fct_month.\" \".$fct_year.\" ( \".$fct_hour.\":\".$fct_minute.\":\".$fct_second.\" \".$fct_am_pm.\" )\";\n }\n\n showclienttime();\n?>\n" }, { "answer_id": 5492192, "author": "Joseph Lust", "author_id": 564157, "author_profile": "https://Stackoverflow.com/users/564157", "pm_score": 6, "selected": false, "text": "function TimezoneDetect(){\n var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear());\n var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt\n var intMonth;\n var intHoursUtc;\n var intHours;\n var intDaysMultiplyBy;\n\n // Go through each month to find the lowest offset to account for DST\n for (intMonth=0;intMonth < 12;intMonth++){\n //go to the next month\n dtDate.setUTCMonth(dtDate.getUTCMonth() + 1);\n\n // To ignore daylight saving time look for the lowest offset.\n // Since, during DST, the clock moves forward, it'll be a bigger number.\n if (intOffset > (dtDate.getTimezoneOffset() * (-1))){\n intOffset = (dtDate.getTimezoneOffset() * (-1));\n }\n }\n\n return intOffset;\n}\n" }, { "answer_id": 5607229, "author": "Westy92", "author_id": 453314, "author_profile": "https://Stackoverflow.com/users/453314", "pm_score": 5, "selected": false, "text": "<?php\n session_start();\n $timezone = $_SESSION['time'];\n?>\n <script type=\"text/javascript\" src=\"http://code.jquery.com/jquery-latest.min.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function() {\n if(\"<?php echo $timezone; ?>\".length==0){\n var visitortime = new Date();\n var visitortimezone = \"GMT \" + -visitortime.getTimezoneOffset()/60;\n $.ajax({\n type: \"GET\",\n url: \"http://example.org/timezone.php\",\n data: 'time='+ visitortimezone,\n success: function(){\n location.reload();\n }\n });\n }\n });\n</script>\n <?php\n session_start();\n $_SESSION['time'] = $_GET['time'];\n?>\n" }, { "answer_id": 7217925, "author": "Envis", "author_id": 915954, "author_profile": "https://Stackoverflow.com/users/915954", "pm_score": 5, "selected": false, "text": "function maketimus(timestampz)\n{\n var linktime = new Date(timestampz * 1000);\n var linkday = linktime.getDate();\n var freakingmonths = new Array();\n\n freakingmonths[0] = \"jan\";\n freakingmonths[1] = \"feb\";\n freakingmonths[2] = \"mar\";\n freakingmonths[3] = \"apr\";\n freakingmonths[4] = \"may\";\n freakingmonths[5] = \"jun\";\n freakingmonths[6] = \"jul\";\n freakingmonths[7] = \"aug\";\n freakingmonths[8] = \"sep\";\n freakingmonths[9] = \"oct\";\n freakingmonths[10] = \"nov\";\n freakingmonths[11] = \"dec\";\n\n var linkmonthnum = linktime.getMonth();\n var linkmonth = freakingmonths[linkmonthnum];\n var linkyear = linktime.getFullYear();\n var linkhour = linktime.getHours();\n var linkminute = linktime.getMinutes();\n\n if (linkminute < 10)\n {\n linkminute = \"0\" + linkminute;\n }\n\n var fomratedtime = linkday + linkmonth + linkyear + \" \" +\n linkhour + \":\" + linkminute + \"h\";\n return fomratedtime;\n}\n echo '<script type=\"text/javascript\">\nvar eltimio = maketimus('.$unix_timestamp_ofshiz.');\ndocument.write(eltimio);\n</script><noscript>pls enable javascript</noscript>';\n" }, { "answer_id": 8340357, "author": "Naeem Ul Wahhab", "author_id": 1067051, "author_profile": "https://Stackoverflow.com/users/1067051", "pm_score": 4, "selected": false, "text": "new Date().getTimezoneOffset();\n" }, { "answer_id": 9043904, "author": "Dane Iracleous", "author_id": 644337, "author_profile": "https://Stackoverflow.com/users/644337", "pm_score": 3, "selected": false, "text": "<?php\nsession_start();\n\nif(!isset($_SESSION['timezone']))\n{\n if(!isset($_REQUEST['offset']))\n {\n ?>\n <script>\n var d = new Date()\n var offset= -d.getTimezoneOffset()/60;\n location.href = \"<?php echo $_SERVER['PHP_SELF']; ?>?offset=\"+offset;\n </script>\n <?php \n }\n else\n {\n $zonelist = array('Kwajalein' => -12.00, 'Pacific/Midway' => -11.00, 'Pacific/Honolulu' => -10.00, 'America/Anchorage' => -9.00, 'America/Los_Angeles' => -8.00, 'America/Denver' => -7.00, 'America/Tegucigalpa' => -6.00, 'America/New_York' => -5.00, 'America/Caracas' => -4.30, 'America/Halifax' => -4.00, 'America/St_Johns' => -3.30, 'America/Argentina/Buenos_Aires' => -3.00, 'America/Sao_Paulo' => -3.00, 'Atlantic/South_Georgia' => -2.00, 'Atlantic/Azores' => -1.00, 'Europe/Dublin' => 0, 'Europe/Belgrade' => 1.00, 'Europe/Minsk' => 2.00, 'Asia/Kuwait' => 3.00, 'Asia/Tehran' => 3.30, 'Asia/Muscat' => 4.00, 'Asia/Yekaterinburg' => 5.00, 'Asia/Kolkata' => 5.30, 'Asia/Katmandu' => 5.45, 'Asia/Dhaka' => 6.00, 'Asia/Rangoon' => 6.30, 'Asia/Krasnoyarsk' => 7.00, 'Asia/Brunei' => 8.00, 'Asia/Seoul' => 9.00, 'Australia/Darwin' => 9.30, 'Australia/Canberra' => 10.00, 'Asia/Magadan' => 11.00, 'Pacific/Fiji' => 12.00, 'Pacific/Tongatapu' => 13.00);\n $index = array_keys($zonelist, $_REQUEST['offset']);\n $_SESSION['timezone'] = $index[0];\n }\n}\n\ndate_default_timezone_set($_SESSION['timezone']);\n\n//rest of your code goes here\n?>\n" }, { "answer_id": 10775887, "author": "JoeyFur62", "author_id": 1420406, "author_profile": "https://Stackoverflow.com/users/1420406", "pm_score": 5, "selected": false, "text": "getTimezoneOffset -new Date().getTimezoneOffset()/60;\n" }, { "answer_id": 11717580, "author": "pckabeer", "author_id": 1298003, "author_profile": "https://Stackoverflow.com/users/1298003", "pm_score": 4, "selected": false, "text": "<?php\n $ip = $_SERVER['REMOTE_ADDR'];\n $json = file_get_contents(\"http://api.easyjquery.com/ips/?ip=\" . $ip . \"&full=true\");\n $json = json_decode($json,true);\n $timezone = $json['LocalTimeZone'];\n?>\n" }, { "answer_id": 11836123, "author": "Adam", "author_id": 226513, "author_profile": "https://Stackoverflow.com/users/226513", "pm_score": 6, "selected": false, "text": ">>> var timezone = jstz.determine();\n>>> timezone.name(); \n\"Europe/London\"\n" }, { "answer_id": 12190240, "author": "Benbob", "author_id": 181637, "author_profile": "https://Stackoverflow.com/users/181637", "pm_score": 5, "selected": false, "text": ">> new Date().toTimeString();\n\"15:46:04 GMT+1200 (New Zealand Standard Time)\"\n//Use some regular expression to extract the time.\n" }, { "answer_id": 12398468, "author": "philfreo", "author_id": 137067, "author_profile": "https://Stackoverflow.com/users/137067", "pm_score": 5, "selected": false, "text": "$.ajaxSetup({\n beforeSend: function(xhr, settings) {\n xhr.setRequestHeader(\"X-TZ-Offset\", -new Date().getTimezoneOffset()/60);\n }\n});\n moment.tz.guess();" }, { "answer_id": 22625076, "author": "Matt Johnson-Pint", "author_id": 634824, "author_profile": "https://Stackoverflow.com/users/634824", "pm_score": 7, "selected": false, "text": "getTimezoneOffset Date America/Los_Angeles const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone;\nconsole.log(tzid); DateTimeFormat resolvedOptions().timeZone defaults to the host environment luxon.Settings.defaultZoneName Intl getTimezoneOffset Date // using jsTimeZoneDetect\n var tzid = jstz.determine().name();\n\n // using moment-timezone\n var tzid = moment.tz.guess();\n" }, { "answer_id": 25734579, "author": "Berislav Lopac", "author_id": 122033, "author_profile": "https://Stackoverflow.com/users/122033", "pm_score": 3, "selected": false, "text": "Date" }, { "answer_id": 25839604, "author": "man", "author_id": 1881655, "author_profile": "https://Stackoverflow.com/users/1881655", "pm_score": 4, "selected": false, "text": "new Date().getTimezoneOffset(); users date_created int(13) creates a new account post insert/update date_created column var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets\nvar tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off;\n tzo $_POST['tzo'] $ts = new DateTime('now', new DateTimeZone($_POST['tzo']);\n$user_time = $ts->format(\"F j, Y, g:i a\");//will return the users current time in readable format, regardless of whether date_default_timezone() is set or not.\n$user_timestamp = strtotime($user_time);\n date_created=$user_timestamp $date_created = // Get from the database\n$created = date(\"F j, Y, g:i a\",$date_created); // Return it to the user or whatever\n first" }, { "answer_id": 39463380, "author": "Tomas Tomecek", "author_id": 909579, "author_profile": "https://Stackoverflow.com/users/909579", "pm_score": 4, "selected": false, "text": "> moment.tz.guess()\n\"America/Asuncion\"\n" }, { "answer_id": 41568276, "author": "Useful Angle", "author_id": 7191417, "author_profile": "https://Stackoverflow.com/users/7191417", "pm_score": 4, "selected": false, "text": "getTimezoneOffset var timezone_offset_minutes = new Date().getTimezoneOffset();\ntimezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes;\n // Just an example.\n$timezone_offset_minutes = -360; // $_GET['timezone_offset_minutes']\n\n// Convert minutes to seconds\n$timezone_name = timezone_name_from_abbr(\"\", $timezone_offset_minutes*60, false);\n\n// America/Chicago\necho $timezone_name;</code></pre>\n" }, { "answer_id": 64329945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "user-agent getTzimezoneOffset() Date new Date().getTimezoneOffset();" }, { "answer_id": 67072466, "author": "Antony", "author_id": 3897214, "author_profile": "https://Stackoverflow.com/users/3897214", "pm_score": 1, "selected": false, "text": "@Matt Johnson-Pints @Mads Kristiansen" }, { "answer_id": 70495118, "author": "Atul Lohiya", "author_id": 9942276, "author_profile": "https://Stackoverflow.com/users/9942276", "pm_score": 2, "selected": false, "text": "Intl.DateTimeFormat().resolvedOptions().timeZone let dateObj = new Date(2021, 11, 25, 09, 30, 00);\n\n//then \n\ndateObj.toString() \n\n//yields\n\nSat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time) //I am located in India (IST) let longZoneRegex = /\\((.+)\\)/;\ndateObj.toString().match(longZoneRegex);\n\n//yields\n\n['(India Standard Time)', 'India Standard Time', index: 34, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]\n\n//Note that output is an array so use output[1] to get the timezone name. let shortZoneRegex = /GMT[+-]\\d{1,4}/;\ndateObj.toString().match(shortZoneRegex);\n\n//yields\n\n['GMT+0530', index: 25, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined]\n\n//Note that output is an array so use output[0] to get the timezone name." } ]
2008/08/01
[ "https://Stackoverflow.com/questions/13", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9/" ]
14
<p>What is the difference between <a href="http://msdn.microsoft.com/en-us/library/9a6a2sxy.aspx" rel="noreferrer"><code>Math.Floor()</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.math.truncate.aspx" rel="noreferrer"><code>Math.Truncate()</code></a> in .NET?</p>
[ { "answer_id": 33, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 9, "selected": false, "text": "Math.Floor Math.Ceiling Math.Truncate Math.Truncate Math.Floor Math.Ceiling Math.Round" }, { "answer_id": 2086, "author": "Marek Grzenkowicz", "author_id": 95, "author_profile": "https://Stackoverflow.com/users/95", "pm_score": 6, "selected": false, "text": "Round(1.5) = 2\nRound(2.5) = 2\nRound(1.5, MidpointRounding.AwayFromZero) = 2\nRound(2.5, MidpointRounding.AwayFromZero) = 3\nRound(1.55, 1) = 1.6\nRound(1.65, 1) = 1.6\nRound(1.55, 1, MidpointRounding.AwayFromZero) = 1.6\nRound(1.65, 1, MidpointRounding.AwayFromZero) = 1.7\n\nTruncate(2.10) = 2\nTruncate(2.00) = 2\nTruncate(1.90) = 1\nTruncate(1.80) = 1\n" }, { "answer_id": 580252, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 9, "selected": false, "text": "Math.Floor Math.Ceiling Math.Truncate Math.Round Round(2.5,MidpointRounding.ToEven) Round(2.5,MidpointRounding.AwayFromZero) -3 -2 -1 0 1 2 3\n +--|------+---------+----|----+--|------+----|----+-------|-+\n a b c d e\n\n a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8\n ====== ====== ===== ===== =====\nFloor -3 -1 0 1 2\nCeiling -2 0 1 2 3\nTruncate -2 0 0 1 2\nRound (ToEven) -3 0 0 2 3\nRound (AwayFromZero) -3 -1 0 2 3\n Round n = 3.145;\na = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14\nb = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15\n c = System.Math.Truncate (n * 100) / 100; // 3.14\nd = System.Math.Ceiling (n * 100) / 100; // 3.15\n" }, { "answer_id": 6742125, "author": "Azhar", "author_id": 228755, "author_profile": "https://Stackoverflow.com/users/228755", "pm_score": 6, "selected": false, "text": "Math.Floor() Math.Truncate Math.Floor(-3.4) = -4\nMath.Truncate(-3.4) = -3\n Math.Floor(3.4) = 3\nMath.Truncate(3.4) = 3\n" }, { "answer_id": 10937469, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "Math.Floor() Math.Truncate()" }, { "answer_id": 18893721, "author": "Pinky", "author_id": 2699939, "author_profile": "https://Stackoverflow.com/users/2699939", "pm_score": 4, "selected": false, "text": "Math.Floor() Math.Round()" }, { "answer_id": 27742779, "author": "Sandesh", "author_id": 1018966, "author_profile": "https://Stackoverflow.com/users/1018966", "pm_score": 5, "selected": false, "text": "Math.Floor(2.5) = 2\nMath.Truncate(2.5) = 2\n\nMath.Floor(-2.5) = -3\nMath.Truncate(-2.5) = -2\n float myFloat = 4.5;\nConsole.WriteLine( Math.Round(myFloat) ); // writes 4\nConsole.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5\nConsole.WriteLine( myFloat.ToString(\"F0\") ); // writes 5\n" }, { "answer_id": 35358670, "author": "safin chacko", "author_id": 5815959, "author_profile": "https://Stackoverflow.com/users/5815959", "pm_score": 5, "selected": false, "text": "Math.Floor(2.56) = 2\nMath.Floor(3.22) = 3\nMath.Floor(-2.56) = -3\nMath.Floor(-3.26) = -4\n\nMath.Truncate(2.56) = 2\nMath.Truncate(2.00) = 2\nMath.Truncate(1.20) = 1\nMath.Truncate(-3.26) = -3\nMath.Truncate(-3.96) = -3\n Math.Round(1.6) = 2\n Math.Round(-8.56) = -9\n Math.Round(8.16) = 8\n Math.Round(8.50) = 8\n Math.Round(8.51) = 9\n math.floor() math.truncate()" }, { "answer_id": 48732884, "author": "Puddle", "author_id": 9312988, "author_profile": "https://Stackoverflow.com/users/9312988", "pm_score": 6, "selected": false, "text": "Math.floor Math.ceil Math.truncate Math.round Math.floor -- -=2 floor if (this == \"wrong\")\n return \"i don't wanna be right\";\n Math.truncate(x) int(x)" }, { "answer_id": 51375320, "author": "vidy", "author_id": 9993935, "author_profile": "https://Stackoverflow.com/users/9993935", "pm_score": 3, "selected": false, "text": "Math.floor() round()" }, { "answer_id": 62551075, "author": "Anonymous", "author_id": 13127212, "author_profile": "https://Stackoverflow.com/users/13127212", "pm_score": 2, "selected": false, "text": " Math.Floor(3.45) =3\n Math.Floor(-3.45) =-4\n Math.Truncate(3.45)=3\n Math.Truncate(-3.45)=-3\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/14", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11/" ]
16
<p>How do you expose a LINQ query as an ASMX web service? <br> Usually, from the business tier, I can return a typed <code>DataSet</code> or a <code>DataTable</code> which can be serialized for transport over ASMX.</p> <p>How can I do the same for a LINQ query? <br> Is there a way to populate a typed <code>DataSet</code> or a <code>DataTable</code> via a LINQ query?</p> <pre><code>public static MyDataTable CallMySproc() { string conn = &quot;...&quot;; MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable(); // execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr; // copy LINQ query resultset into a DataTable -this does not work ! dt = query.CopyToDataTable(); return dt; } </code></pre> <p>How could I put the result set of a LINQ query into a <code>DataSet</code> or a <code>DataTable</code>? <br> Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?</p>
[ { "answer_id": 84, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 4, "selected": false, "text": "IEnumerable" }, { "answer_id": 5830, "author": "Brian Childress", "author_id": 721, "author_profile": "https://Stackoverflow.com/users/721", "pm_score": 4, "selected": false, "text": "list(T)" }, { "answer_id": 12446, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 8, "selected": true, "text": "IEnumerable CopyToDataTable IEnumerable<DataRow> query =\n from order in orders.AsEnumerable()\n where order.Field<DateTime>(\"OrderDate\") > new DateTime(2001, 8, 1)\n select order;\n\n// Create a table from the query.\nDataTable boundTable = query.CopyToDataTable<DataRow>();\n" }, { "answer_id": 544169, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "DataContext MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n as IEnumerable<DataRow>;" }, { "answer_id": 49774484, "author": "Vijay S", "author_id": 7204125, "author_profile": "https://Stackoverflow.com/users/7204125", "pm_score": 3, "selected": false, "text": "IEnumerable MyDataContext db = new MyDataContext();\nIEnumerable<DataRow> query = \n (from order in db.Orders.AsEnumerable()\n select new\n {\n order.Property,\n order.Property2\n })\n as IEnumerable<DataRow>;\nreturn query.CopyToDataTable<DataRow>();\n" }, { "answer_id": 56693278, "author": "Gabriel Magana", "author_id": 99455, "author_profile": "https://Stackoverflow.com/users/99455", "pm_score": 2, "selected": false, "text": "IEnumerable<DataRow>" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/16", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2/" ]
17
<p>How do I store binary data in <a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>?</p>
[ { "answer_id": 18, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "CREATE TABLE binary_data (\n id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n description CHAR(50),\n bin_data LONGBLOB,\n filename CHAR(50),\n filesize CHAR(50),\n filetype CHAR(50)\n);\n <?php\n // store.php3 - by Florian Dittmer <[email protected]>\n // Example php script to demonstrate the storing of binary files into\n // an sql database. More information can be found at http://www.phpbuilder.com/\n?>\n\n<html>\n <head><title>Store binary data into SQL Database</title></head>\n\n <body>\n <?php\n // Code that will be executed if the form has been submitted:\n\n if ($submit) {\n // Connect to the database (you may have to adjust\n // the hostname, username or password).\n\n mysql_connect(\"localhost\", \"root\", \"password\");\n mysql_select_db(\"binary_data\");\n\n $data = mysql_real_escape_string(fread(fopen($form_data, \"r\"), filesize($form_data)));\n\n $result = mysql_query(\"INSERT INTO binary_data (description, bin_data, filename, filesize, filetype) \".\n \"VALUES ('$form_description', '$data', '$form_data_name', '$form_data_size', '$form_data_type')\");\n\n $id= mysql_insert_id();\n print \"<p>This file has the following Database ID: <b>$id</b>\";\n\n mysql_close();\n } else {\n\n // else show the form to submit new data:\n ?>\n <form method=\"post\" action=\"<?php echo $PHP_SELF; ?>\" enctype=\"multipart/form-data\">\n File Description:<br>\n <input type=\"text\" name=\"form_description\" size=\"40\">\n <input type=\"hidden\" name=\"MAX_FILE_SIZE\" value=\"1000000\">\n <br>File to upload/store in database:<br>\n <input type=\"file\" name=\"form_data\" size=\"40\">\n <p><input type=\"submit\" name=\"submit\" value=\"submit\">\n </form>\n\n <?php\n }\n ?>\n </body>\n</html>\n" }, { "answer_id": 26, "author": "Mat", "author_id": 48, "author_profile": "https://Stackoverflow.com/users/48", "pm_score": 8, "selected": true, "text": "BLOB" }, { "answer_id": 69311, "author": "user10117", "author_id": 10117, "author_profile": "https://Stackoverflow.com/users/10117", "pm_score": 4, "selected": false, "text": "base64" }, { "answer_id": 4567420, "author": "d0nut", "author_id": 499257, "author_profile": "https://Stackoverflow.com/users/499257", "pm_score": 4, "selected": false, "text": "LONGBLOB TINYBLOB/BLOB/MEDIUMBLOB/LONGBLOB VARBINARY BINARY BINARY VARBINARY" }, { "answer_id": 18763725, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "mysql_query(\"UPDATE table SET field=X'\".bin2hex($bin_data).\"' WHERE id=$id\");\n" }, { "answer_id": 23405248, "author": "zeppaman", "author_id": 3559251, "author_profile": "https://Stackoverflow.com/users/3559251", "pm_score": 4, "selected": false, "text": "VARBINARY" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/17", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2/" ]
19
<p>I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using <code>#define</code> constants like <code>M_PI</code>, or hard-coding the number in.</p> <p>The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the <code>4 * atan(1)</code> version is fastest on GCC 4.2, because it auto-folds the <code>atan(1)</code> into a constant. With <code>-fno-builtin</code> specified, the <code>atan2(0, -1)</code> version is fastest.</p> <p>Here's the main testing program (<code>pitimes.c</code>):</p> <pre class="lang-c prettyprint-override"><code>#include &lt;math.h&gt; #include &lt;stdio.h&gt; #include &lt;time.h&gt; #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i &lt; ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=&gt; %e, time =&gt; %f\n", #x, diff, diffclock(time2, time1)); \ } static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; } int main() { int i; clock_t time1, time2; double diff; /* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1)) #if defined(__GNUC__) &amp;&amp; (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif /* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1)) return 0; } </code></pre> <p>And the inline assembly stuff (<code>fldpi.c</code>) that will only work for x86 and x64 systems:</p> <pre class="lang-c prettyprint-override"><code>double fldpi() { double pi; asm("fldpi" : "=t" (pi)); return pi; } </code></pre> <p>And a build script that builds all the configurations I'm testing (<code>build.sh</code>):</p> <pre><code>#!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm </code></pre> <p>Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the <code>atan2(0, -1)</code> version still comes out on top every time.</p>
[ { "answer_id": 531, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 9, "selected": true, "text": "let pi_2 iters =\n let rec loop_ a b t p i =\n if i = 0 then a,b,t,p\n else\n let a_n = (a +. b) /. 2.0 \n and b_n = sqrt (a*.b)\n and p_n = 2.0 *. p in\n let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in\n loop_ a_n b_n t_n p_n (i - 1)\n in \n let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in\n (a +. b) *. (a +. b) /. (4.0 *. t)\n int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf(\"%.4d\",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);}\n" }, { "answer_id": 4089, "author": "Michiel de Mare", "author_id": 136, "author_profile": "https://Stackoverflow.com/users/136", "pm_score": 4, "selected": false, "text": ";''6666,-2%{2+.2/@*\\/10.3??2*+}*`1000<~\\;\n" }, { "answer_id": 39512, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 7, "selected": false, "text": "#define _ -F<00||--F-OO--;\nint F=00,OO=00;main(){F_OO();printf(\"%1.3f\\n\",4.*-F/OO/OO);}F_OO()\n{\n _-_-_-_\n _-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_-_-_-_-_\n _-_-_-_-_-_-_-_\n _-_-_-_\n}\n" }, { "answer_id": 85798, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 4, "selected": false, "text": "/** Calculate pi at compile time\n *\n * Compile with dmd -c pi.d\n */\nmodule calcpi;\n\nimport meta.math;\nimport meta.conv;\n\n/** real evaluateSeries!(real x, real metafunction!(real y, int n) term)\n *\n * Evaluate a power series at compile time.\n *\n * Given a metafunction of the form\n * real term!(real y, int n),\n * which gives the nth term of a convergent series at the point y\n * (where the first term is n==1), and a real number x,\n * this metafunction calculates the infinite sum at the point x\n * by adding terms until the sum doesn't change any more.\n */\ntemplate evaluateSeries(real x, alias term, int n=1, real sumsofar=0.0)\n{\n static if (n>1 && sumsofar == sumsofar + term!(x, n+1)) {\n const real evaluateSeries = sumsofar;\n } else {\n const real evaluateSeries = evaluateSeries!(x, term, n+1, sumsofar + term!(x, n));\n }\n}\n\n/*** Calculate atan(x) at compile time.\n *\n * Uses the Maclaurin formula\n * atan(z) = z - z^3/3 + Z^5/5 - Z^7/7 + ...\n */\ntemplate atan(real z)\n{\n const real atan = evaluateSeries!(z, atanTerm);\n}\n\ntemplate atanTerm(real x, int n)\n{\n const real atanTerm = (n & 1 ? 1 : -1) * pow!(x, 2*n-1)/(2*n-1);\n}\n\n/// Machin's formula for pi\n/// pi/4 = 4 atan(1/5) - atan(1/239).\npragma(msg, \"PI = \" ~ fcvt!(4.0 * (4*atan!(1/5.0) - atan!(1/239.0))) );\n" }, { "answer_id": 164687, "author": "Andrea Ambu", "author_id": 21384, "author_profile": "https://Stackoverflow.com/users/21384", "pm_score": 5, "selected": false, "text": "from math import pi\nfrom time import time\n\n\nprecision = 10**6 # higher value -> higher precision\n # lower value -> higher speed\n\nt = time()\n\ncalc = 0\nfor k in xrange(0, precision):\n calc += ((-1)**k) / (2*k+1.)\ncalc *= 4. # this is just a little optimization\n\nt = time()-t\n\nprint \"Calculated: %.40f\" % calc\nprint \"Constant pi: %.40f\" % pi\nprint \"Difference: %.40f\" % abs(calc-pi)\nprint \"Time elapsed: %s\" % repr(t)\n from gmpy import pi\nprint pi(3000) # the rule is the same as \n # the precision on the previous code\n static char doc_pi[]=\"\\\npi(n): returns pi with n bits of precision in an mpf object\\n\\\n\";\n\n/* This function was originally from netlib, package bmp, by\n * Richard P. Brent. Paulo Cesar Pereira de Andrade converted\n * it to C and used it in his LISP interpreter.\n *\n * Original comments:\n * \n * sets mp pi = 3.14159... to the available precision.\n * uses the gauss-legendre algorithm.\n * this method requires time o(ln(t)m(t)), so it is slower\n * than mppi if m(t) = o(t**2), but would be faster for\n * large t if a faster multiplication algorithm were used\n * (see comments in mpmul).\n * for a description of the method, see - multiple-precision\n * zero-finding and the complexity of elementary function\n * evaluation (by r. p. brent), in analytic computational\n * complexity (edited by j. f. traub), academic press, 1976, 151-176.\n * rounding options not implemented, no guard digits used.\n*/\nstatic PyObject *\nPygmpy_pi(PyObject *self, PyObject *args)\n{\n PympfObject *pi;\n int precision;\n mpf_t r_i2, r_i3, r_i4;\n mpf_t ix;\n\n ONE_ARG(\"pi\", \"i\", &precision);\n if(!(pi = Pympf_new(precision))) {\n return NULL;\n }\n\n mpf_set_si(pi->f, 1);\n\n mpf_init(ix);\n mpf_set_ui(ix, 1);\n\n mpf_init2(r_i2, precision);\n\n mpf_init2(r_i3, precision);\n mpf_set_d(r_i3, 0.25);\n\n mpf_init2(r_i4, precision);\n mpf_set_d(r_i4, 0.5);\n mpf_sqrt(r_i4, r_i4);\n\n for (;;) {\n mpf_set(r_i2, pi->f);\n mpf_add(pi->f, pi->f, r_i4);\n mpf_div_ui(pi->f, pi->f, 2);\n mpf_mul(r_i4, r_i2, r_i4);\n mpf_sub(r_i2, pi->f, r_i2);\n mpf_mul(r_i2, r_i2, r_i2);\n mpf_mul(r_i2, r_i2, ix);\n mpf_sub(r_i3, r_i3, r_i2);\n mpf_sqrt(r_i4, r_i4);\n mpf_mul_ui(ix, ix, 2);\n /* Check for convergence */\n if (!(mpf_cmp_si(r_i2, 0) && \n mpf_get_prec(r_i2) >= (unsigned)precision)) {\n mpf_mul(pi->f, pi->f, r_i4);\n mpf_div(pi->f, pi->f, r_i3);\n break;\n }\n }\n\n mpf_clear(ix);\n mpf_clear(r_i2);\n mpf_clear(r_i3);\n mpf_clear(r_i4);\n\n return (PyObject*)pi;\n}\n" }, { "answer_id": 436447, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 4, "selected": false, "text": "program calcpi;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils;\n\nvar\n start, finish: TDateTime;\n\nfunction CalculatePi(iterations: integer): double;\nvar\n numerator, denominator, i: integer;\n sum: double;\nbegin\n {\n PI may be approximated with this formula:\n 4 * (1 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11 .......)\n //}\n numerator := 1;\n denominator := 1;\n sum := 0;\n for i := 1 to iterations do begin\n sum := sum + (numerator/denominator);\n denominator := denominator + 2;\n numerator := -numerator;\n end;\n Result := 4 * sum;\nend;\n\nbegin\n try\n start := Now;\n WriteLn(FloatToStr(CalculatePi(StrToInt(ParamStr(1)))));\n finish := Now;\n WriteLn('Seconds:' + FormatDateTime('hh:mm:ss.zz',finish-start));\n except\n on E:Exception do\n Writeln(E.Classname, ': ', E.Message);\n end;\nend.\n" }, { "answer_id": 571276, "author": "Kristopher Johnson", "author_id": 1175, "author_profile": "https://Stackoverflow.com/users/1175", "pm_score": 4, "selected": false, "text": "/* Return approximation of n * PI; n is integer */\n#define pi_times(n) (((n) * 22) / 7)\n" }, { "answer_id": 592025, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Text;\n\nclass Program {\n static void Main(string[] args) {\n int Digits = 100;\n\n BigNumber x = new BigNumber(Digits);\n BigNumber y = new BigNumber(Digits);\n x.ArcTan(16, 5);\n y.ArcTan(4, 239);\n x.Subtract(y);\n string pi = x.ToString();\n Console.WriteLine(pi);\n }\n}\n\npublic class BigNumber {\n private UInt32[] number;\n private int size;\n private int maxDigits;\n\n public BigNumber(int maxDigits) {\n this.maxDigits = maxDigits;\n this.size = (int)Math.Ceiling((float)maxDigits * 0.104) + 2;\n number = new UInt32[size];\n }\n public BigNumber(int maxDigits, UInt32 intPart)\n : this(maxDigits) {\n number[0] = intPart;\n for (int i = 1; i < size; i++) {\n number[i] = 0;\n }\n }\n private void VerifySameSize(BigNumber value) {\n if (Object.ReferenceEquals(this, value))\n throw new Exception(\"BigNumbers cannot operate on themselves\");\n if (value.size != this.size)\n throw new Exception(\"BigNumbers must have the same size\");\n }\n\n public void Add(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] +\n value.number[index] + carry;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n carry = 1;\n else\n carry = 0;\n index--;\n }\n }\n public void Subtract(BigNumber value) {\n VerifySameSize(value);\n\n int index = size - 1;\n while (index >= 0 && value.number[index] == 0)\n index--;\n\n UInt32 borrow = 0;\n while (index >= 0) {\n UInt64 result = 0x100000000U + (UInt64)number[index] -\n value.number[index] - borrow;\n number[index] = (UInt32)result;\n if (result >= 0x100000000U)\n borrow = 0;\n else\n borrow = 1;\n index--;\n }\n }\n public void Multiply(UInt32 value) {\n int index = size - 1;\n while (index >= 0 && number[index] == 0)\n index--;\n\n UInt32 carry = 0;\n while (index >= 0) {\n UInt64 result = (UInt64)number[index] * value + carry;\n number[index] = (UInt32)result;\n carry = (UInt32)(result >> 32);\n index--;\n }\n }\n public void Divide(UInt32 value) {\n int index = 0;\n while (index < size && number[index] == 0)\n index++;\n\n UInt32 carry = 0;\n while (index < size) {\n UInt64 result = number[index] + ((UInt64)carry << 32);\n number[index] = (UInt32)(result / (UInt64)value);\n carry = (UInt32)(result % (UInt64)value);\n index++;\n }\n }\n public void Assign(BigNumber value) {\n VerifySameSize(value);\n for (int i = 0; i < size; i++) {\n number[i] = value.number[i];\n }\n }\n\n public override string ToString() {\n BigNumber temp = new BigNumber(maxDigits);\n temp.Assign(this);\n\n StringBuilder sb = new StringBuilder();\n sb.Append(temp.number[0]);\n sb.Append(System.Globalization.CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator);\n\n int digitCount = 0;\n while (digitCount < maxDigits) {\n temp.number[0] = 0;\n temp.Multiply(100000);\n sb.AppendFormat(\"{0:D5}\", temp.number[0]);\n digitCount += 5;\n }\n\n return sb.ToString();\n }\n public bool IsZero() {\n foreach (UInt32 item in number) {\n if (item != 0)\n return false;\n }\n return true;\n }\n\n public void ArcTan(UInt32 multiplicand, UInt32 reciprocal) {\n BigNumber X = new BigNumber(maxDigits, multiplicand);\n X.Divide(reciprocal);\n reciprocal *= reciprocal;\n\n this.Assign(X);\n\n BigNumber term = new BigNumber(maxDigits);\n UInt32 divisor = 1;\n bool subtractTerm = true;\n while (true) {\n X.Divide(reciprocal);\n term.Assign(X);\n divisor += 2;\n term.Divide(divisor);\n if (term.IsZero())\n break;\n\n if (subtractTerm)\n this.Subtract(term);\n else\n this.Add(term);\n subtractTerm = !subtractTerm;\n }\n }\n}\n" }, { "answer_id": 622950, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "acos(-1)" }, { "answer_id": 1439914, "author": "Daniel C. Sobral", "author_id": 53013, "author_profile": "https://Stackoverflow.com/users/53013", "pm_score": 4, "selected": false, "text": "355 / 113" }, { "answer_id": 1947163, "author": "jon-hanson", "author_id": 84538, "author_profile": "https://Stackoverflow.com/users/84538", "pm_score": 6, "selected": false, "text": "#include <iostream>\n\ntemplate<int I>\nstruct sign\n{\n enum {value = (I % 2) == 0 ? 1 : -1};\n};\n\ntemplate<int I, int J>\nstruct pi_calc\n{\n inline static double value ()\n {\n return (pi_calc<I-1, J>::value () + pi_calc<I-1, J+1>::value ()) / 2.0;\n }\n};\n\ntemplate<int J>\nstruct pi_calc<0, J>\n{\n inline static double value ()\n {\n return (sign<J>::value * 4.0) / (2.0 * J + 1.0) + pi_calc<0, J-1>::value ();\n }\n};\n\n\ntemplate<>\nstruct pi_calc<0, 0>\n{\n inline static double value ()\n {\n return 4.0;\n }\n};\n\ntemplate<int I>\nstruct pi\n{\n inline static double value ()\n {\n return pi_calc<I, I>::value ();\n }\n};\n\nint main ()\n{\n std::cout.precision (12);\n\n const double pi_value = pi<10>::value ();\n\n std::cout << \"pi ~ \" << pi_value << std::endl;\n\n return 0;\n}\n" }, { "answer_id": 1949194, "author": "Seth", "author_id": 65295, "author_profile": "https://Stackoverflow.com/users/65295", "pm_score": 4, "selected": false, "text": "PI = 3.141592654\n" }, { "answer_id": 2350024, "author": "qwerty01", "author_id": 282776, "author_profile": "https://Stackoverflow.com/users/282776", "pm_score": 4, "selected": false, "text": "4.0 * (4.0 * Math.Atan(0.2) - Math.Atan(1.0 / 239.0))\n" }, { "answer_id": 4905303, "author": "NihilistDandy", "author_id": 604108, "author_profile": "https://Stackoverflow.com/users/604108", "pm_score": 4, "selected": false, "text": "176 * arctan (1/57) + 28 * arctan (1/239) - 48 * arctan (1/682) + 96 * arctan(1/12943) \n\n[; \\left( 176 \\arctan \\frac{1}{57} + 28 \\arctan \\frac{1}{239} - 48 \\arctan \\frac{1}{682} + 96 \\arctan \\frac{1}{12943}\\right) ;], for you TeX the World people.\n (+ (- (+ (* 176 (atan (/ 1 57))) (* 28 (atan (/ 1 239)))) (* 48 (atan (/ 1 682)))) (* 96 (atan (/ 1 12943))))" }, { "answer_id": 44346598, "author": "Agnius Vasiliauskas", "author_id": 380331, "author_profile": "https://Stackoverflow.com/users/380331", "pm_score": 1, "selected": false, "text": "<input id=\"range\" type=\"range\" min=\"10\" max=\"960\" value=\"10\" step=\"50\" oninput=\"calcPi()\">\n<br>\n<div id=\"cont\"></div>\n\n<script>\nfunction generateCircle(width) {\n var c = width/2;\n var delta = 1.0;\n var str = \"\";\n var xCount = 0;\n for (var x=0; x <= width; x++) {\n for (var y = 0; y <= width; y++) {\n var d = Math.sqrt((x-c)*(x-c) + (y-c)*(y-c));\n if (d > (width-1)/2) {\n str += '.';\n }\n else {\n xCount++;\n str += 'o';\n }\n str += \"&nbsp;\" \n }\n str += \"\\n\";\n }\n var pi = (xCount * 4) / (width * width);\n return [str, pi];\n}\n\nfunction calcPi() {\n var e = document.getElementById(\"cont\");\n var width = document.getElementById(\"range\").value;\n e.innerHTML = \"<h4>Generating circle...</h4>\";\n setTimeout(function() {\n var circ = generateCircle(width);\n e.innerHTML = \"<pre>\" + \"π = \" + circ[1].toFixed(2) + \"\\n\" + circ[0] +\"</pre>\";\n }, 200);\n}\ncalcPi();\n</script>" }, { "answer_id": 50907044, "author": "Anand Tripathi", "author_id": 5230702, "author_profile": "https://Stackoverflow.com/users/5230702", "pm_score": 0, "selected": false, "text": "import math\nprint math.pi\n /usr/bin/time -v python math_pi.py Command being timed: \"python math_pi.py\"\nUser time (seconds): 0.01\nSystem time (seconds): 0.01\nPercent of CPU this job got: 91%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n import math\nprint math.acos(-1)\n /usr/bin/time -v python acos_pi.py Command being timed: \"python acos_pi.py\"\nUser time (seconds): 0.02\nSystem time (seconds): 0.01\nPercent of CPU this job got: 94%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.03\n from decimal import Decimal, getcontext\ngetcontext().prec=100\nprint sum(1/Decimal(16)**k * \n (Decimal(4)/(8*k+1) - \n Decimal(2)/(8*k+4) - \n Decimal(1)/(8*k+5) -\n Decimal(1)/(8*k+6)) for k in range(100))\n /usr/bin/time -v python bbp_pi.py Command being timed: \"python c.py\"\nUser time (seconds): 0.05\nSystem time (seconds): 0.01\nPercent of CPU this job got: 98%\nElapsed (wall clock) time (h:mm:ss or m:ss): 0:00.06\n" }, { "answer_id": 61670212, "author": "paperclip optimizer", "author_id": 11147804, "author_profile": "https://Stackoverflow.com/users/11147804", "pm_score": 1, "selected": false, "text": "/*\n Chudnovsky algorithm for computing PI\n*/\n\n#include <iostream>\n#include <cmath>\nusing namespace std;\n\ndouble calc_PI(int K=2) {\n\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n\n const double ID3 = 1./ (double(D)*double(D)*double(D));\n\n double sum = 0.;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n\n sum += double(p) * double(a)* b;\n\n // 2 iterations enough for double convergence\n for (int k=1; k<K; ++k) {\n // A*k + B\n a += A;\n // update denominator\n b *= ID3;\n // p = (-1)^k 6k! / 3k! k!^3\n p *= (6*k)*(6*k-1)*(6*k-2)*(6*k-3)*(6*k-4)*(6*k-5);\n p /= (3*k)*(3*k-1)*(3*k-2) * k*k*k;\n p = -p;\n\n sum += double(p) * double(a)* b;\n }\n\n return 1./(12*sum);\n}\n\nint main() {\n\n cout.precision(16);\n cout.setf(ios::fixed);\n\n for (int k=1; k<=5; ++k) cout << \"k = \" << k << \" PI = \" << calc_PI(k) << endl;\n\n return 0;\n}\n k = 1 PI = 3.1415926535897341\nk = 2 PI = 3.1415926535897931\nk = 3 PI = 3.1415926535897931\nk = 4 PI = 3.1415926535897931\nk = 5 PI = 3.1415926535897931\n" }, { "answer_id": 64410809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "#include <stdio.h>\n#include <math.h>\n\ndouble calc_PI(int K) {\n static const int A = 545140134;\n static const int B = 13591409;\n static const int D = 640320;\n const double ID3 = 1.0 / ((double) D * (double) D * (double) D);\n double sum = 0.0;\n double b = sqrt(ID3);\n long long int p = 1;\n long long int a = B;\n sum += (double) p * (double) a * b;\n for (int k = 1; k < K; ++k) {\n a += A;\n b *= ID3;\n p *= (6 * k) * (6 * k - 1) * (6 * k - 2) * (6 * k - 3) * (6 * k - 4) * (6 * k - 5);\n p /= (3 * k) * (3 * k - 1) * (3 * k - 2) * k * k * k;\n p = -p;\n sum += (double) p * (double) a * b;\n }\n return 1.0 / (12 * sum);\n}\n\nint main() {\n for (int k = 1; k <= 5; ++k) {\n printf(\"k = %i, PI = %.16f\\n\", k, calc_PI(k));\n }\n}\n double double double double double" }, { "answer_id": 73777598, "author": "Andy Richter", "author_id": 6262481, "author_profile": "https://Stackoverflow.com/users/6262481", "pm_score": 0, "selected": false, "text": "class PiChudnovsky:\n \"\"\"Version of Chudnovsky Bros using Binary Splitting \n So far this is the winner for fastest time to a million digits on my older intel i7\n \"\"\"\n A = mpz(13591409)\n B = mpz(545140134)\n C = mpz(640320)\n D = mpz(426880)\n E = mpz(10005)\n C3_24 = pow(C, mpz(3)) // mpz(24)\n #DIGITS_PER_TERM = math.log(53360 ** 3) / math.log(10) #=> 14.181647462725476\n DIGITS_PER_TERM = 14.181647462725476\n MMILL = mpz(1000000)\n\n def __init__(self,ndigits):\n \"\"\" Initialization\n :param int ndigits: digits of PI computation\n \"\"\"\n self.ndigits = ndigits\n self.n = mpz(self.ndigits // self.DIGITS_PER_TERM + 1)\n self.prec = mpz((self.ndigits + 1) * LOG2_10)\n self.one_sq = pow(mpz(10),mpz(2 * ndigits))\n self.sqrt_c = isqrt(self.E * self.one_sq)\n self.iters = mpz(0)\n self.start_time = 0\n\n def compute(self):\n \"\"\" Computation \"\"\"\n try:\n self.start_time = time.time()\n logging.debug(\"Starting {} formula to {:,} decimal places\"\n .format(name,ndigits) )\n __, q, t = self.__bs(mpz(0), self.n) # p is just for recursion\n pi = (q * self.D * self.sqrt_c) // t\n logging.debug('{} calulation Done! {:,} iterations and {:.2f} seconds.'\n .format( name, int(self.iters),time.time() - self.start_time))\n get_context().precision= int((self.ndigits+10) * LOG2_10)\n pi_s = pi.digits() # digits() gmpy2 creates a string \n pi_o = pi_s[:1] + \".\" + pi_s[1:]\n return pi_o,int(self.iters),time.time() - self.start_time\n except Exception as e:\n print (e.message, e.args)\n raise\n\n def __bs(self, a, b):\n \"\"\" PQT computation by BSA(= Binary Splitting Algorithm)\n :param int a: positive integer\n :param int b: positive integer\n :return list [int p_ab, int q_ab, int t_ab]\n \"\"\"\n try:\n self.iters += mpz(1)\n if self.iters % self.MMILL == mpz(0):\n logging.debug('Chudnovsky ... {:,} iterations and {:.2f} seconds.'\n .format( int(self.iters),time.time() - self.start_time))\n if a + mpz(1) == b:\n if a == mpz(0):\n p_ab = q_ab = mpz(1)\n else:\n p_ab = mpz((mpz(6) * a - mpz(5)) * (mpz(2) * a - mpz(1)) * (mpz(6) * a - mpz(1)))\n q_ab = pow(a,mpz(3)) * self.C3_24\n t_ab = p_ab * (self.A + self.B * a)\n if a & 1:\n t_ab *= mpz(-1)\n else:\n m = (a + b) // mpz(2)\n p_am, q_am, t_am = self.__bs(a, m)\n p_mb, q_mb, t_mb = self.__bs(m, b)\n p_ab = p_am * p_mb\n q_ab = q_am * q_mb\n t_ab = q_mb * t_am + p_am * t_mb\n return [p_ab, q_ab, t_ab]\n except Exception as e:\n print (e.message, e.args)\n raise\n python pi-pourri.py -v -d 1,000,000,000 -a 10 \n\n[INFO] 2022-10-03 09:22:51,860 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 09:25:00,543 compute: MainProcess Starting Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 09:25:04,995 __bs: MainProcess Chudnovsky ... 1,000,000 iterations and 4.45 seconds.\n[DEBUG] 2022-10-03 09:25:10,836 __bs: MainProcess Chudnovsky ... 2,000,000 iterations and 10.29 seconds.\n[DEBUG] 2022-10-03 09:25:18,227 __bs: MainProcess Chudnovsky ... 3,000,000 iterations and 17.68 seconds.\n[DEBUG] 2022-10-03 09:25:24,512 __bs: MainProcess Chudnovsky ... 4,000,000 iterations and 23.97 seconds.\n[DEBUG] 2022-10-03 09:25:35,670 __bs: MainProcess Chudnovsky ... 5,000,000 iterations and 35.13 seconds.\n[DEBUG] 2022-10-03 09:25:41,376 __bs: MainProcess Chudnovsky ... 6,000,000 iterations and 40.83 seconds.\n[DEBUG] 2022-10-03 09:25:49,238 __bs: MainProcess Chudnovsky ... 7,000,000 iterations and 48.69 seconds.\n[DEBUG] 2022-10-03 09:25:55,646 __bs: MainProcess Chudnovsky ... 8,000,000 iterations and 55.10 seconds.\n[DEBUG] 2022-10-03 09:26:15,043 __bs: MainProcess Chudnovsky ... 9,000,000 iterations and 74.50 seconds.\n[DEBUG] 2022-10-03 09:26:21,437 __bs: MainProcess Chudnovsky ... 10,000,000 iterations and 80.89 seconds.\n[DEBUG] 2022-10-03 09:26:26,587 __bs: MainProcess Chudnovsky ... 11,000,000 iterations and 86.04 seconds.\n[DEBUG] 2022-10-03 09:26:34,777 __bs: MainProcess Chudnovsky ... 12,000,000 iterations and 94.23 seconds.\n[DEBUG] 2022-10-03 09:26:41,231 __bs: MainProcess Chudnovsky ... 13,000,000 iterations and 100.69 seconds.\n[DEBUG] 2022-10-03 09:26:52,972 __bs: MainProcess Chudnovsky ... 14,000,000 iterations and 112.43 seconds.\n[DEBUG] 2022-10-03 09:26:59,517 __bs: MainProcess Chudnovsky ... 15,000,000 iterations and 118.97 seconds.\n[DEBUG] 2022-10-03 09:27:07,932 __bs: MainProcess Chudnovsky ... 16,000,000 iterations and 127.39 seconds.\n[DEBUG] 2022-10-03 09:27:14,036 __bs: MainProcess Chudnovsky ... 17,000,000 iterations and 133.49 seconds.\n[DEBUG] 2022-10-03 09:27:51,629 __bs: MainProcess Chudnovsky ... 18,000,000 iterations and 171.09 seconds.\n[DEBUG] 2022-10-03 09:27:58,176 __bs: MainProcess Chudnovsky ... 19,000,000 iterations and 177.63 seconds.\n[DEBUG] 2022-10-03 09:28:06,704 __bs: MainProcess Chudnovsky ... 20,000,000 iterations and 186.16 seconds.\n[DEBUG] 2022-10-03 09:28:13,376 __bs: MainProcess Chudnovsky ... 21,000,000 iterations and 192.83 seconds.\n[DEBUG] 2022-10-03 09:28:18,737 __bs: MainProcess Chudnovsky ... 22,000,000 iterations and 198.19 seconds.\n[DEBUG] 2022-10-03 09:28:31,095 __bs: MainProcess Chudnovsky ... 23,000,000 iterations and 210.55 seconds.\n[DEBUG] 2022-10-03 09:28:37,789 __bs: MainProcess Chudnovsky ... 24,000,000 iterations and 217.25 seconds.\n[DEBUG] 2022-10-03 09:28:46,171 __bs: MainProcess Chudnovsky ... 25,000,000 iterations and 225.63 seconds.\n[DEBUG] 2022-10-03 09:28:52,933 __bs: MainProcess Chudnovsky ... 26,000,000 iterations and 232.39 seconds.\n[DEBUG] 2022-10-03 09:29:13,524 __bs: MainProcess Chudnovsky ... 27,000,000 iterations and 252.98 seconds.\n[DEBUG] 2022-10-03 09:29:19,676 __bs: MainProcess Chudnovsky ... 28,000,000 iterations and 259.13 seconds.\n[DEBUG] 2022-10-03 09:29:28,196 __bs: MainProcess Chudnovsky ... 29,000,000 iterations and 267.65 seconds.\n[DEBUG] 2022-10-03 09:29:34,720 __bs: MainProcess Chudnovsky ... 30,000,000 iterations and 274.18 seconds.\n[DEBUG] 2022-10-03 09:29:47,075 __bs: MainProcess Chudnovsky ... 31,000,000 iterations and 286.53 seconds.\n[DEBUG] 2022-10-03 09:29:53,746 __bs: MainProcess Chudnovsky ... 32,000,000 iterations and 293.20 seconds.\n[DEBUG] 2022-10-03 09:29:59,099 __bs: MainProcess Chudnovsky ... 33,000,000 iterations and 298.56 seconds.\n[DEBUG] 2022-10-03 09:30:07,511 __bs: MainProcess Chudnovsky ... 34,000,000 iterations and 306.97 seconds.\n[DEBUG] 2022-10-03 09:30:14,279 __bs: MainProcess Chudnovsky ... 35,000,000 iterations and 313.74 seconds.\n[DEBUG] 2022-10-03 09:31:31,710 __bs: MainProcess Chudnovsky ... 36,000,000 iterations and 391.17 seconds.\n[DEBUG] 2022-10-03 09:31:38,454 __bs: MainProcess Chudnovsky ... 37,000,000 iterations and 397.91 seconds.\n[DEBUG] 2022-10-03 09:31:46,437 __bs: MainProcess Chudnovsky ... 38,000,000 iterations and 405.89 seconds.\n[DEBUG] 2022-10-03 09:31:53,285 __bs: MainProcess Chudnovsky ... 39,000,000 iterations and 412.74 seconds.\n[DEBUG] 2022-10-03 09:32:05,602 __bs: MainProcess Chudnovsky ... 40,000,000 iterations and 425.06 seconds.\n[DEBUG] 2022-10-03 09:32:12,220 __bs: MainProcess Chudnovsky ... 41,000,000 iterations and 431.68 seconds.\n[DEBUG] 2022-10-03 09:32:20,708 __bs: MainProcess Chudnovsky ... 42,000,000 iterations and 440.17 seconds.\n[DEBUG] 2022-10-03 09:32:27,552 __bs: MainProcess Chudnovsky ... 43,000,000 iterations and 447.01 seconds.\n[DEBUG] 2022-10-03 09:32:32,986 __bs: MainProcess Chudnovsky ... 44,000,000 iterations and 452.44 seconds.\n[DEBUG] 2022-10-03 09:32:53,904 __bs: MainProcess Chudnovsky ... 45,000,000 iterations and 473.36 seconds.\n[DEBUG] 2022-10-03 09:33:00,832 __bs: MainProcess Chudnovsky ... 46,000,000 iterations and 480.29 seconds.\n[DEBUG] 2022-10-03 09:33:09,198 __bs: MainProcess Chudnovsky ... 47,000,000 iterations and 488.66 seconds.\n[DEBUG] 2022-10-03 09:33:16,000 __bs: MainProcess Chudnovsky ... 48,000,000 iterations and 495.46 seconds.\n[DEBUG] 2022-10-03 09:33:27,921 __bs: MainProcess Chudnovsky ... 49,000,000 iterations and 507.38 seconds.\n[DEBUG] 2022-10-03 09:33:34,778 __bs: MainProcess Chudnovsky ... 50,000,000 iterations and 514.24 seconds.\n[DEBUG] 2022-10-03 09:33:43,298 __bs: MainProcess Chudnovsky ... 51,000,000 iterations and 522.76 seconds.\n[DEBUG] 2022-10-03 09:33:49,959 __bs: MainProcess Chudnovsky ... 52,000,000 iterations and 529.42 seconds.\n[DEBUG] 2022-10-03 09:34:29,294 __bs: MainProcess Chudnovsky ... 53,000,000 iterations and 568.75 seconds.\n[DEBUG] 2022-10-03 09:34:36,176 __bs: MainProcess Chudnovsky ... 54,000,000 iterations and 575.63 seconds.\n[DEBUG] 2022-10-03 09:34:41,576 __bs: MainProcess Chudnovsky ... 55,000,000 iterations and 581.03 seconds.\n[DEBUG] 2022-10-03 09:34:50,161 __bs: MainProcess Chudnovsky ... 56,000,000 iterations and 589.62 seconds.\n[DEBUG] 2022-10-03 09:34:56,811 __bs: MainProcess Chudnovsky ... 57,000,000 iterations and 596.27 seconds.\n[DEBUG] 2022-10-03 09:35:09,382 __bs: MainProcess Chudnovsky ... 58,000,000 iterations and 608.84 seconds.\n[DEBUG] 2022-10-03 09:35:16,206 __bs: MainProcess Chudnovsky ... 59,000,000 iterations and 615.66 seconds.\n[DEBUG] 2022-10-03 09:35:24,295 __bs: MainProcess Chudnovsky ... 60,000,000 iterations and 623.75 seconds.\n[DEBUG] 2022-10-03 09:35:31,095 __bs: MainProcess Chudnovsky ... 61,000,000 iterations and 630.55 seconds.\n[DEBUG] 2022-10-03 09:35:52,139 __bs: MainProcess Chudnovsky ... 62,000,000 iterations and 651.60 seconds.\n[DEBUG] 2022-10-03 09:35:58,781 __bs: MainProcess Chudnovsky ... 63,000,000 iterations and 658.24 seconds.\n[DEBUG] 2022-10-03 09:36:07,399 __bs: MainProcess Chudnovsky ... 64,000,000 iterations and 666.86 seconds.\n[DEBUG] 2022-10-03 09:36:12,847 __bs: MainProcess Chudnovsky ... 65,000,000 iterations and 672.30 seconds.\n[DEBUG] 2022-10-03 09:36:19,763 __bs: MainProcess Chudnovsky ... 66,000,000 iterations and 679.22 seconds.\n[DEBUG] 2022-10-03 09:36:32,351 __bs: MainProcess Chudnovsky ... 67,000,000 iterations and 691.81 seconds.\n[DEBUG] 2022-10-03 09:36:39,078 __bs: MainProcess Chudnovsky ... 68,000,000 iterations and 698.53 seconds.\n[DEBUG] 2022-10-03 09:36:47,830 __bs: MainProcess Chudnovsky ... 69,000,000 iterations and 707.29 seconds.\n[DEBUG] 2022-10-03 09:36:54,701 __bs: MainProcess Chudnovsky ... 70,000,000 iterations and 714.16 seconds.\n[DEBUG] 2022-10-03 09:39:39,357 __bs: MainProcess Chudnovsky ... 71,000,000 iterations and 878.81 seconds.\n[DEBUG] 2022-10-03 09:39:46,199 __bs: MainProcess Chudnovsky ... 72,000,000 iterations and 885.66 seconds.\n[DEBUG] 2022-10-03 09:39:54,956 __bs: MainProcess Chudnovsky ... 73,000,000 iterations and 894.41 seconds.\n[DEBUG] 2022-10-03 09:40:01,639 __bs: MainProcess Chudnovsky ... 74,000,000 iterations and 901.10 seconds.\n[DEBUG] 2022-10-03 09:40:14,219 __bs: MainProcess Chudnovsky ... 75,000,000 iterations and 913.68 seconds.\n[DEBUG] 2022-10-03 09:40:19,680 __bs: MainProcess Chudnovsky ... 76,000,000 iterations and 919.14 seconds.\n[DEBUG] 2022-10-03 09:40:26,625 __bs: MainProcess Chudnovsky ... 77,000,000 iterations and 926.08 seconds.\n[DEBUG] 2022-10-03 09:40:35,212 __bs: MainProcess Chudnovsky ... 78,000,000 iterations and 934.67 seconds.\n[DEBUG] 2022-10-03 09:40:41,914 __bs: MainProcess Chudnovsky ... 79,000,000 iterations and 941.37 seconds.\n[DEBUG] 2022-10-03 09:41:03,218 __bs: MainProcess Chudnovsky ... 80,000,000 iterations and 962.68 seconds.\n[DEBUG] 2022-10-03 09:41:10,213 __bs: MainProcess Chudnovsky ... 81,000,000 iterations and 969.67 seconds.\n[DEBUG] 2022-10-03 09:41:18,344 __bs: MainProcess Chudnovsky ... 82,000,000 iterations and 977.80 seconds.\n[DEBUG] 2022-10-03 09:41:25,261 __bs: MainProcess Chudnovsky ... 83,000,000 iterations and 984.72 seconds.\n[DEBUG] 2022-10-03 09:41:37,663 __bs: MainProcess Chudnovsky ... 84,000,000 iterations and 997.12 seconds.\n[DEBUG] 2022-10-03 09:41:44,680 __bs: MainProcess Chudnovsky ... 85,000,000 iterations and 1004.14 seconds.\n[DEBUG] 2022-10-03 09:41:53,411 __bs: MainProcess Chudnovsky ... 86,000,000 iterations and 1012.87 seconds.\n[DEBUG] 2022-10-03 09:41:58,926 __bs: MainProcess Chudnovsky ... 87,000,000 iterations and 1018.38 seconds.\n[DEBUG] 2022-10-03 09:42:05,858 __bs: MainProcess Chudnovsky ... 88,000,000 iterations and 1025.32 seconds.\n[DEBUG] 2022-10-03 09:42:46,163 __bs: MainProcess Chudnovsky ... 89,000,000 iterations and 1065.62 seconds.\n[DEBUG] 2022-10-03 09:42:53,054 __bs: MainProcess Chudnovsky ... 90,000,000 iterations and 1072.51 seconds.\n[DEBUG] 2022-10-03 09:43:02,030 __bs: MainProcess Chudnovsky ... 91,000,000 iterations and 1081.49 seconds.\n[DEBUG] 2022-10-03 09:43:09,192 __bs: MainProcess Chudnovsky ... 92,000,000 iterations and 1088.65 seconds.\n[DEBUG] 2022-10-03 09:43:21,533 __bs: MainProcess Chudnovsky ... 93,000,000 iterations and 1100.99 seconds.\n[DEBUG] 2022-10-03 09:43:28,643 __bs: MainProcess Chudnovsky ... 94,000,000 iterations and 1108.10 seconds.\n[DEBUG] 2022-10-03 09:43:37,372 __bs: MainProcess Chudnovsky ... 95,000,000 iterations and 1116.83 seconds.\n[DEBUG] 2022-10-03 09:43:44,558 __bs: MainProcess Chudnovsky ... 96,000,000 iterations and 1124.02 seconds.\n[DEBUG] 2022-10-03 09:44:06,555 __bs: MainProcess Chudnovsky ... 97,000,000 iterations and 1146.01 seconds.\n[DEBUG] 2022-10-03 09:44:12,220 __bs: MainProcess Chudnovsky ... 98,000,000 iterations and 1151.68 seconds.\n[DEBUG] 2022-10-03 09:44:19,278 __bs: MainProcess Chudnovsky ... 99,000,000 iterations and 1158.74 seconds.\n[DEBUG] 2022-10-03 09:44:28,323 __bs: MainProcess Chudnovsky ... 100,000,000 iterations and 1167.78 seconds.\n[DEBUG] 2022-10-03 09:44:35,211 __bs: MainProcess Chudnovsky ... 101,000,000 iterations and 1174.67 seconds.\n[DEBUG] 2022-10-03 09:44:48,331 __bs: MainProcess Chudnovsky ... 102,000,000 iterations and 1187.79 seconds.\n[DEBUG] 2022-10-03 09:44:54,835 __bs: MainProcess Chudnovsky ... 103,000,000 iterations and 1194.29 seconds.\n[DEBUG] 2022-10-03 09:45:03,869 __bs: MainProcess Chudnovsky ... 104,000,000 iterations and 1203.33 seconds.\n[DEBUG] 2022-10-03 09:45:10,967 __bs: MainProcess Chudnovsky ... 105,000,000 iterations and 1210.42 seconds.\n[DEBUG] 2022-10-03 09:46:32,760 __bs: MainProcess Chudnovsky ... 106,000,000 iterations and 1292.22 seconds.\n[DEBUG] 2022-10-03 09:46:39,872 __bs: MainProcess Chudnovsky ... 107,000,000 iterations and 1299.33 seconds.\n[DEBUG] 2022-10-03 09:46:48,948 __bs: MainProcess Chudnovsky ... 108,000,000 iterations and 1308.41 seconds.\n[DEBUG] 2022-10-03 09:46:54,611 __bs: MainProcess Chudnovsky ... 109,000,000 iterations and 1314.07 seconds.\n[DEBUG] 2022-10-03 09:47:01,727 __bs: MainProcess Chudnovsky ... 110,000,000 iterations and 1321.18 seconds.\n[DEBUG] 2022-10-03 09:47:14,525 __bs: MainProcess Chudnovsky ... 111,000,000 iterations and 1333.98 seconds.\n[DEBUG] 2022-10-03 09:47:21,682 __bs: MainProcess Chudnovsky ... 112,000,000 iterations and 1341.14 seconds.\n[DEBUG] 2022-10-03 09:47:30,610 __bs: MainProcess Chudnovsky ... 113,000,000 iterations and 1350.07 seconds.\n[DEBUG] 2022-10-03 09:47:37,176 __bs: MainProcess Chudnovsky ... 114,000,000 iterations and 1356.63 seconds.\n[DEBUG] 2022-10-03 09:47:59,642 __bs: MainProcess Chudnovsky ... 115,000,000 iterations and 1379.10 seconds.\n[DEBUG] 2022-10-03 09:48:06,702 __bs: MainProcess Chudnovsky ... 116,000,000 iterations and 1386.16 seconds.\n[DEBUG] 2022-10-03 09:48:15,483 __bs: MainProcess Chudnovsky ... 117,000,000 iterations and 1394.94 seconds.\n[DEBUG] 2022-10-03 09:48:22,537 __bs: MainProcess Chudnovsky ... 118,000,000 iterations and 1401.99 seconds.\n[DEBUG] 2022-10-03 09:48:35,714 __bs: MainProcess Chudnovsky ... 119,000,000 iterations and 1415.17 seconds.\n[DEBUG] 2022-10-03 09:48:41,321 __bs: MainProcess Chudnovsky ... 120,000,000 iterations and 1420.78 seconds.\n[DEBUG] 2022-10-03 09:48:48,408 __bs: MainProcess Chudnovsky ... 121,000,000 iterations and 1427.87 seconds.\n[DEBUG] 2022-10-03 09:48:57,138 __bs: MainProcess Chudnovsky ... 122,000,000 iterations and 1436.60 seconds.\n[DEBUG] 2022-10-03 09:49:04,328 __bs: MainProcess Chudnovsky ... 123,000,000 iterations and 1443.79 seconds.\n[DEBUG] 2022-10-03 09:49:46,274 __bs: MainProcess Chudnovsky ... 124,000,000 iterations and 1485.73 seconds.\n[DEBUG] 2022-10-03 09:49:52,833 __bs: MainProcess Chudnovsky ... 125,000,000 iterations and 1492.29 seconds.\n[DEBUG] 2022-10-03 09:50:01,786 __bs: MainProcess Chudnovsky ... 126,000,000 iterations and 1501.24 seconds.\n[DEBUG] 2022-10-03 09:50:08,975 __bs: MainProcess Chudnovsky ... 127,000,000 iterations and 1508.43 seconds.\n[DEBUG] 2022-10-03 09:50:21,850 __bs: MainProcess Chudnovsky ... 128,000,000 iterations and 1521.31 seconds.\n[DEBUG] 2022-10-03 09:50:28,962 __bs: MainProcess Chudnovsky ... 129,000,000 iterations and 1528.42 seconds.\n[DEBUG] 2022-10-03 09:50:34,594 __bs: MainProcess Chudnovsky ... 130,000,000 iterations and 1534.05 seconds.\n[DEBUG] 2022-10-03 09:50:43,647 __bs: MainProcess Chudnovsky ... 131,000,000 iterations and 1543.10 seconds.\n[DEBUG] 2022-10-03 09:50:50,724 __bs: MainProcess Chudnovsky ... 132,000,000 iterations and 1550.18 seconds.\n[DEBUG] 2022-10-03 09:51:12,742 __bs: MainProcess Chudnovsky ... 133,000,000 iterations and 1572.20 seconds.\n[DEBUG] 2022-10-03 09:51:19,799 __bs: MainProcess Chudnovsky ... 134,000,000 iterations and 1579.26 seconds.\n[DEBUG] 2022-10-03 09:51:28,824 __bs: MainProcess Chudnovsky ... 135,000,000 iterations and 1588.28 seconds.\n[DEBUG] 2022-10-03 09:51:35,324 __bs: MainProcess Chudnovsky ... 136,000,000 iterations and 1594.78 seconds.\n[DEBUG] 2022-10-03 09:51:48,419 __bs: MainProcess Chudnovsky ... 137,000,000 iterations and 1607.88 seconds.\n[DEBUG] 2022-10-03 09:51:55,634 __bs: MainProcess Chudnovsky ... 138,000,000 iterations and 1615.09 seconds.\n[DEBUG] 2022-10-03 09:52:04,435 __bs: MainProcess Chudnovsky ... 139,000,000 iterations and 1623.89 seconds.\n[DEBUG] 2022-10-03 09:52:11,583 __bs: MainProcess Chudnovsky ... 140,000,000 iterations and 1631.04 seconds.\n[DEBUG] 2022-10-03 09:52:17,222 __bs: MainProcess Chudnovsky ... 141,000,000 iterations and 1636.68 seconds.\n[DEBUG] 2022-10-03 10:02:43,939 compute: MainProcess Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n calulation Done! 141,027,339 iterations and 2263.39 seconds.\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 10:09:07,119 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 10 Chudnovsky brothers 1988 \n π = (Q(0, N) / 12T(0, N) + 12AQ(0, N))**(C**(3/2))\n \n[INFO] 2022-10-03 10:09:07,120 <module>: MainProcess Calculation took 141,027,339 iterations and 0:44:06.398345.\n python pi-pourri.py -v -d 1,000,000,000 -a 11\n[INFO] 2022-10-03 14:33:34,729 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-03 14:33:34,729 compute: MainProcess Starting const_pi() function from the gmpy2 library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-03 15:46:46,575 compute: MainProcess const_pi() function from the gmpy2 library calulation Done! 1 iterations and 4391.85 seconds.\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 11 const_pi() function from the gmpy2 library \n[INFO] 2022-10-03 15:46:46,575 <module>: MainProcess Calculation took 1 iterations and 1:13:11.845652.\n python pi-pourri.py -v -a 12 -d 1,000,000,000 \n[INFO] 2022-10-04 09:10:37,085 <module>: MainProcess Computing π to 1,000,000,000 digits.\n[DEBUG] 2022-10-04 09:10:37,085 compute: MainProcess Starting mp.pi() function from the mpmath library formula to 1,000,000,000 decimal places\n[DEBUG] 2022-10-04 10:01:25,321 compute: MainProcess mp.pi() function from the mpmath library calulation Done! 1 iterations and 3048.22 seconds.\n[INFO] 2022-10-04 10:01:25,338 <module>: MainProcess Last 5 digits of π were 45519 as expected at offset 999,999,995\n[INFO] 2022-10-04 10:01:25,340 <module>: MainProcess Calculated π to 1,000,000,000 digits using a formula of:\n 12 mp.pi() function from the mpmath library \n[INFO] 2022-10-04 10:01:25,343 <module>: MainProcess Calculation took 1 iterations and 0:50:48.250337.\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/19", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13/" ]
24
<p>If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?</p>
[ { "answer_id": 7189396, "author": "RuiDC", "author_id": 521586, "author_profile": "https://Stackoverflow.com/users/521586", "pm_score": 7, "selected": false, "text": "SIGNAL signal sqlstate '45000' set message_text = 'My Error Message';\n delimiter //\nuse test//\ncreate table trigger_test\n(\n id int not null\n)//\ndrop trigger if exists trg_trigger_test_ins //\ncreate trigger trg_trigger_test_ins before insert on trigger_test\nfor each row\nbegin\n declare msg varchar(128);\n if new.id < 0 then\n set msg = concat('MyTriggerError: Trying to insert a negative value in trigger_test: ', cast(new.id as char));\n signal sqlstate '45000' set message_text = msg;\n end if;\nend\n//\n\ndelimiter ;\n-- run the following as seperate statements:\ninsert into trigger_test values (1), (-1), (2); -- everything fails as one row is bad\nselect * from trigger_test;\ninsert into trigger_test values (1); -- succeeds as expected\ninsert into trigger_test values (-1); -- fails as expected\nselect * from trigger_test;\n" }, { "answer_id": 9046539, "author": "el.atomo", "author_id": 831797, "author_profile": "https://Stackoverflow.com/users/831797", "pm_score": 5, "selected": false, "text": "table_name doesn't exist table_name DELIMITER $$\n-- before inserting new id\nDROP TRIGGER IF EXISTS before_insert_id$$\nCREATE TRIGGER before_insert_id\n BEFORE INSERT ON test FOR EACH ROW\n BEGIN\n -- condition to check\n IF NEW.id < 0 THEN\n -- hack to solve absence of SIGNAL/prepared statements in triggers\n UPDATE `Error: invalid_id_test` SET x=1;\n END IF;\n END$$\n\nDELIMITER ;\n DELIMITER $$\n-- my_signal procedure\nCREATE PROCEDURE `my_signal`(in_errortext VARCHAR(255))\nBEGIN\n SET @sql=CONCAT('UPDATE `', in_errortext, '` SET x=1');\n PREPARE my_signal_stmt FROM @sql;\n EXECUTE my_signal_stmt;\n DEALLOCATE PREPARE my_signal_stmt;\nEND$$\n\nCREATE PROCEDURE insert_test(p_id INT)\nBEGIN\n IF NEW.id < 0 THEN\n CALL my_signal('Error: invalid_id_test; Id must be a positive integer');\n ELSE\n INSERT INTO test (id) VALUES (p_id);\n END IF;\nEND$$\nDELIMITER ;\n" }, { "answer_id": 13293014, "author": "Marinos An", "author_id": 1555615, "author_profile": "https://Stackoverflow.com/users/1555615", "pm_score": 4, "selected": false, "text": "create table mysql_error_generator(error_field varchar(64) unique) engine INNODB;\nDELIMITER $$\nCREATE PROCEDURE throwCustomError(IN errorText VARCHAR(44))\nBEGIN\n DECLARE errorWithDate varchar(64);\n select concat(\"[\",DATE_FORMAT(now(),\"%Y%m%d %T\"),\"] \", errorText) into errorWithDate;\n INSERT IGNORE INTO mysql_error_generator(error_field) VALUES (errorWithDate);\n INSERT INTO mysql_error_generator(error_field) VALUES (errorWithDate);\nEND;\n$$\nDELIMITER ;\n\n\ncall throwCustomError(\"Custom error message with log support.\");\n" }, { "answer_id": 36523822, "author": "PhotonFalcon", "author_id": 3088965, "author_profile": "https://Stackoverflow.com/users/3088965", "pm_score": 3, "selected": false, "text": "BEGIN\n -- Force one of the following to be assigned otherwise set required field to null which will throw an error\n IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN\n SET NEW.`required_id_field`=NULL;\n END IF;\nEND\n BEGIN\n -- Force one of the following to be assigned otherwise use signal sqlstate to throw a unique error\n IF (NEW.`nullable_field_1` IS NULL AND NEW.`nullable_field_2` IS NULL) THEN\n SIGNAL SQLSTATE '45000' set message_text='A unique identifier for nullable_field_1 OR nullable_field_2 is required!';\n END IF;\nEND\n" }, { "answer_id": 38924077, "author": "BHUVANESH MOHANKUMAR", "author_id": 456918, "author_profile": "https://Stackoverflow.com/users/456918", "pm_score": 3, "selected": false, "text": "CREATE TRIGGER sample_trigger_msg \n BEFORE INSERT\nFOR EACH ROW\n BEGIN\nIF(NEW.important_value) < (1*2) THEN\n DECLARE dummy INT;\n SELECT \n Enter your Message Here!!!\n INTO dummy \n FROM mytable\n WHERE mytable.id=new.id\nEND IF;\nEND;\n" }, { "answer_id": 62135883, "author": "Bashir", "author_id": 5988526, "author_profile": "https://Stackoverflow.com/users/5988526", "pm_score": 1, "selected": false, "text": "DELIMITER @@\nDROP TRIGGER IF EXISTS trigger_name @@\nCREATE TRIGGER trigger_name \nBEFORE UPDATE ON table_name\nFOR EACH ROW\nBEGIN\n\n --the condition of error is: \n --if NEW update value of the attribute age = 1 and OLD value was 0\n --key word OLD and NEW let you distinguish between the old and new value of an attribute\n\n IF (NEW.state = 1 AND OLD.state = 0) THEN\n signal sqlstate '-20000' set message_text = 'hey it's an error!'; \n END IF;\n\nEND @@ \nDELIMITER ;\n" } ]
2008/08/01
[ "https://Stackoverflow.com/questions/24", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22/" ]

Dataset Card for "stack-exchange-preferences-code"

More Information needed

Downloads last month
50