Datasets:

Modalities:
Text
Formats:
json
Languages:
English
Tags:
code
Libraries:
Datasets
Dask
License:
text
stringlengths
8
267k
meta
dict
Q: How to convert Decimal to Double in C#? I want to assign the decimal variable "trans" to the double variable "this.Opacity". decimal trans = trackBar1.Value / 5000; this.Opacity = trans; When I build the app it gives the following error: Cannot implicitly convert type decimal to double A: Why are you dividing by 5000? Just set the TrackBar's Minimum and Maximum values between 0 and 100 and then divide the Value by 100 for the Opacity percentage. The minimum 20 example below prevents the form from becoming completely invisible: private void Form1_Load(object sender, System.EventArgs e) { TrackBar1.Minimum = 20; TrackBar1.Maximum = 100; TrackBar1.LargeChange = 10; TrackBar1.SmallChange = 1; TrackBar1.TickFrequency = 5; } private void TrackBar1_Scroll(object sender, System.EventArgs e) { this.Opacity = TrackBar1.Value / 100; } A: You have two problems. Firstly, Opacity requires a double, not a decimal value. The compiler is telling you that while there is a conversion between decimal and double, it is an explicit conversion that you need to specify in order for it to work. Secondly, TrackBar.Value is an integer value and dividing an int by an int results in an int no matter what type of variable you assign it to. In this case there is an implicit cast from int to decimal or double, because there is no loss of precision when you do the cast. So the compiler doesn't complain. But the value you get is always 0, presumably, since trackBar.Value is always less than 5000. The solution is to change your code to use double (the native type for Opacity) and do floating point arithmetic by explicitly making the constant a double, which will have the effect of promoting the arithmetic or casting trackBar.Value to double, which will do the same thing or both. You don't need the intermediate variable unless it is used elsewhere. My guess is the compiler would optimize it away anyway. trackBar.Opacity = (double)trackBar.Value / 5000.0; A: In my opinion, it is desirable to be as explicit as possible. This adds clarity to the code and aids your fellow programmers who may eventually read it. In addition to (or instead of) appending a .0 to the number, you can use decimal.ToDouble(). Here are some examples: // Example 1 double transparency = trackBar1.Value/5000; this.Opacity = decimal.ToDouble(transparency); // Example 2 - with inline temp this.Opacity = decimal.ToDouble(trackBar1.Value/5000); A: It sounds like this.Opacity is a double value, and the compiler doesn't like you trying to cram a decimal value into it. A: You should use 5000.0 instead of 5000. A: The Opacity property is of double type: double trans = trackBar1.Value / 5000.0; this.Opacity = trans; or simply: this.Opacity = trackBar1.Value / 5000.0; or: this.Opacity = trackBar1.Value / 5000d; Notice that I am using 5000.0 (or 5000d) to force a double division because trackBar1.Value is an integer and it would perform an integer division and the result would be an integer. A: Assuming you are using WinForms, Form.Opacity is of type double, so you should use: double trans = trackBar1.Value / 5000.0; this.Opacity = trans; Unless you need the value elsewhere, it's simpler to write: this.Opacity = trackBar1.Value / 5000.0; The reason the control doesn't work when you changed your code to simply be a double was because you had: double trans = trackbar1.Value / 5000; which interpreted the 5000 as an integer, and because trackbar1.Value is also an integer your trans value was always zero. By explicitly making the numeric a floating point value by adding the .0 the compiler can now interpret it as a double and perform the proper calculation. A: Since Opacity is a double value, I would just use a double from the outset and not cast at all, but be sure to use a double when dividing so you don't lose any precision: Opacity = trackBar1.Value / 5000.0; A: An explicit cast to double like this isn't necessary: double trans = (double) trackBar1.Value / 5000.0; Identifying the constant as 5000.0 (or as 5000d) is sufficient: double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; A: The best solution is: this.Opacity = decimal.ToDouble(trackBar1.Value/5000); A: OG Fact: Double type represents a wider range of possible values than Decimal. Casting as Double decimal trans = trackBar1.Value / 5000m; this.Opacity = (double) trans; Type Conversion decimal trans = trackBar1.Value / 5000m; this.Opacity = decimal.ToDouble(trans); No explicit Cast/Conversion In this case, adding 'd' in the end of the constant 5000d or ".0" 5000.0 will identify the required Type. When there is no constant in the operation, just multiply your decimal variable by 1.0 or 1d. A: Try the following code: Decimal values decimal d1 = 3234.3434m; Convert to double double r1 = Decimal.ToDouble(d1); A: A more generic answer for the generic question "Decimal vs Double?": Decimal is for monetary calculations to preserve precision. Double is for scientific calculations that do not get affected by small differences. Since Double is a type that is native to the CPU (internal representation is stored in base 2), calculations made with Double perform better than Decimal (which is represented in base 10 internally). A: Your code worked fine in VB.NET because it implicitly does any casts, while C# has both implicit and explicit ones. In C# the conversion from decimal to double is explicit as you lose accuracy. For instance 1.1 can't be accurately expressed as a double, but can as a decimal (see "Floating point numbers - more inaccurate than you think" for the reason why). In VB the conversion was added for you by the compiler: decimal trans = trackBar1.Value / 5000m; this.Opacity = (double) trans; That (double) has to be explicitly stated in C#, but can be implied by VB's more 'forgiving' compiler.
{ "language": "en", "url": "https://stackoverflow.com/questions/4", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "794" }
Q: Why did the width collapse in the percentage width child element in an absolutely positioned parent on Internet Explorer 7? I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to 0 width on IE7, but not on Firefox or Safari. If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works. * *Is there something I'm missing here? *Is there an easy fix for this besides the pixel-based width on the child? *Is there an area of the CSS specification that covers this? A: The div needs to have a defined width: <div id="parent" style="width:230px;"> <div id="child1"></div> <div id="child2"></div> </div> A: Here is a sample code. I think this is what you are looking for. The following code displays exactly the same in Firefox 3 (mac) and IE7. #absdiv { position: absolute; left: 100px; top: 100px; width: 80%; height: 60%; background: #999; } #pctchild { width: 60%; height: 40%; background: #CCC; } #reldiv { position: relative; left: 20px; top: 20px; height: 25px; width: 40%; background: red; } <div id="absdiv"> <div id="reldiv"></div> <div id="pctchild"></div> </div> A: The parent <div> tag doesn't have any width specified. Use it for the child <div> tags, it could be percentage or pixel, but whatever it would be,it should link to its appropriate positions: <div id="MainDiv" style="width:60%;"> <div id="Div1"> ... </div> <div id="Div2"> ... </div> ... </div> A: IE prior to 8 has a temporal aspect to its box model that most notably creates a problem with percentage-based widths. In your case here an absolutely positioned div by default has no width. Its width will be worked out based on the pixel width of its content and will be calculated after the contents are rendered. So at the point, IE encounters and renders your relatively positioned div its parent has a width of 0 hence why it itself collapses to 0. If you would like a more in-depth discussion of this along with lots of working examples, have a gander here. A: Why doesn’t the percentage width child in absolutely positioned parent work in IE7? Because it's Internet Explorer. Is there something I'm missing here? That is, to raise your co-workers' / clients' awareness that IE is not good. Is there an easy fix besides the pixel-based width on the child? Use em units as they are more useful when creating liquid layouts as you can use them for padding and margins as well as font sizes. So your white space grows and shrinks proportionally to your text if it is resized (which is really what you need). I don't think percentages give a finer control than ems; there's nothing to stop you specifying in hundredths of ems (0.01 em) and the browser will interpret as it sees fit. Is there an area of the CSS specification that covers this? None, as far as I remember em's and %'s were intended for font sizes alone back at CSS 1.0. A: I think this has something to do with the way the hasLayout property is implemented in the older browser. Have you tried your code in IE8 to see if works in there, too? IE8 has a Debugger (F12) and can also run in IE7 mode. A: The parent div needs to have a defined width, either in pixels or as a percentage. In Internet Explorer 7, the parent div needs a defined width for child percentage divs to work correctly.
{ "language": "en", "url": "https://stackoverflow.com/questions/6", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "319" }
Q: How do I calculate someone's age based on a DateTime type birthday? Given a DateTime representing a person's birthday, how do I calculate their age in years? A: My suggestion int age = (int) ((DateTime.Now - bday).TotalDays/365.242199); That seems to have the year changing on the right date. (I spot tested up to age 107.) A: Another function, not by me but found on the web and refined it a bit: public static int GetAge(DateTime birthDate) { DateTime n = DateTime.Now; // To avoid a race condition around midnight int age = n.Year - birthDate.Year; if (n.Month < birthDate.Month || (n.Month == birthDate.Month && n.Day < birthDate.Day)) age--; return age; } Just two things that come into my mind: What about people from countries that do not use the Gregorian calendar? DateTime.Now is in the server-specific culture I think. I have absolutely zero knowledge about actually working with Asian calendars and I do not know if there is an easy way to convert dates between calendars, but just in case you're wondering about those Chinese guys from the year 4660 :-) A: I used ScArcher2's solution for an accurate Year calculation of a persons age but I needed to take it further and calculate their Months and Days along with the Years. public static Dictionary<string,int> CurrentAgeInYearsMonthsDays(DateTime? ndtBirthDate, DateTime? ndtReferralDate) { //---------------------------------------------------------------------- // Can't determine age if we don't have a dates. //---------------------------------------------------------------------- if (ndtBirthDate == null) return null; if (ndtReferralDate == null) return null; DateTime dtBirthDate = Convert.ToDateTime(ndtBirthDate); DateTime dtReferralDate = Convert.ToDateTime(ndtReferralDate); //---------------------------------------------------------------------- // Create our Variables //---------------------------------------------------------------------- Dictionary<string, int> dYMD = new Dictionary<string,int>(); int iNowDate, iBirthDate, iYears, iMonths, iDays; string sDif = ""; //---------------------------------------------------------------------- // Store off current date/time and DOB into local variables //---------------------------------------------------------------------- iNowDate = int.Parse(dtReferralDate.ToString("yyyyMMdd")); iBirthDate = int.Parse(dtBirthDate.ToString("yyyyMMdd")); //---------------------------------------------------------------------- // Calculate Years //---------------------------------------------------------------------- sDif = (iNowDate - iBirthDate).ToString(); iYears = int.Parse(sDif.Substring(0, sDif.Length - 4)); //---------------------------------------------------------------------- // Store Years in Return Value //---------------------------------------------------------------------- dYMD.Add("Years", iYears); //---------------------------------------------------------------------- // Calculate Months //---------------------------------------------------------------------- if (dtBirthDate.Month > dtReferralDate.Month) iMonths = 12 - dtBirthDate.Month + dtReferralDate.Month - 1; else iMonths = dtBirthDate.Month - dtReferralDate.Month; //---------------------------------------------------------------------- // Store Months in Return Value //---------------------------------------------------------------------- dYMD.Add("Months", iMonths); //---------------------------------------------------------------------- // Calculate Remaining Days //---------------------------------------------------------------------- if (dtBirthDate.Day > dtReferralDate.Day) //Logic: Figure out the days in month previous to the current month, or the admitted month. // 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. // then take the referral date and simply add the number of days the person has lived this month. //If referral date is january, we need to go back to the following year's December to get the days in that month. if (dtReferralDate.Month == 1) iDays = DateTime.DaysInMonth(dtReferralDate.Year - 1, 12) - dtBirthDate.Day + dtReferralDate.Day; else iDays = DateTime.DaysInMonth(dtReferralDate.Year, dtReferralDate.Month - 1) - dtBirthDate.Day + dtReferralDate.Day; else iDays = dtReferralDate.Day - dtBirthDate.Day; //---------------------------------------------------------------------- // Store Days in Return Value //---------------------------------------------------------------------- dYMD.Add("Days", iDays); return dYMD; } A: This is simple and appears to be accurate for my needs. I am making an assumption for the purpose of leap years that regardless of when the person chooses to celebrate the birthday they are not technically a year older until 365 days have passed since their last birthday (i.e 28th February does not make them a year older). DateTime now = DateTime.Today; DateTime birthday = new DateTime(1991, 02, 03);//3rd feb int age = now.Year - birthday.Year; if (now.Month < birthday.Month || (now.Month == birthday.Month && now.Day < birthday.Day))//not had bday this year yet age--; return age; A: I've made one small change to Mark Soen's answer: I've rewriten the third line so that the expression can be parsed a bit more easily. public int AgeInYears(DateTime bday) { DateTime now = DateTime.Today; int age = now.Year - bday.Year; if (bday.AddYears(age) > now) age--; return age; } I've also made it into a function for the sake of clarity. A: === Common Saying (from months to years old) === If you just for common use, here is the code as your information: DateTime today = DateTime.Today; DateTime bday = DateTime.Parse("2016-2-14"); int age = today.Year - bday.Year; var unit = ""; if (bday > today.AddYears(-age)) { age--; } if (age == 0) // Under one year old { age = today.Month - bday.Month; age = age <= 0 ? (12 + age) : age; // The next year before birthday age = today.Day - bday.Day >= 0 ? age : --age; // Before the birthday.day unit = "month"; } else { unit = "year"; } if (age > 1) { unit = unit + "s"; } The test result as below: The birthday: 2016-2-14 2016-2-15 => age=0, unit=month; 2016-5-13 => age=2, unit=months; 2016-5-14 => age=3, unit=months; 2016-6-13 => age=3, unit=months; 2016-6-15 => age=4, unit=months; 2017-1-13 => age=10, unit=months; 2017-1-14 => age=11, unit=months; 2017-2-13 => age=11, unit=months; 2017-2-14 => age=1, unit=year; 2017-2-15 => age=1, unit=year; 2017-3-13 => age=1, unit=year; 2018-1-13 => age=1, unit=year; 2018-1-14 => age=1, unit=year; 2018-2-13 => age=1, unit=year; 2018-2-14 => age=2, unit=years; A: private int GetYearDiff(DateTime start, DateTime end) { int diff = end.Year - start.Year; if (end.DayOfYear < start.DayOfYear) { diff -= 1; } return diff; } [Fact] public void GetYearDiff_WhenCalls_ShouldReturnCorrectYearDiff() { //arrange var now = DateTime.Now; //act //assert Assert.Equal(24, GetYearDiff(new DateTime(1992, 7, 9), now)); // passed Assert.Equal(24, GetYearDiff(new DateTime(1992, now.Month, now.Day), now)); // passed Assert.Equal(23, GetYearDiff(new DateTime(1992, 12, 9), now)); // passed } A: 2 Main problems to solve are: 1. Calculate Exact age - in years, months, days, etc. 2. Calculate Generally perceived age - people usually do not care how old they exactly are, they just care when their birthday in the current year is. Solution for 1 is obvious: DateTime birth = DateTime.Parse("1.1.2000"); DateTime today = DateTime.Today; //we usually don't care about birth time TimeSpan age = today - birth; //.NET FCL should guarantee this as precise double ageInDays = age.TotalDays; //total number of days ... also precise double daysInYear = 365.2425; //statistical value for 400 years double ageInYears = ageInDays / daysInYear; //can be shifted ... not so precise Solution for 2 is the one which is not so precise in determing total age, but is perceived as precise by people. People also usually use it, when they calculate their age "manually": DateTime birth = DateTime.Parse("1.1.2000"); DateTime today = DateTime.Today; int age = today.Year - birth.Year; //people perceive their age in years if (today.Month < birth.Month || ((today.Month == birth.Month) && (today.Day < birth.Day))) { age--; //birthday in current year not yet reached, we are 1 year younger ;) //+ no birthday for 29.2. guys ... sorry, just wrong date for birth } Notes to 2.: * *This is my preferred solution *We cannot use DateTime.DayOfYear or TimeSpans, as they shift number of days in leap years *I have put there little more lines for readability Just one more note ... I would create 2 static overloaded methods for it, one for universal usage, second for usage-friendliness: public static int GetAge(DateTime bithDay, DateTime today) { //chosen solution method body } public static int GetAge(DateTime birthDay) { return GetAge(birthDay, DateTime.Now); } A: Wow, I had to give my answer here... There are so many answers for such a simple question. private int CalcularIdade(DateTime dtNascimento) { var nHoje = Convert.ToInt32(DateTime.Today.ToString("yyyyMMdd")); var nAniversario = Convert.ToInt32(dtNascimento.ToString("yyyyMMdd")); double diff = (nHoje - nAniversario) / 10000; var ret = Convert.ToInt32(Math.Truncate(diff)); return ret; } A: The best way that I know of because of leap years and everything is: DateTime birthDate = new DateTime(2000,3,1); int age = (int)Math.Floor((DateTime.Now - birthDate).TotalDays / 365.25D); A: Here's a one-liner: int age = new DateTime(DateTime.Now.Subtract(birthday).Ticks).Year-1; A: It can be this simple: int age = DateTime.Now.AddTicks(0 - dob.Ticks).Year - 1; A: This is the easiest way to answer this in a single line. DateTime Dob = DateTime.Parse("1985-04-24"); int Age = DateTime.MinValue.AddDays(DateTime.Now.Subtract(Dob).TotalHours/24 - 1).Year - 1; This also works for leap years. A: This is the version we use here. It works, and it's fairly simple. It's the same idea as Jeff's but I think it's a little clearer because it separates out the logic for subtracting one, so it's a little easier to understand. public static int GetAge(this DateTime dateOfBirth, DateTime dateAsAt) { return dateAsAt.Year - dateOfBirth.Year - (dateOfBirth.DayOfYear < dateAsAt.DayOfYear ? 0 : 1); } You could expand the ternary operator to make it even clearer, if you think that sort of thing is unclear. Obviously this is done as an extension method on DateTime, but clearly you can grab that one line of code that does the work and put it anywhere. Here we have another overload of the Extension method that passes in DateTime.Now, just for completeness. A: Here is a test snippet: DateTime bDay = new DateTime(2000, 2, 29); DateTime now = new DateTime(2009, 2, 28); MessageBox.Show(string.Format("Test {0} {1} {2}", CalculateAgeWrong1(bDay, now), // outputs 9 CalculateAgeWrong2(bDay, now), // outputs 9 CalculateAgeCorrect(bDay, now), // outputs 8 CalculateAgeCorrect2(bDay, now))); // outputs 8 Here you have the methods: public int CalculateAgeWrong1(DateTime birthDate, DateTime now) { return new DateTime(now.Subtract(birthDate).Ticks).Year - 1; } public int CalculateAgeWrong2(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; if (now < birthDate.AddYears(age)) age--; return age; } public int CalculateAgeCorrect(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--; return age; } public int CalculateAgeCorrect2(DateTime birthDate, DateTime now) { int age = now.Year - birthDate.Year; // For leap years we need this if (birthDate > now.AddYears(-age)) age--; // Don't use: // if (birthDate.AddYears(age) > now) // age--; return age; } A: This may work: public override bool IsValid(DateTime value) { _dateOfBirth = value; var yearsOld = (double) (DateTime.Now.Subtract(_dateOfBirth).TotalDays/365); if (yearsOld > 18) return true; return false; } A: Here's a little code sample for C# I knocked up, be careful around the edge cases specifically leap years, not all the above solutions take them into account. Pushing the answer out as a DateTime can cause problems as you could end up trying to put too many days into a specific month e.g. 30 days in Feb. public string LoopAge(DateTime myDOB, DateTime FutureDate) { int years = 0; int months = 0; int days = 0; DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1); DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1); while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate) { months++; if (months > 12) { years++; months = months - 12; } } if (FutureDate.Day >= myDOB.Day) { days = days + FutureDate.Day - myDOB.Day; } else { months--; if (months < 0) { years--; months = months + 12; } days = days + (DateTime.DaysInMonth(FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month) + FutureDate.Day) - myDOB.Day; } //add an extra day if the dob is a leap day if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29) { //but only if the future date is less than 1st March if(FutureDate >= new DateTime(FutureDate.Year, 3,1)) days++; } return "Years: " + years + " Months: " + months + " Days: " + days; } A: Here's a DateTime extender that adds the age calculation to the DateTime object. public static class AgeExtender { public static int GetAge(this DateTime dt) { int d = int.Parse(dt.ToString("yyyyMMdd")); int t = int.Parse(DateTime.Today.ToString("yyyyMMdd")); return (t-d)/10000; } } A: public string GetAge(this DateTime birthdate, string ageStrinFormat = null) { var date = DateTime.Now.AddMonths(-birthdate.Month).AddDays(-birthdate.Day); return string.Format(ageStrinFormat ?? "{0}/{1}/{2}", (date.Year - birthdate.Year), date.Month, date.Day); } A: This gives "more detail" to this question. Maybe this is what you're looking for DateTime birth = new DateTime(1974, 8, 29); DateTime today = DateTime.Now; TimeSpan span = today - birth; DateTime age = DateTime.MinValue + span; // Make adjustment due to MinValue equalling 1/1/1 int years = age.Year - 1; int months = age.Month - 1; int days = age.Day - 1; // Print out not only how many years old they are but give months and days as well Console.Write("{0} years, {1} months, {2} days", years, months, days); A: I use this: public static class DateTimeExtensions { public static int Age(this DateTime birthDate) { return Age(birthDate, DateTime.Now); } public static int Age(this DateTime birthDate, DateTime offsetDate) { int result=0; result = offsetDate.Year - birthDate.Year; if (offsetDate.DayOfYear < birthDate.DayOfYear) { result--; } return result; } } A: Here's yet another answer: public static int AgeInYears(DateTime birthday, DateTime today) { return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372; } This has been extensively unit-tested. It does look a bit "magic". The number 372 is the number of days there would be in a year if every month had 31 days. The explanation of why it works (lifted from here) is: Let's set 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 We know that what we need is either Yn-Yb if the date has already been reached, Yn-Yb-1 if it has not. a) If Mn<Mb, we have -341 <= 31*(Mn-Mb) <= -31 and -30 <= Dn-Db <= 30 -371 <= 31*(Mn - Mb) + (Dn - Db) <= -1 With integer division (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 b) If Mn=Mb and Dn<Db, we have 31*(Mn - Mb) = 0 and -30 <= Dn-Db <= -1 With integer division, again (31*(Mn - Mb) + (Dn - Db)) / 372 = -1 c) If Mn>Mb, we have 31 <= 31*(Mn-Mb) <= 341 and -30 <= Dn-Db <= 30 1 <= 31*(Mn - Mb) + (Dn - Db) <= 371 With integer division (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 d) If Mn=Mb and Dn>Db, we have 31*(Mn - Mb) = 0 and 1 <= Dn-Db <= 30 With integer division, again (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 e) If Mn=Mb and Dn=Db, we have 31*(Mn - Mb) + Dn-Db = 0 and therefore (31*(Mn - Mb) + (Dn - Db)) / 372 = 0 A: I have created a SQL Server User Defined Function to calculate someone's age, given their birthdate. This is useful when you need it as part of a query: using System; using System.Data; using System.Data.Sql; using System.Data.SqlClient; using System.Data.SqlTypes; using Microsoft.SqlServer.Server; public partial class UserDefinedFunctions { [SqlFunction(DataAccess = DataAccessKind.Read)] public static SqlInt32 CalculateAge(string strBirthDate) { DateTime dtBirthDate = new DateTime(); dtBirthDate = Convert.ToDateTime(strBirthDate); DateTime dtToday = DateTime.Now; // get the difference in years int years = dtToday.Year - dtBirthDate.Year; // subtract another year if we're before the // birth day in the current year if (dtToday.Month < dtBirthDate.Month || (dtToday.Month == dtBirthDate.Month && dtToday.Day < dtBirthDate.Day)) years=years-1; int intCustomerAge = years; return intCustomerAge; } }; A: I think the TimeSpan has all that we need in it, without having to resort to 365.25 (or any other approximation). Expanding on Aug's example: DateTime myBD = new DateTime(1980, 10, 10); TimeSpan difference = DateTime.Now.Subtract(myBD); textBox1.Text = difference.Years + " years " + difference.Months + " Months " + difference.Days + " days"; A: I want to add Hebrew calendar calculations (or other System.Globalization calendar can be used in the same way), using rewrited functions from this thread: Public Shared Function CalculateAge(BirthDate As DateTime) As Integer Dim HebCal As New System.Globalization.HebrewCalendar () Dim now = DateTime.Now() Dim iAge = HebCal.GetYear(now) - HebCal.GetYear(BirthDate) Dim iNowMonth = HebCal.GetMonth(now), iBirthMonth = HebCal.GetMonth(BirthDate) If iNowMonth < iBirthMonth Or (iNowMonth = iBirthMonth AndAlso HebCal.GetDayOfMonth(now) < HebCal.GetDayOfMonth(BirthDate)) Then iAge -= 1 Return iAge End Function A: Try this solution, it's working. int age = (Int32.Parse(DateTime.Today.ToString("yyyyMMdd")) - Int32.Parse(birthday.ToString("yyyyMMdd rawrrr"))) / 10000; A: Here is a function that is serving me well. No calculations , very simple. public static string ToAge(this DateTime dob, DateTime? toDate = null) { if (!toDate.HasValue) toDate = DateTime.Now; var now = toDate.Value; if (now.CompareTo(dob) < 0) return "Future date"; int years = now.Year - dob.Year; int months = now.Month - dob.Month; int days = now.Day - dob.Day; if (days < 0) { months--; days = DateTime.DaysInMonth(dob.Year, dob.Month) - dob.Day + now.Day; } if (months < 0) { years--; months = 12 + months; } return string.Format("{0} year(s), {1} month(s), {2} days(s)", years, months, days); } And here is a unit test: [Test] public void ToAgeTests() { var date = new DateTime(2000, 1, 1); Assert.AreEqual("0 year(s), 0 month(s), 1 days(s)", new DateTime(1999, 12, 31).ToAge(date)); Assert.AreEqual("0 year(s), 0 month(s), 0 days(s)", new DateTime(2000, 1, 1).ToAge(date)); Assert.AreEqual("1 year(s), 0 month(s), 0 days(s)", new DateTime(1999, 1, 1).ToAge(date)); Assert.AreEqual("0 year(s), 11 month(s), 0 days(s)", new DateTime(1999, 2, 1).ToAge(date)); Assert.AreEqual("0 year(s), 10 month(s), 25 days(s)", new DateTime(1999, 2, 4).ToAge(date)); Assert.AreEqual("0 year(s), 10 month(s), 1 days(s)", new DateTime(1999, 2, 28).ToAge(date)); date = new DateTime(2000, 2, 15); Assert.AreEqual("0 year(s), 0 month(s), 28 days(s)", new DateTime(2000, 1, 18).ToAge(date)); } A: I have used the following for this issue. I know it's not very elegant, but it's working. DateTime zeroTime = new DateTime(1, 1, 1); var date1 = new DateTime(1983, 03, 04); var date2 = DateTime.Now; var dif = date2 - date1; int years = (zeroTime + dif).Year - 1; Log.DebugFormat("Years -->{0}", years); A: I often count on my fingers. I need to look at a calendar to work out when things change. So that's what I'd do in my code: int AgeNow(DateTime birthday) { return AgeAt(DateTime.Now, birthday); } int AgeAt(DateTime now, DateTime birthday) { return AgeAt(now, birthday, CultureInfo.CurrentCulture.Calendar); } int AgeAt(DateTime now, DateTime birthday, Calendar calendar) { // My age has increased on the morning of my // birthday even though I was born in the evening. now = now.Date; birthday = birthday.Date; var age = 0; if (now <= birthday) return age; // I am zero now if I am to be born tomorrow. while (calendar.AddYears(birthday, age + 1) <= now) { age++; } return age; } Running this through in LINQPad gives this: PASSED: someone born on 28 February 1964 is age 4 on 28 February 1968 PASSED: someone born on 29 February 1964 is age 3 on 28 February 1968 PASSED: someone born on 31 December 2016 is age 0 on 01 January 2017 Code in LINQPad is here. A: Just use: (DateTime.Now - myDate).TotalHours / 8766.0 The current date - myDate = TimeSpan, get total hours and divide in the total hours per year and get exactly the age/months/days... A: I would strongly recommend using a NuGet package called AgeCalculator since there are many things to consider when calculating age (leap years, time component etc) and only two lines of code does not cut it. The library gives you more than just a year. It even takes into consideration the time component at the calculation so you get an accurate age with years, months, days and time components. It is more advanced giving an option to consider Feb 29 in a leap year as Feb 28 in a non-leap year. A: I've spent some time working on this and came up with this to calculate someone's age in years, months and days. I've tested against the Feb 29th problem and leap years and it seems to work, I'd appreciate any feedback: public void LoopAge(DateTime myDOB, DateTime FutureDate) { int years = 0; int months = 0; int days = 0; DateTime tmpMyDOB = new DateTime(myDOB.Year, myDOB.Month, 1); DateTime tmpFutureDate = new DateTime(FutureDate.Year, FutureDate.Month, 1); while (tmpMyDOB.AddYears(years).AddMonths(months) < tmpFutureDate) { months++; if (months > 12) { years++; months = months - 12; } } if (FutureDate.Day >= myDOB.Day) { days = days + FutureDate.Day - myDOB.Day; } else { months--; if (months < 0) { years--; months = months + 12; } days += DateTime.DaysInMonth( FutureDate.AddMonths(-1).Year, FutureDate.AddMonths(-1).Month ) + FutureDate.Day - myDOB.Day; } //add an extra day if the dob is a leap day if (DateTime.IsLeapYear(myDOB.Year) && myDOB.Month == 2 && myDOB.Day == 29) { //but only if the future date is less than 1st March if (FutureDate >= new DateTime(FutureDate.Year, 3, 1)) days++; } } A: An easy to understand and simple solution. // Save today's date. var today = DateTime.Today; // Calculate the age. var age = today.Year - birthdate.Year; // Go back to the year in which the person was born in case of a leap year if (birthdate.Date > today.AddYears(-age)) age--; However, this assumes you are looking for the western idea of the age and not using East Asian reckoning. A: Keeping it simple (and possibly stupid:)). DateTime birth = new DateTime(1975, 09, 27, 01, 00, 00, 00); TimeSpan ts = DateTime.Now - birth; Console.WriteLine("You are approximately " + ts.TotalSeconds.ToString() + " seconds old."); A: The simplest way I've ever found is this. It works correctly for the US and western europe locales. Can't speak to other locales, especially places like China. 4 extra compares, at most, following the initial computation of age. public int AgeInYears(DateTime birthDate, DateTime referenceDate) { Debug.Assert(referenceDate >= birthDate, "birth date must be on or prior to the reference date"); DateTime birth = birthDate.Date; DateTime reference = referenceDate.Date; int years = (reference.Year - birth.Year); // // an offset of -1 is applied if the birth date has // not yet occurred in the current year. // if (reference.Month > birth.Month); else if (reference.Month < birth.Month) --years; else // in birth month { if (reference.Day < birth.Day) --years; } return years ; } I was looking over the answers to this and noticed that nobody has made reference to regulatory/legal implications of leap day births. For instance, per Wikipedia, if you're born on February 29th in various jurisdictions, you're non-leap year birthday varies: * *In the United Kingdom and Hong Kong: it's the ordinal day of the year, so the next day, March 1st is your birthday. *In New Zealand: it's the previous day, February 28th for the purposes of driver licencing, and March 1st for other purposes. *Taiwan: it's February 28th. And as near as I can tell, in the US, the statutes are silent on the matter, leaving it up to the common law and to how various regulatory bodies define things in their regulations. To that end, an improvement: public enum LeapDayRule { OrdinalDay = 1 , LastDayOfMonth = 2 , } static int ComputeAgeInYears(DateTime birth, DateTime reference, LeapYearBirthdayRule ruleInEffect) { bool isLeapYearBirthday = CultureInfo.CurrentCulture.Calendar.IsLeapDay(birth.Year, birth.Month, birth.Day); DateTime cutoff; if (isLeapYearBirthday && !DateTime.IsLeapYear(reference.Year)) { switch (ruleInEffect) { case LeapDayRule.OrdinalDay: cutoff = new DateTime(reference.Year, 1, 1) .AddDays(birth.DayOfYear - 1); break; case LeapDayRule.LastDayOfMonth: cutoff = new DateTime(reference.Year, birth.Month, 1) .AddMonths(1) .AddDays(-1); break; default: throw new InvalidOperationException(); } } else { cutoff = new DateTime(reference.Year, birth.Month, birth.Day); } int age = (reference.Year - birth.Year) + (reference >= cutoff ? 0 : -1); return age < 0 ? 0 : age; } It should be noted that this code assumes: * *A western (European) reckoning of age, and *A calendar, like the Gregorian calendar that inserts a single leap day at the end of a month. A: Do we need to consider people who is smaller than 1 year? as Chinese culture, we describe small babies' age as 2 months or 4 weeks. Below is my implementation, it is not as simple as what I imagined, especially to deal with date like 2/28. public static string HowOld(DateTime birthday, DateTime now) { if (now < birthday) throw new ArgumentOutOfRangeException("birthday must be less than now."); TimeSpan diff = now - birthday; int diffDays = (int)diff.TotalDays; if (diffDays > 7)//year, month and week { int age = now.Year - birthday.Year; if (birthday > now.AddYears(-age)) age--; if (age > 0) { return age + (age > 1 ? " years" : " year"); } else {// month and week DateTime d = birthday; int diffMonth = 1; while (d.AddMonths(diffMonth) <= now) { diffMonth++; } age = diffMonth-1; if (age == 1 && d.Day > now.Day) age--; if (age > 0) { return age + (age > 1 ? " months" : " month"); } else { age = diffDays / 7; return age + (age > 1 ? " weeks" : " week"); } } } else if (diffDays > 0) { int age = diffDays; return age + (age > 1 ? " days" : " day"); } else { int age = diffDays; return "just born"; } } This implementation has passed below test cases. [TestMethod] public void TestAge() { string age = HowOld(new DateTime(2011, 1, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("1 year", age); age = HowOld(new DateTime(2011, 11, 30), new DateTime(2012, 11, 30)); Assert.AreEqual("1 year", age); age = HowOld(new DateTime(2001, 1, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("11 years", age); age = HowOld(new DateTime(2012, 1, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("10 months", age); age = HowOld(new DateTime(2011, 12, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("11 months", age); age = HowOld(new DateTime(2012, 10, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("1 month", age); age = HowOld(new DateTime(2008, 2, 28), new DateTime(2009, 2, 28)); Assert.AreEqual("1 year", age); age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 2, 28)); Assert.AreEqual("11 months", age); age = HowOld(new DateTime(2008, 3, 28), new DateTime(2009, 3, 28)); Assert.AreEqual("1 year", age); age = HowOld(new DateTime(2009, 1, 28), new DateTime(2009, 2, 28)); Assert.AreEqual("1 month", age); age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1)); Assert.AreEqual("1 month", age); // NOTE. // new DateTime(2008, 1, 31).AddMonths(1) == new DateTime(2009, 2, 28); // new DateTime(2008, 1, 28).AddMonths(1) == new DateTime(2009, 2, 28); age = HowOld(new DateTime(2009, 1, 31), new DateTime(2009, 2, 28)); Assert.AreEqual("4 weeks", age); age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 2, 28)); Assert.AreEqual("3 weeks", age); age = HowOld(new DateTime(2009, 2, 1), new DateTime(2009, 3, 1)); Assert.AreEqual("1 month", age); age = HowOld(new DateTime(2012, 11, 5), new DateTime(2012, 11, 30)); Assert.AreEqual("3 weeks", age); age = HowOld(new DateTime(2012, 11, 1), new DateTime(2012, 11, 30)); Assert.AreEqual("4 weeks", age); age = HowOld(new DateTime(2012, 11, 20), new DateTime(2012, 11, 30)); Assert.AreEqual("1 week", age); age = HowOld(new DateTime(2012, 11, 25), new DateTime(2012, 11, 30)); Assert.AreEqual("5 days", age); age = HowOld(new DateTime(2012, 11, 29), new DateTime(2012, 11, 30)); Assert.AreEqual("1 day", age); age = HowOld(new DateTime(2012, 11, 30), new DateTime(2012, 11, 30)); Assert.AreEqual("just born", age); age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 2, 28)); Assert.AreEqual("8 years", age); age = HowOld(new DateTime(2000, 2, 29), new DateTime(2009, 3, 1)); Assert.AreEqual("9 years", age); Exception e = null; try { age = HowOld(new DateTime(2012, 12, 1), new DateTime(2012, 11, 30)); } catch (ArgumentOutOfRangeException ex) { e = ex; } Assert.IsTrue(e != null); } Hope it's helpful. A: This is not a direct answer, but more of a philosophical reasoning about the problem at hand from a quasi-scientific point of view. I would argue that the question does not specify the unit nor culture in which to measure age, most answers seem to assume an integer annual representation. The SI-unit for time is second, ergo the correct generic answer should be (of course assuming normalized DateTime and taking no regard whatsoever to relativistic effects): var lifeInSeconds = (DateTime.Now.Ticks - then.Ticks)/TickFactor; In the Christian way of calculating age in years: var then = ... // Then, in this case the birthday var now = DateTime.UtcNow; int age = now.Year - then.Year; if (now.AddYears(-age) < then) age--; In finance there is a similar problem when calculating something often referred to as the Day Count Fraction, which roughly is a number of years for a given period. And the age issue is really a time measuring issue. Example for the actual/actual (counting all days "correctly") convention: DateTime start, end = .... // Whatever, assume start is before end double startYearContribution = 1 - (double) start.DayOfYear / (double) (DateTime.IsLeapYear(start.Year) ? 366 : 365); double endYearContribution = (double)end.DayOfYear / (double)(DateTime.IsLeapYear(end.Year) ? 366 : 365); double middleContribution = (double) (end.Year - start.Year - 1); double DCF = startYearContribution + endYearContribution + middleContribution; Another quite common way to measure time generally is by "serializing" (the dude who named this date convention must seriously have been trippin'): DateTime start, end = .... // Whatever, assume start is before end int days = (end - start).Days; I wonder how long we have to go before a relativistic age in seconds becomes more useful than the rough approximation of earth-around-sun-cycles during one's lifetime so far :) Or in other words, when a period must be given a location or a function representing motion for itself to be valid :) A: I've created an Age struct, which looks like this: public struct Age : IEquatable<Age>, IComparable<Age> { private readonly int _years; private readonly int _months; private readonly int _days; public int Years { get { return _years; } } public int Months { get { return _months; } } public int Days { get { return _days; } } public Age( int years, int months, int days ) : this() { _years = years; _months = months; _days = days; } public static Age CalculateAge( DateTime dateOfBirth, DateTime date ) { // Here is some logic that ressembles Mike's solution, although it // also takes into account months & days. // Ommitted for brevity. return new Age (years, months, days); } // Ommited Equality, Comparable, GetHashCode, functionality for brevity. } A: Here is a very simple and easy to follow example. private int CalculateAge() { //get birthdate DateTime dtBirth = Convert.ToDateTime(BirthDatePicker.Value); int byear = dtBirth.Year; int bmonth = dtBirth.Month; int bday = dtBirth.Day; DateTime dtToday = DateTime.Now; int tYear = dtToday.Year; int tmonth = dtToday.Month; int tday = dtToday.Day; int age = tYear - byear; if (bmonth < tmonth) age--; else if (bmonth == tmonth && bday>tday) { age--; } return age; } A: With fewer conversions and UtcNow, this code can take care of someone born on the Feb 29 in a leap year: public int GetAge(DateTime DateOfBirth) { var Now = DateTime.UtcNow; return Now.Year - DateOfBirth.Year - ( ( Now.Month > DateOfBirth.Month || (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day) ) ? 0 : 1 ); } A: Just because I don't think the top answer is that clear: public static int GetAgeByLoop(DateTime birthday) { var age = -1; for (var date = birthday; date < DateTime.Today; date = date.AddYears(1)) { age++; } return age; } A: I would simply do this: DateTime birthDay = new DateTime(1990, 05, 23); DateTime age = DateTime.Now - birthDay; This way you can calculate the exact age of a person, down to the millisecond if you want. A: Simple Code var birthYear=1993; var age = DateTime.Now.AddYears(-birthYear).Year; A: Here is the simplest way to calculate someone's age. Calculating someone's age is pretty straightforward, and here's how! In order for the code to work, you need a DateTime object called BirthDate containing the birthday. C# // get the difference in years int years = DateTime.Now.Year - BirthDate.Year; // subtract another year if we're before the // birth day in the current year if (DateTime.Now.Month < BirthDate.Month || (DateTime.Now.Month == BirthDate.Month && DateTime.Now.Day < BirthDate.Day)) years--; VB.NET ' get the difference in years Dim years As Integer = DateTime.Now.Year - BirthDate.Year ' subtract another year if we're before the ' birth day in the current year If DateTime.Now.Month < BirthDate.Month Or (DateTime.Now.Month = BirthDate.Month And DateTime.Now.Day < BirthDate.Day) Then years = years - 1 End If A: var birthDate = ... // DOB var resultDate = DateTime.Now - birthDate; Using resultDate you can apply TimeSpan properties whatever you want to display it. A: TimeSpan diff = DateTime.Now - birthdayDateTime; string age = String.Format("{0:%y} years, {0:%M} months, {0:%d}, days old", diff); I'm not sure how exactly you'd like it returned to you, so I just made a readable string. A: Here is a solution. DateTime dateOfBirth = new DateTime(2000, 4, 18); DateTime currentDate = DateTime.Now; int ageInYears = 0; int ageInMonths = 0; int ageInDays = 0; ageInDays = currentDate.Day - dateOfBirth.Day; ageInMonths = currentDate.Month - dateOfBirth.Month; ageInYears = currentDate.Year - dateOfBirth.Year; if (ageInDays < 0) { ageInDays += DateTime.DaysInMonth(currentDate.Year, currentDate.Month); ageInMonths = ageInMonths--; if (ageInMonths < 0) { ageInMonths += 12; ageInYears--; } } if (ageInMonths < 0) { ageInMonths += 12; ageInYears--; } Console.WriteLine("{0}, {1}, {2}", ageInYears, ageInMonths, ageInDays); A: This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb. public int GetAge(DateTime birthDate) { int age = DateTime.Now.Year - birthDate.Year; if (birthDate.DayOfYear > DateTime.Now.DayOfYear) age--; return age; } A: I have a customized method to calculate age, plus a bonus validation message just in case it helps: public void GetAge(DateTime dob, DateTime now, out int years, out int months, out int days) { years = 0; months = 0; days = 0; DateTime tmpdob = new DateTime(dob.Year, dob.Month, 1); DateTime tmpnow = new DateTime(now.Year, now.Month, 1); while (tmpdob.AddYears(years).AddMonths(months) < tmpnow) { months++; if (months > 12) { years++; months = months - 12; } } if (now.Day >= dob.Day) days = days + now.Day - dob.Day; else { months--; if (months < 0) { years--; months = months + 12; } days += DateTime.DaysInMonth(now.AddMonths(-1).Year, now.AddMonths(-1).Month) + now.Day - dob.Day; } if (DateTime.IsLeapYear(dob.Year) && dob.Month == 2 && dob.Day == 29 && now >= new DateTime(now.Year, 3, 1)) days++; } private string ValidateDate(DateTime dob) //This method will validate the date { int Years = 0; int Months = 0; int Days = 0; GetAge(dob, DateTime.Now, out Years, out Months, out Days); if (Years < 18) message = Years + " is too young. Please try again on your 18th birthday."; else if (Years >= 65) message = Years + " is too old. Date of Birth must not be 65 or older."; else return null; //Denotes validation passed } Method call here and pass out datetime value (MM/dd/yyyy if server set to USA locale). Replace this with anything a messagebox or any container to display: DateTime dob = DateTime.Parse("03/10/1982"); string message = ValidateDate(dob); lbldatemessage.Visible = !StringIsNullOrWhitespace(message); lbldatemessage.Text = message ?? ""; //Ternary if message is null then default to empty string Remember you can format the message any way you like. A: How about this solution? static string CalcAge(DateTime birthDay) { DateTime currentDate = DateTime.Now; int approximateAge = currentDate.Year - birthDay.Year; int daysToNextBirthDay = (birthDay.Month * 30 + birthDay.Day) - (currentDate.Month * 30 + currentDate.Day) ; if (approximateAge == 0 || approximateAge == 1) { int month = Math.Abs(daysToNextBirthDay / 30); int days = Math.Abs(daysToNextBirthDay % 30); if (month == 0) return "Your age is: " + daysToNextBirthDay + " days"; return "Your age is: " + month + " months and " + days + " days"; ; } if (daysToNextBirthDay > 0) return "Your age is: " + --approximateAge + " Years"; return "Your age is: " + approximateAge + " Years"; ; } A: private int GetAge(int _year, int _month, int _day { DateTime yourBirthDate= new DateTime(_year, _month, _day); DateTime todaysDateTime = DateTime.Today; int noOfYears = todaysDateTime.Year - yourBirthDate.Year; if (DateTime.Now.Month < yourBirthDate.Month || (DateTime.Now.Month == yourBirthDate.Month && DateTime.Now.Day < yourBirthDate.Day)) { noOfYears--; } return noOfYears; } A: This classic question is deserving of a Noda Time solution. static int GetAge(LocalDate dateOfBirth) { Instant now = SystemClock.Instance.Now; // The target time zone is important. // It should align with the *current physical location* of the person // you are talking about. When the whereabouts of that person are unknown, // then you use the time zone of the person who is *asking* for the age. // The time zone of birth is irrelevant! DateTimeZone zone = DateTimeZoneProviders.Tzdb["America/New_York"]; LocalDate today = now.InZone(zone).Date; Period period = Period.Between(dateOfBirth, today, PeriodUnits.Years); return (int) period.Years; } Usage: LocalDate dateOfBirth = new LocalDate(1976, 8, 27); int age = GetAge(dateOfBirth); You might also be interested in the following improvements: * *Passing in the clock as an IClock, instead of using SystemClock.Instance, would improve testability. *The target time zone will likely change, so you'd want a DateTimeZone parameter as well. See also my blog post on this subject: Handling Birthdays, and Other Anniversaries A: The simple answer to this is to apply AddYears as shown below because this is the only native method to add years to the 29th of Feb. of leap years and obtain the correct result of the 28th of Feb. for common years. Some feel that 1th of Mar. is the birthday of leaplings but neither .Net nor any official rule supports this, nor does common logic explain why some born in February should have 75% of their birthdays in another month. Further, an Age method lends itself to be added as an extension to DateTime. By this you can obtain the age in the simplest possible way: * *List item int age = birthDate.Age(); public static class DateTimeExtensions { /// <summary> /// Calculates the age in years of the current System.DateTime object today. /// </summary> /// <param name="birthDate">The date of birth</param> /// <returns>Age in years today. 0 is returned for a future date of birth.</returns> public static int Age(this DateTime birthDate) { return Age(birthDate, DateTime.Today); } /// <summary> /// Calculates the age in years of the current System.DateTime object on a later date. /// </summary> /// <param name="birthDate">The date of birth</param> /// <param name="laterDate">The date on which to calculate the age.</param> /// <returns>Age in years on a later day. 0 is returned as minimum.</returns> public static int Age(this DateTime birthDate, DateTime laterDate) { int age; age = laterDate.Year - birthDate.Year; if (age > 0) { age -= Convert.ToInt32(laterDate.Date < birthDate.Date.AddYears(age)); } else { age = 0; } return age; } } Now, run this test: class Program { static void Main(string[] args) { RunTest(); } private static void RunTest() { DateTime birthDate = new DateTime(2000, 2, 28); DateTime laterDate = new DateTime(2011, 2, 27); string iso = "yyyy-MM-dd"; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { 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()); } } Console.ReadKey(); } } The critical date example is this: Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11 Output: { Birth date: 2000-02-28 Later date: 2011-02-27 Age: 10 Birth date: 2000-02-28 Later date: 2011-02-28 Age: 11 Birth date: 2000-02-28 Later date: 2011-03-01 Age: 11 Birth date: 2000-02-29 Later date: 2011-02-27 Age: 10 Birth date: 2000-02-29 Later date: 2011-02-28 Age: 11 Birth date: 2000-02-29 Later date: 2011-03-01 Age: 11 Birth date: 2000-03-01 Later date: 2011-02-27 Age: 10 Birth date: 2000-03-01 Later date: 2011-02-28 Age: 10 Birth date: 2000-03-01 Later date: 2011-03-01 Age: 11 } And for the later date 2012-02-28: { Birth date: 2000-02-28 Later date: 2012-02-28 Age: 12 Birth date: 2000-02-28 Later date: 2012-02-29 Age: 12 Birth date: 2000-02-28 Later date: 2012-03-01 Age: 12 Birth date: 2000-02-29 Later date: 2012-02-28 Age: 11 Birth date: 2000-02-29 Later date: 2012-02-29 Age: 12 Birth date: 2000-02-29 Later date: 2012-03-01 Age: 12 Birth date: 2000-03-01 Later date: 2012-02-28 Age: 11 Birth date: 2000-03-01 Later date: 2012-02-29 Age: 11 Birth date: 2000-03-01 Later date: 2012-03-01 Age: 12 } A: This is a strange way to do it, but if you format the date to yyyymmdd and subtract the date of birth from the current date then drop the last 4 digits you've got the age :) I don't know C#, but I believe this will work in any language. 20080814 - 19800703 = 280111 Drop the last 4 digits = 28. C# Code: int now = int.Parse(DateTime.Now.ToString("yyyyMMdd")); int dob = int.Parse(dateOfBirth.ToString("yyyyMMdd")); int age = (now - dob) / 10000; Or alternatively without all the type conversion in the form of an extension method. Error checking omitted: public static Int32 GetAge(this DateTime dateOfBirth) { var today = DateTime.Today; var a = (today.Year * 100 + today.Month) * 100 + today.Day; var b = (dateOfBirth.Year * 100 + dateOfBirth.Month) * 100 + dateOfBirth.Day; return (a - b) / 10000; } A: The following approach (extract from Time Period Library for .NET class DateDiff) considers the calendar of the culture info: // ---------------------------------------------------------------------- private static int YearDiff( DateTime date1, DateTime date2 ) { return YearDiff( date1, date2, DateTimeFormatInfo.CurrentInfo.Calendar ); } // YearDiff // ---------------------------------------------------------------------- private static int YearDiff( DateTime date1, DateTime date2, Calendar calendar ) { if ( date1.Equals( date2 ) ) { return 0; } int year1 = calendar.GetYear( date1 ); int month1 = calendar.GetMonth( date1 ); int year2 = calendar.GetYear( date2 ); int month2 = calendar.GetMonth( date2 ); // find the the day to compare int compareDay = date2.Day; int compareDaysPerMonth = calendar.GetDaysInMonth( year1, month1 ); if ( compareDay > compareDaysPerMonth ) { compareDay = compareDaysPerMonth; } // build the compare date DateTime compareDate = new DateTime( year1, month2, compareDay, date2.Hour, date2.Minute, date2.Second, date2.Millisecond ); if ( date2 > date1 ) { if ( compareDate < date1 ) { compareDate = compareDate.AddYears( 1 ); } } else { if ( compareDate > date1 ) { compareDate = compareDate.AddYears( -1 ); } } return year2 - calendar.GetYear( compareDate ); } // YearDiff Usage: // ---------------------------------------------------------------------- public void CalculateAgeSamples() { PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2009, 02, 28 ) ); // > Birthdate=29.02.2000, Age at 28.02.2009 is 8 years PrintAge( new DateTime( 2000, 02, 29 ), new DateTime( 2012, 02, 28 ) ); // > Birthdate=29.02.2000, Age at 28.02.2012 is 11 years } // CalculateAgeSamples // ---------------------------------------------------------------------- public void PrintAge( DateTime birthDate, DateTime moment ) { Console.WriteLine( "Birthdate={0:d}, Age at {1:d} is {2} years", birthDate, moment, YearDiff( birthDate, moment ) ); } // PrintAge A: SQL version: declare @dd smalldatetime = '1980-04-01' declare @age int = YEAR(GETDATE())-YEAR(@dd) if (@dd> DATEADD(YYYY, -@age, GETDATE())) set @age = @age -1 print @age A: How come the MSDN help did not tell you that? It looks so obvious: System.DateTime birthTime = AskTheUser(myUser); // :-) System.DateTime now = System.DateTime.Now; System.TimeSpan age = now - birthTime; // As simple as that double ageInDays = age.TotalDays; // Will you convert to whatever you want yourself? A: Simple and readable with complementary method public static int getAge(DateTime birthDate) { var today = DateTime.Today; var age = today.Year - birthDate.Year; var monthDiff = today.Month - birthDate.Month; var dayDiff = today.Day - birthDate.Day; if (dayDiff < 0) { monthDiff--; } if (monthDiff < 0) { age--; } return age; } A: var EndDate = new DateTime(2022, 4, 21); var StartDate = new DateTime(1986, 4, 25); Int32 Months = EndDate.Month - StartDate.Month; Int32 Years = EndDate.Year - StartDate.Year; Int32 Days = EndDate.Day - StartDate.Day; if (Days < 0) { Months = Months - 1; } if (Months < 0) { Years = Years - 1; Months = Months + 12; } string Ages = Years.ToString() + " Year(s) " + Months.ToString() + " Month(s) "; A: Here's an answer making use of DateTimeOffset and manual math: var diff = DateTimeOffset.Now - dateOfBirth; var sinceEpoch = DateTimeOffset.UnixEpoch + diff; return sinceEpoch.Year - 1970; A: To calculate how many years old a person is, DateTime dateOfBirth; int ageInYears = DateTime.Now.Year - dateOfBirth.Year; if (dateOfBirth > today.AddYears(-ageInYears )) ageInYears --; A: Very simple answer DateTime dob = new DateTime(1991, 3, 4); DateTime now = DateTime.Now; int dobDay = dob.Day, dobMonth = dob.Month; int add = -1; if (dobMonth < now.Month) { add = 0; } else if (dobMonth == now.Month) { if(dobDay <= now.Day) { add = 0; } else { add = -1; } } else { add = -1; } int age = now.Year - dob.Year + add; A: int Age = new DateTime((DateTime.Now - BirthDate).Ticks).Year -1; Console.WriteLine("Age {0}", Age); A: I have no knowledge about DateTime but all I can do is this: using System; public class Program { public static int getAge(int month, int day, int year) { DateTime today = DateTime.Today; int currentDay = today.Day; int currentYear = today.Year; int currentMonth = today.Month; int age = 0; if (currentMonth < month) { age -= 1; } else if (currentMonth == month) { if (currentDay < day) { age -= 1; } } currentYear -= year; age += currentYear; return age; } public static void Main() { int ageInYears = getAge(8, 10, 2007); Console.WriteLine(ageInYears); } } A little confusing, but looking at the code more carefully, it will all make sense. A: var startDate = new DateTime(2015, 04, 05);//your start date var endDate = DateTime.Now; var years = 0; while(startDate < endDate) { startDate = startDate.AddYears(1); if(startDate < endDate) { years++; } } A: One could compute 'age' (i.e. the 'westerner' way) this way: public static int AgeInYears(this System.DateTime source, System.DateTime target) => target.Year - source.Year is int age && age > 0 && source.AddYears(age) > target ? age - 1 : age < 0 && source.AddYears(age) < target ? age + 1 : age; If the direction of time is 'negative', the age will be negative also. One can add a fraction, which represents the amount of age accumulated from target to the next birthday: public static double AgeInTotalYears(this System.DateTime source, System.DateTime target) { var sign = (source <= target ? 1 : -1); var ageInYears = AgeInYears(source, target); // The method above. var last = source.AddYears(ageInYears); var next = source.AddYears(ageInYears + sign); var fractionalAge = (double)(target - last).Ticks / (double)(next - last).Ticks * sign; return ageInYears + fractionalAge; } The fraction is the ratio of passed time (from the last birthday) over total time (to the next birthday). Both of the methods work the same way whether going forward or backward in time. A: This is a very simple approach: int Age = DateTime.Today.Year - new DateTime(2000, 1, 1).Year; A: A branchless solution: public int GetAge(DateOnly birthDate, DateOnly today) { return today.Year - birthDate.Year + (((today.Month << 5) + today.Day - ((birthDate.Month << 5) + birthDate.Day)) >> 31); } A: Don't know why nobody tried this: ushort age = (ushort)DateAndTime.DateDiff(DateInterval.Year, DateTime.Now.Date, birthdate); All it requires is using Microsoft.VisualBasic; and reference to this assembly in the project (if not already referred). A: Why can't be simplified to check birth month and day? First line (var year = end.Year - start.Year - 1;): assums that birthdate is not yet occurred on end year. Then check the month and day to see if it is occurred; add one more year. No special treatment on leap year scenario. You cannot create a date (feb 29) as end date if it is not a leap year, so birthdate celebration will be counted if end date is on march 1th, not on deb 28th. The function below will cover this scenario as ordinary date. static int Get_Age(DateTime start, DateTime end) { var year = end.Year - start.Year - 1; if (end.Month < start.Month) return year; else if (end.Month == start.Month) { if (end.Day >= start.Day) return ++year; return year; } else return ++year; } static void Test_Get_Age() { var start = new DateTime(2008, 4, 10); // b-date, leap year BTY var end = new DateTime(2023, 2, 1); // end date is before the b-date var result1 = Get_Age(start, end); var success1 = result1 == 14; // true end = new DateTime(2023, 4, 10); // end date is on the b-date var result2 = Get_Age(start, end); var success2 = result2 == 15; // true end = new DateTime(2023, 6, 22); // end date is after the b-date var result3 = Get_Age(start, end); var success3 = result3 == 15; // true start = new DateTime(2008, 2, 29); // b-date is on feb 29 end = new DateTime(2023, 2, 28); // end date is before the b-date var result4 = Get_Age(start, end); var success4 = result4 == 14; // true end = new DateTime(2020, 2, 29); // end date is on the b-date, on another leap year var result5 = Get_Age(start, end); var success5 = result5 == 12; // true } A: A one-liner answer: DateTime dateOfBirth = Convert.ToDateTime("01/16/1990"); var age = ((DateTime.Now - dateOfBirth).Days) / 365; A: To calculate the age with nearest age: var ts = DateTime.Now - new DateTime(1988, 3, 19); var age = Math.Round(ts.Days / 365.0); A: Check this out: TimeSpan ts = DateTime.Now.Subtract(Birthdate); age = (byte)(ts.TotalDays / 365.25); A: I think this problem can be solved with an easier way like this- The class can be like- using System; namespace TSA { class BirthDay { double ageDay; public BirthDay(int day, int month, int year) { DateTime birthDate = new DateTime(year, month, day); ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow } internal int GetAgeYear() { return (int)Math.Truncate(ageDay / 365); } internal int GetAgeMonth() { return (int)Math.Truncate((ageDay % 365) / 30); } } } And calls can be like- BirthDay b = new BirthDay(1,12,1990); int year = b.GetAgeYear(); int month = b.GetAgeMonth();
{ "language": "en", "url": "https://stackoverflow.com/questions/9", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2199" }
Q: Calculate relative time in C# Given a specific DateTime value, how do I display relative time, like: * *2 hours ago *3 days ago *a month ago A: public static string RelativeDate(DateTime theDate) { Dictionary<long, string> thresholds = new Dictionary<long, string>(); int minute = 60; int hour = 60 * minute; int day = 24 * hour; thresholds.Add(60, "{0} seconds ago"); thresholds.Add(minute * 2, "a minute ago"); thresholds.Add(45 * minute, "{0} minutes ago"); thresholds.Add(120 * minute, "an hour ago"); thresholds.Add(day, "{0} hours ago"); thresholds.Add(day * 2, "yesterday"); thresholds.Add(day * 30, "{0} days ago"); thresholds.Add(day * 365, "{0} months ago"); thresholds.Add(long.MaxValue, "{0} years ago"); long since = (DateTime.Now.Ticks - theDate.Ticks) / 10000000; foreach (long threshold in thresholds.Keys) { if (since < threshold) { TimeSpan t = new TimeSpan((DateTime.Now.Ticks - theDate.Ticks)); 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()); } } return ""; } I prefer this version for its conciseness, and ability to add in new tick points. This could be encapsulated with a Latest() extension to Timespan instead of that long 1 liner, but for the sake of brevity in posting, this will do. This fixes the an hour ago, 1 hours ago, by providing an hour until 2 hours have elapsed A: I got this answer from one of Bill Gates' blogs. I need to find it on my browser history and I'll give you the link. The Javascript code to do the same thing (as requested): function posted(t) { var now = new Date(); var diff = parseInt((now.getTime() - Date.parse(t)) / 1000); if (diff < 60) { return 'less than a minute ago'; } else if (diff < 120) { return 'about a minute ago'; } else if (diff < (2700)) { return (parseInt(diff / 60)).toString() + ' minutes ago'; } else if (diff < (5400)) { return 'about an hour ago'; } else if (diff < (86400)) { return 'about ' + (parseInt(diff / 3600)).toString() + ' hours ago'; } else if (diff < (172800)) { return '1 day ago'; } else {return (parseInt(diff / 86400)).toString() + ' days ago'; } } Basically, you work in terms of seconds. A: Java for client-side gwt usage: import java.util.Date; public class RelativeDateFormat { private static final long ONE_MINUTE = 60000L; private static final long ONE_HOUR = 3600000L; private static final long ONE_DAY = 86400000L; private static final long ONE_WEEK = 604800000L; public static String format(Date date) { long delta = new Date().getTime() - date.getTime(); if (delta < 1L * ONE_MINUTE) { return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago"; } if (delta < 2L * ONE_MINUTE) { return "one minute ago"; } if (delta < 45L * ONE_MINUTE) { return toMinutes(delta) + " minutes ago"; } if (delta < 90L * ONE_MINUTE) { return "one hour ago"; } if (delta < 24L * ONE_HOUR) { return toHours(delta) + " hours ago"; } if (delta < 48L * ONE_HOUR) { return "yesterday"; } if (delta < 30L * ONE_DAY) { return toDays(delta) + " days ago"; } if (delta < 12L * 4L * ONE_WEEK) { long months = toMonths(delta); return months <= 1 ? "one month ago" : months + " months ago"; } else { long years = toYears(delta); return years <= 1 ? "one year ago" : years + " years ago"; } } private static long toSeconds(long date) { return date / 1000L; } private static long toMinutes(long date) { return toSeconds(date) / 60L; } private static long toHours(long date) { return toMinutes(date) / 60L; } private static long toDays(long date) { return toHours(date) / 24L; } private static long toMonths(long date) { return toDays(date) / 30L; } private static long toYears(long date) { return toMonths(date) / 365L; } } A: I think there is already a number of answers related to this post, but one can use this which is easy to use just like plugin and also easily readable for programmers. Send your specific date, and get its value in string form: public string RelativeDateTimeCount(DateTime inputDateTime) { string outputDateTime = string.Empty; TimeSpan ts = DateTime.Now - inputDateTime; if (ts.Days > 7) { outputDateTime = inputDateTime.ToString("MMMM d, yyyy"); } else if (ts.Days > 0) { outputDateTime = ts.Days == 1 ? ("about 1 Day ago") : ("about " + ts.Days.ToString() + " Days ago"); } else if (ts.Hours > 0) { outputDateTime = ts.Hours == 1 ? ("an hour ago") : (ts.Hours.ToString() + " hours ago"); } else if (ts.Minutes > 0) { outputDateTime = ts.Minutes == 1 ? ("1 minute ago") : (ts.Minutes.ToString() + " minutes ago"); } else outputDateTime = "few seconds ago"; return outputDateTime; } A: public static string ToRelativeDate(DateTime input) { TimeSpan oSpan = DateTime.Now.Subtract(input); double TotalMinutes = oSpan.TotalMinutes; string Suffix = " ago"; if (TotalMinutes < 0.0) { TotalMinutes = Math.Abs(TotalMinutes); Suffix = " from now"; } var aValue = new SortedList<double, Func<string>>(); aValue.Add(0.75, () => "less than a minute"); aValue.Add(1.5, () => "about a minute"); aValue.Add(45, () => string.Format("{0} minutes", Math.Round(TotalMinutes))); aValue.Add(90, () => "about an hour"); aValue.Add(1440, () => string.Format("about {0} hours", Math.Round(Math.Abs(oSpan.TotalHours)))); // 60 * 24 aValue.Add(2880, () => "a day"); // 60 * 48 aValue.Add(43200, () => string.Format("{0} days", Math.Floor(Math.Abs(oSpan.TotalDays)))); // 60 * 24 * 30 aValue.Add(86400, () => "about a month"); // 60 * 24 * 60 aValue.Add(525600, () => string.Format("{0} months", Math.Floor(Math.Abs(oSpan.TotalDays / 30)))); // 60 * 24 * 365 aValue.Add(1051200, () => "about a year"); // 60 * 24 * 365 * 2 aValue.Add(double.MaxValue, () => string.Format("{0} years", Math.Floor(Math.Abs(oSpan.TotalDays / 365)))); return aValue.First(n => TotalMinutes < n.Key).Value.Invoke() + Suffix; } http://refactormycode.com/codes/493-twitter-esque-relative-dates C# 6 version: static readonly SortedList<double, Func<TimeSpan, string>> offsets = new SortedList<double, Func<TimeSpan, string>> { { 0.75, _ => "less than a minute"}, { 1.5, _ => "about a minute"}, { 45, x => $"{x.TotalMinutes:F0} minutes"}, { 90, x => "about an hour"}, { 1440, x => $"about {x.TotalHours:F0} hours"}, { 2880, x => "a day"}, { 43200, x => $"{x.TotalDays:F0} days"}, { 86400, x => "about a month"}, { 525600, x => $"{x.TotalDays / 30:F0} months"}, { 1051200, x => "about a year"}, { double.MaxValue, x => $"{x.TotalDays / 365:F0} years"} }; public static string ToRelativeDate(this DateTime input) { TimeSpan x = DateTime.Now - input; string Suffix = x.TotalMinutes > 0 ? " ago" : " from now"; x = new TimeSpan(Math.Abs(x.Ticks)); return offsets.First(n => x.TotalMinutes < n.Key).Value(x) + Suffix; } A: Here a rewrite from Jeffs Script for PHP: define("SECOND", 1); define("MINUTE", 60 * SECOND); define("HOUR", 60 * MINUTE); define("DAY", 24 * HOUR); define("MONTH", 30 * DAY); function relativeTime($time) { $delta = time() - $time; if ($delta < 1 * MINUTE) { return $delta == 1 ? "one second ago" : $delta . " seconds ago"; } if ($delta < 2 * MINUTE) { return "a minute ago"; } if ($delta < 45 * MINUTE) { return floor($delta / MINUTE) . " minutes ago"; } if ($delta < 90 * MINUTE) { return "an hour ago"; } if ($delta < 24 * HOUR) { return floor($delta / HOUR) . " hours ago"; } if ($delta < 48 * HOUR) { return "yesterday"; } if ($delta < 30 * DAY) { return floor($delta / DAY) . " days ago"; } if ($delta < 12 * MONTH) { $months = floor($delta / DAY / 30); return $months <= 1 ? "one month ago" : $months . " months ago"; } else { $years = floor($delta / DAY / 365); return $years <= 1 ? "one year ago" : $years . " years ago"; } } A: var ts = new TimeSpan(DateTime.Now.Ticks - dt.Ticks); A: If you want to have an output like "2 days, 4 hours and 12 minutes ago", you need a timespan: TimeSpan timeDiff = DateTime.Now-CreatedDate; Then you can access the values you like: timeDiff.Days timeDiff.Hours etc... A: Here's an implementation I added as an extension method to the DateTime class that handles both future and past dates and provides an approximation option that allows you to specify the level of detail you're looking for ("3 hour ago" vs "3 hours, 23 minutes, 12 seconds ago"): using System.Text; /// <summary> /// Compares a supplied date to the current date and generates a friendly English /// comparison ("5 days ago", "5 days from now") /// </summary> /// <param name="date">The date to convert</param> /// <param name="approximate">When off, calculate timespan down to the second. /// When on, approximate to the largest round unit of time.</param> /// <returns></returns> public static string ToRelativeDateString(this DateTime value, bool approximate) { StringBuilder sb = new StringBuilder(); string suffix = (value > DateTime.Now) ? " from now" : " ago"; TimeSpan timeSpan = new TimeSpan(Math.Abs(DateTime.Now.Subtract(value).Ticks)); if (timeSpan.Days > 0) { sb.AppendFormat("{0} {1}", timeSpan.Days, (timeSpan.Days > 1) ? "days" : "day"); if (approximate) return sb.ToString() + suffix; } if (timeSpan.Hours > 0) { sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, timeSpan.Hours, (timeSpan.Hours > 1) ? "hours" : "hour"); if (approximate) return sb.ToString() + suffix; } if (timeSpan.Minutes > 0) { sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, timeSpan.Minutes, (timeSpan.Minutes > 1) ? "minutes" : "minute"); if (approximate) return sb.ToString() + suffix; } if (timeSpan.Seconds > 0) { sb.AppendFormat("{0}{1} {2}", (sb.Length > 0) ? ", " : string.Empty, timeSpan.Seconds, (timeSpan.Seconds > 1) ? "seconds" : "second"); if (approximate) return sb.ToString() + suffix; } if (sb.Length == 0) return "right now"; sb.Append(suffix); return sb.ToString(); } A: I would provide some handy extensions methods for this and make the code more readable. First, couple of extension methods for Int32. public static class TimeSpanExtensions { public static TimeSpan Days(this int value) { return new TimeSpan(value, 0, 0, 0); } public static TimeSpan Hours(this int value) { return new TimeSpan(0, value, 0, 0); } public static TimeSpan Minutes(this int value) { return new TimeSpan(0, 0, value, 0); } public static TimeSpan Seconds(this int value) { return new TimeSpan(0, 0, 0, value); } public static TimeSpan Milliseconds(this int value) { return new TimeSpan(0, 0, 0, 0, value); } public static DateTime Ago(this TimeSpan value) { return DateTime.Now - value; } } Then, one for DateTime. public static class DateTimeExtensions { public static DateTime Ago(this DateTime dateTime, TimeSpan delta) { return dateTime - delta; } } Now, you can do something like below: var date = DateTime.Now; date.Ago(2.Days()); // 2 days ago date.Ago(7.Hours()); // 7 hours ago date.Ago(567.Milliseconds()); // 567 milliseconds ago A: There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation. DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday" DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago" DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow" DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now" TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks" TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour" Scott Hanselman has a writeup on it on his blog A: /** * {@code date1} has to be earlier than {@code date2}. */ public static String relativize(Date date1, Date date2) { assert date2.getTime() >= date1.getTime(); long duration = date2.getTime() - date1.getTime(); long converted; if ((converted = TimeUnit.MILLISECONDS.toDays(duration)) > 0) { return String.format("%d %s ago", converted, converted == 1 ? "day" : "days"); } else if ((converted = TimeUnit.MILLISECONDS.toHours(duration)) > 0) { return String.format("%d %s ago", converted, converted == 1 ? "hour" : "hours"); } else if ((converted = TimeUnit.MILLISECONDS.toMinutes(duration)) > 0) { return String.format("%d %s ago", converted, converted == 1 ? "minute" : "minutes"); } else if ((converted = TimeUnit.MILLISECONDS.toSeconds(duration)) > 0) { return String.format("%d %s ago", converted, converted == 1 ? "second" : "seconds"); } else { return "just now"; } } A: Turkish localized version of Vincents answer. const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks); double delta = Math.Abs(ts.TotalSeconds); if (delta < 1 * MINUTE) return ts.Seconds + " saniye önce"; if (delta < 45 * MINUTE) return ts.Minutes + " dakika önce"; if (delta < 24 * HOUR) return ts.Hours + " saat önce"; if (delta < 48 * HOUR) return "dün"; if (delta < 30 * DAY) return ts.Days + " gün önce"; if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months + " ay önce"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years + " yıl önce"; } A: jquery.timeago plugin Jeff, because Stack Overflow uses jQuery extensively, I recommend the jquery.timeago plugin. Benefits: * *Avoid timestamps dated "1 minute ago" even though the page was opened 10 minutes ago; timeago refreshes automatically. *You can take full advantage of page and/or fragment caching in your web applications, because the timestamps aren't calculated on the server. *You get to use microformats like the cool kids. Just attach it to your timestamps on DOM ready: jQuery(document).ready(function() { jQuery('abbr.timeago').timeago(); }); This will turn all abbr elements with a class of timeago and an ISO 8601 timestamp in the title: <abbr class="timeago" title="2008-07-17T09:24:17Z">July 17, 2008</abbr> into something like this: <abbr class="timeago" title="July 17, 2008">4 months ago</abbr> which yields: 4 months ago. As time passes, the timestamps will automatically update. Disclaimer: I wrote this plugin, so I'm biased. A: I would recommend computing this on the client side too. Less work for the server. The following is the version that I use (from Zach Leatherman) /* * Javascript Humane Dates * Copyright (c) 2008 Dean Landolt (deanlandolt.com) * Re-write by Zach Leatherman (zachleat.com) * * Adopted from the John Resig's pretty.js * at http://ejohn.org/blog/javascript-pretty-date * and henrah's proposed modification * at http://ejohn.org/blog/javascript-pretty-date/#comment-297458 * * Licensed under the MIT license. */ function humane_date(date_str){ var time_formats = [ [60, 'just now'], [90, '1 minute'], // 60*1.5 [3600, 'minutes', 60], // 60*60, 60 [5400, '1 hour'], // 60*60*1.5 [86400, 'hours', 3600], // 60*60*24, 60*60 [129600, '1 day'], // 60*60*24*1.5 [604800, 'days', 86400], // 60*60*24*7, 60*60*24 [907200, '1 week'], // 60*60*24*7*1.5 [2628000, 'weeks', 604800], // 60*60*24*(365/12), 60*60*24*7 [3942000, '1 month'], // 60*60*24*(365/12)*1.5 [31536000, 'months', 2628000], // 60*60*24*365, 60*60*24*(365/12) [47304000, '1 year'], // 60*60*24*365*1.5 [3153600000, 'years', 31536000], // 60*60*24*365*100, 60*60*24*365 [4730400000, '1 century'] // 60*60*24*365*100*1.5 ]; var time = ('' + date_str).replace(/-/g,"/").replace(/[TZ]/g," "), dt = new Date, seconds = ((dt - new Date(time) + (dt.getTimezoneOffset() * 60000)) / 1000), token = ' ago', i = 0, format; if (seconds < 0) { seconds = Math.abs(seconds); token = ''; } while (format = time_formats[i++]) { if (seconds < format[0]) { if (format.length == 2) { return format[1] + (i > 1 ? token : ''); // Conditional so we don't return Just Now Ago } else { return Math.round(seconds / format[2]) + ' ' + format[1] + (i > 1 ? token : ''); } } } // overflow for centuries if(seconds > 4730400000) return Math.round(seconds / 4730400000) + ' centuries' + token; return date_str; }; if(typeof jQuery != 'undefined') { jQuery.fn.humane_dates = function(){ return this.each(function(){ var date = humane_date(this.title); if(date && jQuery(this).text() != date) // don't modify the dom if we don't have to jQuery(this).text(date); }); }; } A: Here's how I do it var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks); double delta = Math.Abs(ts.TotalSeconds); if (delta < 60) { return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; } if (delta < 60 * 2) { return "a minute ago"; } if (delta < 45 * 60) { return ts.Minutes + " minutes ago"; } if (delta < 90 * 60) { return "an hour ago"; } if (delta < 24 * 60 * 60) { return ts.Hours + " hours ago"; } if (delta < 48 * 60 * 60) { return "yesterday"; } if (delta < 30 * 24 * 60 * 60) { return ts.Days + " days ago"; } if (delta < 12 * 30 * 24 * 60 * 60) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "one month ago" : months + " months ago"; } int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "one year ago" : years + " years ago"; Suggestions? Comments? Ways to improve this algorithm? A: @jeff IMHO yours seems a little long. However it does seem a little more robust with support for "yesterday" and "years". But in my experience when this is used, the person is most likely to view the content in the first 30 days. It is only the really hardcore people that come after that. So, I usually elect to keep this short and simple. This is the method I am currently using in one of my websites. This returns only a relative day, hour and time. And then the user has to slap on "ago" in the output. public static string ToLongString(this TimeSpan time) { string output = String.Empty; if (time.Days > 0) output += time.Days + " days "; if ((time.Days == 0 || time.Days == 1) && time.Hours > 0) output += time.Hours + " hr "; if (time.Days == 0 && time.Minutes > 0) output += time.Minutes + " min "; if (output.Length == 0) output += time.Seconds + " sec"; return output.Trim(); } A: Surely an easy fix to get rid of the '1 hours ago' problem would be to increase the window that 'an hour ago' is valid for. Change if (delta < 5400) // 90 * 60 { return "an hour ago"; } into if (delta < 7200) // 120 * 60 { return "an hour ago"; } This means that something that occurred 110 minutes ago will read as 'an hour ago' - this may not be perfect, but I'd say it is better than the current situation of '1 hours ago'. A: public string getRelativeDateTime(DateTime date) { TimeSpan ts = DateTime.Now - date; if (ts.TotalMinutes < 1)//seconds ago return "just now"; if (ts.TotalHours < 1)//min ago return (int)ts.TotalMinutes == 1 ? "1 Minute ago" : (int)ts.TotalMinutes + " Minutes ago"; if (ts.TotalDays < 1)//hours ago return (int)ts.TotalHours == 1 ? "1 Hour ago" : (int)ts.TotalHours + " Hours ago"; if (ts.TotalDays < 7)//days ago return (int)ts.TotalDays == 1 ? "1 Day ago" : (int)ts.TotalDays + " Days ago"; if (ts.TotalDays < 30.4368)//weeks ago return (int)(ts.TotalDays / 7) == 1 ? "1 Week ago" : (int)(ts.TotalDays / 7) + " Weeks ago"; if (ts.TotalDays < 365.242)//months ago return (int)(ts.TotalDays / 30.4368) == 1 ? "1 Month ago" : (int)(ts.TotalDays / 30.4368) + " Months ago"; //years ago return (int)(ts.TotalDays / 365.242) == 1 ? "1 Year ago" : (int)(ts.TotalDays / 365.242) + " Years ago"; } Conversion values for days in a month and year were taken from Google. A: In a way you do your DateTime function over calculating relative time by either seconds to years, try something like this: using System; public class Program { public static string getRelativeTime(DateTime past) { DateTime now = DateTime.Today; string rt = ""; int time; string statement = ""; if (past.Second >= now.Second) { if (past.Second - now.Second == 1) { rt = "second ago"; } rt = "seconds ago"; time = past.Second - now.Second; statement = "" + time; return (statement + rt); } if (past.Minute >= now.Minute) { if (past.Second - now.Second == 1) { rt = "second ago"; } else { rt = "minutes ago"; } time = past.Minute - now.Minute; statement = "" + time; return (statement + rt); } // This process will go on until years } public static void Main() { DateTime before = new DateTime(1995, 8, 24); string date = getRelativeTime(before); Console.WriteLine("Windows 95 was {0}.", date); } } Not exactly working but if you modify and debug it a bit, it will likely do the job. A: A couple of years late to the party, but I had a requirement to do this for both past and future dates, so I combined Jeff's and Vincent's into this. It's a ternarytastic extravaganza! :) public static class DateTimeHelper { private const int SECOND = 1; private const int MINUTE = 60 * SECOND; private const int HOUR = 60 * MINUTE; private const int DAY = 24 * HOUR; private const int MONTH = 30 * DAY; /// <summary> /// Returns a friendly version of the provided DateTime, relative to now. E.g.: "2 days ago", or "in 6 months". /// </summary> /// <param name="dateTime">The DateTime to compare to Now</param> /// <returns>A friendly string</returns> public static string GetFriendlyRelativeTime(DateTime dateTime) { if (DateTime.UtcNow.Ticks == dateTime.Ticks) { return "Right now!"; } bool isFuture = (DateTime.UtcNow.Ticks < dateTime.Ticks); var ts = DateTime.UtcNow.Ticks < dateTime.Ticks ? new TimeSpan(dateTime.Ticks - DateTime.UtcNow.Ticks) : new TimeSpan(DateTime.UtcNow.Ticks - dateTime.Ticks); double delta = ts.TotalSeconds; if (delta < 1 * MINUTE) { return isFuture ? "in " + (ts.Seconds == 1 ? "one second" : ts.Seconds + " seconds") : ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; } if (delta < 2 * MINUTE) { return isFuture ? "in a minute" : "a minute ago"; } if (delta < 45 * MINUTE) { return isFuture ? "in " + ts.Minutes + " minutes" : ts.Minutes + " minutes ago"; } if (delta < 90 * MINUTE) { return isFuture ? "in an hour" : "an hour ago"; } if (delta < 24 * HOUR) { return isFuture ? "in " + ts.Hours + " hours" : ts.Hours + " hours ago"; } if (delta < 48 * HOUR) { return isFuture ? "tomorrow" : "yesterday"; } if (delta < 30 * DAY) { return isFuture ? "in " + ts.Days + " days" : ts.Days + " days ago"; } if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return isFuture ? "in " + (months <= 1 ? "one month" : months + " months") : months <= 1 ? "one month ago" : months + " months ago"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return isFuture ? "in " + (years <= 1 ? "one year" : years + " years") : years <= 1 ? "one year ago" : years + " years ago"; } } } A: using Fluent DateTime var dateTime1 = 2.Hours().Ago(); var dateTime2 = 3.Days().Ago(); var dateTime3 = 1.Months().Ago(); var dateTime4 = 5.Hours().FromNow(); var dateTime5 = 2.Weeks().FromNow(); var dateTime6 = 40.Seconds().FromNow(); A: Given the world and her husband appear to be posting code samples, here is what I wrote a while ago, based on a couple of these answers. I had a specific need for this code to be localisable. So I have two classes — Grammar, which specifies the localisable terms, and FuzzyDateExtensions, which holds a bunch of extension methods. I had no need to deal with future datetimes, so no attempt is made to handle them with this code. I've left some of the XMLdoc in the source, but removed most (where they'd be obvious) for brevity's sake. I've also not included every class member here: public class Grammar { /// <summary> Gets or sets the term for "just now". </summary> public string JustNow { get; set; } /// <summary> Gets or sets the term for "X minutes ago". </summary> /// <remarks> /// This is a <see cref="String.Format"/> pattern, where <c>{0}</c> /// is the number of minutes. /// </remarks> public string MinutesAgo { get; set; } public string OneHourAgo { get; set; } public string HoursAgo { get; set; } public string Yesterday { get; set; } public string DaysAgo { get; set; } public string LastMonth { get; set; } public string MonthsAgo { get; set; } public string LastYear { get; set; } public string YearsAgo { get; set; } /// <summary> Gets or sets the term for "ages ago". </summary> public string AgesAgo { get; set; } /// <summary> /// Gets or sets the threshold beyond which the fuzzy date should be /// considered "ages ago". /// </summary> public TimeSpan AgesAgoThreshold { get; set; } /// <summary> /// Initialises a new <see cref="Grammar"/> instance with the /// specified properties. /// </summary> private void Initialise(string justNow, string minutesAgo, string oneHourAgo, string hoursAgo, string yesterday, string daysAgo, string lastMonth, string monthsAgo, string lastYear, string yearsAgo, string agesAgo, TimeSpan agesAgoThreshold) { ... } } The FuzzyDateString class contains: public static class FuzzyDateExtensions { public static string ToFuzzyDateString(this TimeSpan timespan) { return timespan.ToFuzzyDateString(new Grammar()); } public static string ToFuzzyDateString(this TimeSpan timespan, Grammar grammar) { return GetFuzzyDateString(timespan, grammar); } public static string ToFuzzyDateString(this DateTime datetime) { return (DateTime.Now - datetime).ToFuzzyDateString(); } public static string ToFuzzyDateString(this DateTime datetime, Grammar grammar) { return (DateTime.Now - datetime).ToFuzzyDateString(grammar); } private static string GetFuzzyDateString(TimeSpan timespan, Grammar grammar) { timespan = timespan.Duration(); if (timespan >= grammar.AgesAgoThreshold) { return grammar.AgesAgo; } if (timespan < new TimeSpan(0, 2, 0)) // 2 minutes { return grammar.JustNow; } if (timespan < new TimeSpan(1, 0, 0)) // 1 hour { return String.Format(grammar.MinutesAgo, timespan.Minutes); } if (timespan < new TimeSpan(1, 55, 0)) // 1 hour 55 minutes { return grammar.OneHourAgo; } if (timespan < new TimeSpan(12, 0, 0) // 12 hours && (DateTime.Now - timespan).IsToday()) { return String.Format(grammar.HoursAgo, timespan.RoundedHours()); } if ((DateTime.Now.AddDays(1) - timespan).IsToday()) { return grammar.Yesterday; } if (timespan < new TimeSpan(32, 0, 0, 0) // 32 days && (DateTime.Now - timespan).IsThisMonth()) { return String.Format(grammar.DaysAgo, timespan.RoundedDays()); } if ((DateTime.Now.AddMonths(1) - timespan).IsThisMonth()) { return grammar.LastMonth; } if (timespan < new TimeSpan(365, 0, 0, 0, 0) // 365 days && (DateTime.Now - timespan).IsThisYear()) { return String.Format(grammar.MonthsAgo, timespan.RoundedMonths()); } if ((DateTime.Now - timespan).AddYears(1).IsThisYear()) { return grammar.LastYear; } return String.Format(grammar.YearsAgo, timespan.RoundedYears()); } } One of the key things I wanted to achieve, as well as localisation, was that "today" would only mean "this calendar day", so the IsToday, IsThisMonth, IsThisYear methods look like this: public static bool IsToday(this DateTime date) { return date.DayOfYear == DateTime.Now.DayOfYear && date.IsThisYear(); } and the rounding methods are like this (I've included RoundedMonths, as that's a bit different): public static int RoundedDays(this TimeSpan timespan) { return (timespan.Hours > 12) ? timespan.Days + 1 : timespan.Days; } public static int RoundedMonths(this TimeSpan timespan) { DateTime then = DateTime.Now - timespan; // Number of partial months elapsed since 1 Jan, AD 1 (DateTime.MinValue) int nowMonthYears = DateTime.Now.Year * 12 + DateTime.Now.Month; int thenMonthYears = then.Year * 12 + then.Month; return nowMonthYears - thenMonthYears; } I hope people find this useful and/or interesting :o) A: // Calculate total days in current year int daysInYear; for (var i = 1; i <= 12; i++) daysInYear += DateTime.DaysInMonth(DateTime.Now.Year, i); // Past date DateTime dateToCompare = DateTime.Now.Subtract(TimeSpan.FromMinutes(582)); // Calculate difference between current date and past date double diff = (DateTime.Now - dateToCompare).TotalMilliseconds; TimeSpan ts = TimeSpan.FromMilliseconds(diff); var years = ts.TotalDays / daysInYear; // Years var months = ts.TotalDays / (daysInYear / (double)12); // Months var weeks = ts.TotalDays / 7; // Weeks var days = ts.TotalDays; // Days var hours = ts.TotalHours; // Hours var minutes = ts.TotalMinutes; // Minutes var seconds = ts.TotalSeconds; // Seconds if (years >= 1) Console.WriteLine(Math.Round(years, 0) + " year(s) ago"); else if (months >= 1) Console.WriteLine(Math.Round(months, 0) + " month(s) ago"); else if (weeks >= 1) Console.WriteLine(Math.Round(weeks, 0) + " week(s) ago"); else if (days >= 1) Console.WriteLine(Math.Round(days, 0) + " days(s) ago"); else if (hours >= 1) Console.WriteLine(Math.Round(hours, 0) + " hour(s) ago"); else if (minutes >= 1) Console.WriteLine(Math.Round(minutes, 0) + " minute(s) ago"); else if (seconds >= 1) Console.WriteLine(Math.Round(seconds, 0) + " second(s) ago"); Console.ReadLine(); A: A "one-liner" using deconstruction and Linq to get "n [biggest unit of time] ago" : TimeSpan timeSpan = DateTime.Now - new DateTime(1234, 5, 6, 7, 8, 9); (string unit, int value) = new Dictionary<string, int> { {"year(s)", (int)(timeSpan.TotalDays / 365.25)}, //https://en.wikipedia.org/wiki/Year#Intercalation {"month(s)", (int)(timeSpan.TotalDays / 29.53)}, //https://en.wikipedia.org/wiki/Month {"day(s)", (int)timeSpan.TotalDays}, {"hour(s)", (int)timeSpan.TotalHours}, {"minute(s)", (int)timeSpan.TotalMinutes}, {"second(s)", (int)timeSpan.TotalSeconds}, {"millisecond(s)", (int)timeSpan.TotalMilliseconds} }.First(kvp => kvp.Value > 0); Console.WriteLine($"{value} {unit} ago"); You get 786 year(s) ago With the current year and month, like TimeSpan timeSpan = DateTime.Now - new DateTime(2020, 12, 6, 7, 8, 9); you get 4 day(s) ago With the actual date, like TimeSpan timeSpan = DateTime.Now - DateTime.Now.Date; you get 9 hour(s) ago A: Is there an easy way to do this in Java? The java.util.Date class seems rather limited. Here is my quick and dirty Java solution: import java.util.Date; import javax.management.timer.Timer; String getRelativeDate(Date date) { long delta = new Date().getTime() - date.getTime(); if (delta < 1L * Timer.ONE_MINUTE) { return toSeconds(delta) == 1 ? "one second ago" : toSeconds(delta) + " seconds ago"; } if (delta < 2L * Timer.ONE_MINUTE) { return "a minute ago"; } if (delta < 45L * Timer.ONE_MINUTE) { return toMinutes(delta) + " minutes ago"; } if (delta < 90L * Timer.ONE_MINUTE) { return "an hour ago"; } if (delta < 24L * Timer.ONE_HOUR) { return toHours(delta) + " hours ago"; } if (delta < 48L * Timer.ONE_HOUR) { return "yesterday"; } if (delta < 30L * Timer.ONE_DAY) { return toDays(delta) + " days ago"; } if (delta < 12L * 4L * Timer.ONE_WEEK) { // a month long months = toMonths(delta); return months <= 1 ? "one month ago" : months + " months ago"; } else { long years = toYears(delta); return years <= 1 ? "one year ago" : years + " years ago"; } } private long toSeconds(long date) { return date / 1000L; } private long toMinutes(long date) { return toSeconds(date) / 60L; } private long toHours(long date) { return toMinutes(date) / 60L; } private long toDays(long date) { return toHours(date) / 24L; } private long toMonths(long date) { return toDays(date) / 30L; } private long toYears(long date) { return toMonths(date) / 365L; } A: iPhone Objective-C Version + (NSString *)timeAgoString:(NSDate *)date { int delta = -(int)[date timeIntervalSinceNow]; if (delta < 60) { return delta == 1 ? @"one second ago" : [NSString stringWithFormat:@"%i seconds ago", delta]; } if (delta < 120) { return @"a minute ago"; } if (delta < 2700) { return [NSString stringWithFormat:@"%i minutes ago", delta/60]; } if (delta < 5400) { return @"an hour ago"; } if (delta < 24 * 3600) { return [NSString stringWithFormat:@"%i hours ago", delta/3600]; } if (delta < 48 * 3600) { return @"yesterday"; } if (delta < 30 * 24 * 3600) { return [NSString stringWithFormat:@"%i days ago", delta/(24*3600)]; } if (delta < 12 * 30 * 24 * 3600) { int months = delta/(30*24*3600); return months <= 1 ? @"one month ago" : [NSString stringWithFormat:@"%i months ago", months]; } else { int years = delta/(12*30*24*3600); return years <= 1 ? @"one year ago" : [NSString stringWithFormat:@"%i years ago", years]; } } A: I thought I'd give this a shot using classes and polymorphism. I had a previous iteration which used sub-classing which ended up having way too much overhead. I've switched to a more flexible delegate / public property object model which is significantly better. My code is very slightly more accurate, I wish I could come up with a better way to generate "months ago" that didn't seem too over-engineered. I think I'd still stick with Jeff's if-then cascade because it's less code and it's simpler (it's definitely easier to ensure it'll work as expected). For the below code PrintRelativeTime.GetRelativeTimeMessage(TimeSpan ago) returns the relative time message (e.g. "yesterday"). public class RelativeTimeRange : IComparable { public TimeSpan UpperBound { get; set; } public delegate string RelativeTimeTextDelegate(TimeSpan timeDelta); public RelativeTimeTextDelegate MessageCreator { get; set; } public int CompareTo(object obj) { if (!(obj is RelativeTimeRange)) { return 1; } // note that this sorts in reverse order to the way you'd expect, // this saves having to reverse a list later return (obj as RelativeTimeRange).UpperBound.CompareTo(UpperBound); } } public class PrintRelativeTime { private static List<RelativeTimeRange> timeRanges; static PrintRelativeTime() { timeRanges = new List<RelativeTimeRange>{ new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(1), MessageCreator = (delta) => { return "one second ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromSeconds(60), MessageCreator = (delta) => { return delta.Seconds + " seconds ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(2), MessageCreator = (delta) => { return "one minute ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromMinutes(60), MessageCreator = (delta) => { return delta.Minutes + " minutes ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(2), MessageCreator = (delta) => { return "one hour ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromHours(24), MessageCreator = (delta) => { return delta.Hours + " hours ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.FromDays(2), MessageCreator = (delta) => { return "yesterday"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-1)), MessageCreator = (delta) => { return delta.Days + " days ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddMonths(-2)), MessageCreator = (delta) => { return "one month ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-1)), MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 30) + " months ago"; } }, new RelativeTimeRange { UpperBound = DateTime.Now.Subtract(DateTime.Now.AddYears(-2)), MessageCreator = (delta) => { return "one year ago"; } }, new RelativeTimeRange { UpperBound = TimeSpan.MaxValue, MessageCreator = (delta) => { return (int)Math.Floor(delta.TotalDays / 365.24D) + " years ago"; } } }; timeRanges.Sort(); } public static string GetRelativeTimeMessage(TimeSpan ago) { RelativeTimeRange postRelativeDateRange = timeRanges[0]; foreach (var timeRange in timeRanges) { if (ago.CompareTo(timeRange.UpperBound) <= 0) { postRelativeDateRange = timeRange; } } return postRelativeDateRange.MessageCreator(ago); } } A: When you know the viewer's time zone, it might be clearer to use calendar days at the day scale. I'm not familiar with the .NET libraries so I don't know how you'd do that in C#, unfortunately. On consumer sites, you could also be hand-wavier under a minute. "Less than a minute ago" or "just now" could be good enough. A: In PHP, I do it this way: <?php function timesince($original) { // array of time period chunks $chunks = array( array(60 * 60 * 24 * 365 , 'year'), array(60 * 60 * 24 * 30 , 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24 , 'day'), array(60 * 60 , 'hour'), array(60 , 'minute'), ); $today = time(); /* Current unix time */ $since = $today - $original; if($since > 604800) { $print = date("M jS", $original); if($since > 31536000) { $print .= ", " . date("Y", $original); } return $print; } // $j saves performing the count function each time around the loop for ($i = 0, $j = count($chunks); $i < $j; $i++) { $seconds = $chunks[$i][0]; $name = $chunks[$i][1]; // finding the biggest chunk (if the chunk fits, break) if (($count = floor($since / $seconds)) != 0) { break; } } $print = ($count == 1) ? '1 '.$name : "$count {$name}s"; return $print . " ago"; } ?> A: using System; using System.Collections.Generic; using System.Linq; public static class RelativeDateHelper { private static Dictionary<double, Func<double, string>> sm_Dict = null; private static Dictionary<double, Func<double, string>> DictionarySetup() { var dict = new Dictionary<double, Func<double, string>>(); dict.Add(0.75, (mins) => "less than a minute"); dict.Add(1.5, (mins) => "about a minute"); dict.Add(45, (mins) => string.Format("{0} minutes", Math.Round(mins))); dict.Add(90, (mins) => "about an hour"); dict.Add(1440, (mins) => string.Format("about {0} hours", Math.Round(Math.Abs(mins / 60)))); // 60 * 24 dict.Add(2880, (mins) => "a day"); // 60 * 48 dict.Add(43200, (mins) => string.Format("{0} days", Math.Floor(Math.Abs(mins / 1440)))); // 60 * 24 * 30 dict.Add(86400, (mins) => "about a month"); // 60 * 24 * 60 dict.Add(525600, (mins) => string.Format("{0} months", Math.Floor(Math.Abs(mins / 43200)))); // 60 * 24 * 365 dict.Add(1051200, (mins) => "about a year"); // 60 * 24 * 365 * 2 dict.Add(double.MaxValue, (mins) => string.Format("{0} years", Math.Floor(Math.Abs(mins / 525600)))); return dict; } public static string ToRelativeDate(this DateTime input) { TimeSpan oSpan = DateTime.Now.Subtract(input); double TotalMinutes = oSpan.TotalMinutes; string Suffix = " ago"; if (TotalMinutes < 0.0) { TotalMinutes = Math.Abs(TotalMinutes); Suffix = " from now"; } if (null == sm_Dict) sm_Dict = DictionarySetup(); return sm_Dict.First(n => TotalMinutes < n.Key).Value.Invoke(TotalMinutes) + Suffix; } } The same as another answer to this question but as an extension method with a static dictionary. A: @Jeff var ts = new TimeSpan(DateTime.UtcNow.Ticks - dt.Ticks); Doing a subtraction on DateTime returns a TimeSpan anyway. So you can just do (DateTime.UtcNow - dt).TotalSeconds I'm also surprised to see the constants multiplied-out by hand and then comments added with the multiplications in. Was that some misguided optimisation? A: you can try this.I think it will work correctly. long delta = new Date().getTime() - date.getTime(); const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; if (delta < 0L) { return "not yet"; } if (delta < 1L * MINUTE) { return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; } if (delta < 2L * MINUTE) { return "a minute ago"; } if (delta < 45L * MINUTE) { return ts.Minutes + " minutes ago"; } if (delta < 90L * MINUTE) { return "an hour ago"; } if (delta < 24L * HOUR) { return ts.Hours + " hours ago"; } if (delta < 48L * HOUR) { return "yesterday"; } if (delta < 30L * DAY) { return ts.Days + " days ago"; } if (delta < 12L * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "one month ago" : months + " months ago"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "one year ago" : years + " years ago"; } A: You can use TimeAgo extension as below: public static string TimeAgo(this DateTime dateTime) { string result = string.Empty; var timeSpan = DateTime.Now.Subtract(dateTime); if (timeSpan <= TimeSpan.FromSeconds(60)) { result = string.Format("{0} seconds ago", timeSpan.Seconds); } else if (timeSpan <= TimeSpan.FromMinutes(60)) { result = timeSpan.Minutes > 1 ? String.Format("about {0} minutes ago", timeSpan.Minutes) : "about a minute ago"; } else if (timeSpan <= TimeSpan.FromHours(24)) { result = timeSpan.Hours > 1 ? String.Format("about {0} hours ago", timeSpan.Hours) : "about an hour ago"; } else if (timeSpan <= TimeSpan.FromDays(30)) { result = timeSpan.Days > 1 ? String.Format("about {0} days ago", timeSpan.Days) : "yesterday"; } else if (timeSpan <= TimeSpan.FromDays(365)) { result = timeSpan.Days > 30 ? String.Format("about {0} months ago", timeSpan.Days / 30) : "about a month ago"; } else { result = timeSpan.Days > 365 ? String.Format("about {0} years ago", timeSpan.Days / 365) : "about a year ago"; } return result; } Or use jQuery plugin with Razor extension from Timeago. A: You can reduce the server-side load by performing this logic client-side. View source on some Digg pages for reference. They have the server emit an epoch time value that gets processed by Javascript. This way you don't need to manage the end user's time zone. The new server-side code would be something like: public string GetRelativeTime(DateTime timeStamp) { return string.Format("<script>printdate({0});</script>", timeStamp.ToFileTimeUtc()); } You could even add a NOSCRIPT block there and just perform a ToString(). A: Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete). const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY; var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks); double delta = Math.Abs(ts.TotalSeconds); if (delta < 1 * MINUTE) return ts.Seconds == 1 ? "one second ago" : ts.Seconds + " seconds ago"; if (delta < 2 * MINUTE) return "a minute ago"; if (delta < 45 * MINUTE) return ts.Minutes + " minutes ago"; if (delta < 90 * MINUTE) return "an hour ago"; if (delta < 24 * HOUR) return ts.Hours + " hours ago"; if (delta < 48 * HOUR) return "yesterday"; if (delta < 30 * DAY) return ts.Days + " days ago"; if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1 ? "one month ago" : months + " months ago"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1 ? "one year ago" : years + " years ago"; } A: Here's the algorithm stackoverflow uses but rewritten more concisely in perlish pseudocode with a bug fix (no "one hours ago"). The function takes a (positive) number of seconds ago and returns a human-friendly string like "3 hours ago" or "yesterday". agoify($delta) local($y, $mo, $d, $h, $m, $s); $s = floor($delta); if($s<=1) return "a second ago"; if($s<60) return "$s seconds ago"; $m = floor($s/60); if($m==1) return "a minute ago"; if($m<45) return "$m minutes ago"; $h = floor($m/60); if($h==1) return "an hour ago"; if($h<24) return "$h hours ago"; $d = floor($h/24); if($d<2) return "yesterday"; if($d<30) return "$d days ago"; $mo = floor($d/30); if($mo<=1) return "a month ago"; $y = floor($mo/12); if($y<1) return "$mo months ago"; if($y==1) return "a year ago"; return "$y years ago"; A: This is my function, works like a charm :) public static string RelativeDate(DateTime theDate) { var span = DateTime.Now - theDate; if (span.Days > 365) { var years = (span.Days / 365); if (span.Days % 365 != 0) years += 1; return $"about {years} {(years == 1 ? "year" : "years")} ago"; } if (span.Days > 30) { var months = (span.Days / 30); if (span.Days % 31 != 0) months += 1; return $"about {months} {(months == 1 ? "month" : "months")} ago"; } if (span.Days > 0) return $"about {span.Days} {(span.Days == 1 ? "day" : "days")} ago"; if (span.Hours > 0) return $"about {span.Hours} {(span.Hours == 1 ? "hour" : "hours")} ago"; if (span.Minutes > 0) return $"about {span.Minutes} {(span.Minutes == 1 ? "minute" : "minutes")} ago"; if (span.Seconds > 5) return $"about {span.Seconds} seconds ago"; return span.Seconds <= 5 ? "about 5 seconds ago" : string.Empty; } A: The accepted answer by Vincent makes quite a few arbitrary decisions. Why is 45 minutes rounded up to an hour while 45 seconds is not rounded up to a minute? It has an increased level of cyclomatic complexity within the years and month calculations that makes it more complex to follow the logic. It makes the assumption that the TimeSpan is relative to the past (2 days ago) when it could very well be in the future (2 days until). It defines unnecessary constants instead of using TimeSpan.TicksPerSecond etc. This implementation resolves the above and updates the syntax to use switch expressions and relational patterns /// <summary> /// Convert a <see cref="TimeSpan"/> to a natural language representation. /// </summary> /// <example> /// <code> /// TimeSpan.FromSeconds(10).ToNaturalLanguage(); /// // 10 seconds /// </code> /// </example> public static string ToNaturalLanguage(this TimeSpan @this) { const int daysInWeek = 7; const int daysInMonth = 30; const int daysInYear = 365; const long threshold = 100 * TimeSpan.TicksPerMillisecond; @this = @this.TotalSeconds < 0 ? TimeSpan.FromSeconds(@this.TotalSeconds * -1) : @this; return (@this.Ticks + threshold) switch { < 2 * TimeSpan.TicksPerSecond => "a second", < 1 * TimeSpan.TicksPerMinute => @this.Seconds + " seconds", < 2 * TimeSpan.TicksPerMinute => "a minute", < 1 * TimeSpan.TicksPerHour => @this.Minutes + " minutes", < 2 * TimeSpan.TicksPerHour => "an hour", < 1 * TimeSpan.TicksPerDay => @this.Hours + " hours", < 2 * TimeSpan.TicksPerDay => "a day", < 1 * daysInWeek * TimeSpan.TicksPerDay => @this.Days + " days", < 2 * daysInWeek * TimeSpan.TicksPerDay => "a week", < 1 * daysInMonth * TimeSpan.TicksPerDay => (@this.Days / daysInWeek).ToString("F0") + " weeks", < 2 * daysInMonth * TimeSpan.TicksPerDay => "a month", < 1 * daysInYear * TimeSpan.TicksPerDay => (@this.Days / daysInMonth).ToString("F0") + " months", < 2 * daysInYear * TimeSpan.TicksPerDay => "a year", _ => (@this.Days / daysInYear).ToString("F0") + " years" }; } /// <summary> /// Convert a <see cref="DateTime"/> to a natural language representation. /// </summary> /// <example> /// <code> /// (DateTime.Now - TimeSpan.FromSeconds(10)).ToNaturalLanguage() /// // 10 seconds ago /// </code> /// </example> public static string ToNaturalLanguage(this DateTime @this) { TimeSpan timeSpan = @this - DateTime.Now; return timeSpan.TotalSeconds switch { >= 1 => timeSpan.ToNaturalLanguage() + " until", <= -1 => timeSpan.ToNaturalLanguage() + " ago", _ => "now", }; } You can test it with NUnit as follows: [TestCase("a second", 0)] [TestCase("a second", 1)] [TestCase("2 seconds", 2)] [TestCase("a minute", 0, 1)] [TestCase("5 minutes", 0, 5)] [TestCase("an hour", 0, 0, 1)] [TestCase("2 hours", 0, 0, 2)] [TestCase("a day", 0, 0, 24)] [TestCase("a day", 0, 0, 0, 1)] [TestCase("6 days", 0, 0, 0, 6)] [TestCase("a week", 0, 0, 0, 7)] [TestCase("4 weeks", 0, 0, 0, 29)] [TestCase("a month", 0, 0, 0, 30)] [TestCase("6 months", 0, 0, 0, 6 * 30)] [TestCase("a year", 0, 0, 0, 365)] [TestCase("68 years", int.MaxValue)] public void NaturalLanguageHelpers_TimeSpan( string expected, int seconds, int minutes = 0, int hours = 0, int days = 0 ) { // Arrange TimeSpan timeSpan = new(days, hours, minutes, seconds); // Act string result = timeSpan.ToNaturalLanguage(); // Assert Assert.That(result, Is.EqualTo(expected)); } [TestCase("now", 0)] [TestCase("10 minutes ago", 0, -10)] [TestCase("10 minutes until", 10, 10)] [TestCase("68 years until", int.MaxValue)] [TestCase("68 years ago", int.MinValue)] public void NaturalLanguageHelpers_DateTime( string expected, int seconds, int minutes = 0, int hours = 0, int days = 0 ) { // Arrange TimeSpan timeSpan = new(days, hours, minutes, seconds); DateTime now = DateTime.Now; DateTime dateTime = now + timeSpan; // Act string result = dateTime.ToNaturalLanguage(); // Assert Assert.That(result, Is.EqualTo(expected)); } Or as a gist: https://gist.github.com/StudioLE/2dd394e3f792e79adc927ede274df56e A: My way is much more simpler. You can tweak with the return strings as you want public static string TimeLeft(DateTime utcDate) { TimeSpan timeLeft = DateTime.UtcNow - utcDate; string timeLeftString = ""; if (timeLeft.Days > 0) { timeLeftString += timeLeft.Days == 1 ? timeLeft.Days + " day" : timeLeft.Days + " days"; } else if (timeLeft.Hours > 0) { timeLeftString += timeLeft.Hours == 1 ? timeLeft.Hours + " hour" : timeLeft.Hours + " hours"; } else { timeLeftString += timeLeft.Minutes == 1 ? timeLeft.Minutes+" minute" : timeLeft.Minutes + " minutes"; } return timeLeftString; } A: Simple and 100% working solution. Handling ago and future times as well.. just in case public string GetTimeSince(DateTime postDate) { string message = ""; DateTime currentDate = DateTime.Now; TimeSpan timegap = currentDate - postDate; if (timegap.Days > 365) { message = string.Format(L("Ago") + " {0} " + L("Years"), (((timegap.Days) / 30) / 12)); } else if (timegap.Days > 30) { message = string.Format(L("Ago") + " {0} " + L("Months"), timegap.Days/30); } else if (timegap.Days > 0) { message = string.Format(L("Ago") + " {0} " + L("Days"), timegap.Days); } else if (timegap.Hours > 0) { message = string.Format(L("Ago") + " {0} " + L("Hours"), timegap.Hours); } else if (timegap.Minutes > 0) { message = string.Format(L("Ago") + " {0} " + L("Minutes"), timegap.Minutes); } else if (timegap.Seconds > 0) { message = string.Format(L("Ago") + " {0} " + L("Seconds"), timegap.Seconds); } // let's handle future times..just in case else if (timegap.Days < -365) { message = string.Format(L("In") + " {0} " + L("Years"), (((Math.Abs(timegap.Days)) / 30) / 12)); } else if (timegap.Days < -30) { message = string.Format(L("In") + " {0} " + L("Months"), ((Math.Abs(timegap.Days)) / 30)); } else if (timegap.Days < 0) { message = string.Format(L("In") + " {0} " + L("Days"), Math.Abs(timegap.Days)); } else if (timegap.Hours < 0) { message = string.Format(L("In") + " {0} " + L("Hours"), Math.Abs(timegap.Hours)); } else if (timegap.Minutes < 0) { message = string.Format(L("In") + " {0} " + L("Minutes"), Math.Abs(timegap.Minutes)); } else if (timegap.Seconds < 0) { message = string.Format(L("In") + " {0} " + L("Seconds"), Math.Abs(timegap.Seconds)); } else { message = "a bit"; } return message; }
{ "language": "en", "url": "https://stackoverflow.com/questions/11", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1644" }
Q: Determine a user's timezone Is there a standard way for a web server to be able to determine a user's timezone within a web page? Perhaps from an HTTP header or part of the user-agent string? A: One possible option is to use the Date header field, which is defined in RFC 7231 and is supposed to include the timezone. Of course, it is not guaranteed that the value is really the client's timezone, but it can be a convenient starting point. A: JavaScript is the easiest way to get the client's local time. I would suggest using an XMLHttpRequest to send back the local time, and if that fails, fall back to the timezone detected based on their IP address. As far as geolocation, I've used MaxMind GeoIP on several projects and it works well, though I'm not sure if they provide timezone data. It's a service you pay for and they provide monthly updates to your database. They provide wrappers in several web languages. A: Here is a robust JavaScript solution to determine the time zone the browser is in. >>> var timezone = jstz.determine(); >>> timezone.name(); "Europe/London" https://github.com/pellepim/jstimezonedetect A: Here is a more complete way. * *Get the timezone offset for the user *Test some days on daylight saving boundaries to determine if they are in a zone that uses daylight saving. An excerpt is below: function TimezoneDetect(){ var dtDate = new Date('1/1/' + (new Date()).getUTCFullYear()); var intOffset = 10000; //set initial offset high so it is adjusted on the first attempt var intMonth; var intHoursUtc; var intHours; var intDaysMultiplyBy; // Go through each month to find the lowest offset to account for DST for (intMonth=0;intMonth < 12;intMonth++){ //go to the next month dtDate.setUTCMonth(dtDate.getUTCMonth() + 1); // To ignore daylight saving time look for the lowest offset. // Since, during DST, the clock moves forward, it'll be a bigger number. if (intOffset > (dtDate.getTimezoneOffset() * (-1))){ intOffset = (dtDate.getTimezoneOffset() * (-1)); } } return intOffset; } Getting TZ and DST from JS (via Way Back Machine) A: There can be a few ways to determine the timezone in the browser. If there is a standard function that is available and supported by your browser, that is what you should use. Below are three ways to get the same information in different formats. Avoid using non-standard solutions that make any guesses based on certain assumptions or hard coded lists of zones though they may be helpful if nothing else can be done. Once you have this info, you can pass this as a non-standard request header to server and use it there. If you also need the timezone offset, you can also pass it to server in headers or in request payload which can be retrieved with dateObj.getTimezoneOffset(). * *Use Intl API to get the Olson format (Standard and recommended way): Note that this is not supported by all browsers. Refer this link for details on browser support for this. This API let's you get the timezone in Olson format i.e., something like Asia/Kolkata, America/New_York etc. Intl.DateTimeFormat().resolvedOptions().timeZone *Use Date object to get the long format such as India Standard Time, Eastern Standard Time etc: This is supported by all browsers. let dateObj = new Date(2021, 11, 25, 09, 30, 00); //then dateObj.toString() //yields Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time) //I am located in India (IST) Notice the string contains timezone info in long and short formats. You can now use regex to get this info out: let longZoneRegex = /\((.+)\)/; dateObj.toString().match(longZoneRegex); //yields ['(India Standard Time)', 'India Standard Time', index: 34, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined] //Note that output is an array so use output[1] to get the timezone name. *Use Date object to get the short format such as GMT+0530, GMT-0500 etc: This is supported by all browsers. Similarly, you can get the short format out too: let shortZoneRegex = /GMT[+-]\d{1,4}/; dateObj.toString().match(shortZoneRegex); //yields ['GMT+0530', index: 25, input: 'Sat Dec 25 2021 09:30:00 GMT+0530 (India Standard Time)', groups: undefined] //Note that output is an array so use output[0] to get the timezone name. A: Using Unkwntech's approach, I wrote a function using jQuery and PHP. This is tested and does work! On the PHP page where you want to have the timezone as a variable, have this snippet of code somewhere near the top of the page: <?php session_start(); $timezone = $_SESSION['time']; ?> This will read the session variable "time", which we are now about to create. On the same page, in the <head>, you need to first of all include jQuery: <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script> Also in the <head>, below the jQuery, paste this: <script type="text/javascript"> $(document).ready(function() { if("<?php echo $timezone; ?>".length==0){ var visitortime = new Date(); var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60; $.ajax({ type: "GET", url: "http://example.org/timezone.php", data: 'time='+ visitortimezone, success: function(){ location.reload(); } }); } }); </script> You may or may not have noticed, but you need to change the URL to your actual domain. One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above URL) <?php session_start(); $_SESSION['time'] = $_GET['time']; ?> If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in. A: -new Date().getTimezoneOffset()/60; The method getTimezoneOffset() will subtract your time from GMT and return the number of minutes. So if you live in GMT-8, it will return 480. To put this into hours, divide by 60. Also, notice that the sign is the opposite of what you need - it's calculating GMT's offset from your time zone, not your time zone's offset from GMT. To fix this, simply multiply by -1. Also note that w3school says: The returned value is not a constant, because of the practice of using Daylight Saving Time. A: To submit the timezone offset as an HTTP header on AJAX requests with jQuery $.ajaxSetup({ beforeSend: function(xhr, settings) { xhr.setRequestHeader("X-TZ-Offset", -new Date().getTimezoneOffset()/60); } }); You can also do something similar to get the actual time zone name by using moment.tz.guess(); from http://momentjs.com/timezone/docs/#/using-timezones/guessing-user-timezone/ A: With the PHP date function you will get the date time of server on which the site is located. The only way to get the user time is to use JavaScript. But I suggest you to, if your site has registration required then the best way is to ask the user while to have registration as a compulsory field. You can list various time zones in the register page and save that in the database. After this, if the user logs in to the site then you can set the default time zone for that session as per the users’ selected time zone. You can set any specific time zone using the PHP function date_default_timezone_set. This sets the specified time zone for users. Basically the users’ time zone is goes to the client side, so we must use JavaScript for this. Below is the script to get users’ time zone using PHP and JavaScript. <?php #http://www.php.net/manual/en/timezones.php List of Time Zones function showclienttime() { if(!isset($_COOKIE['GMT_bias'])) { ?> <script type="text/javascript"> var Cookies = {}; Cookies.create = function (name, value, days) { if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); var expires = "; expires=" + date.toGMTString(); } else { var expires = ""; } document.cookie = name + "=" + value + expires + "; path=/"; this[name] = value; } var now = new Date(); Cookies.create("GMT_bias",now.getTimezoneOffset(),1); window.location = "<?php echo $_SERVER['PHP_SELF'];?>"; </script> <?php } else { $fct_clientbias = $_COOKIE['GMT_bias']; } $fct_servertimedata = gettimeofday(); $fct_servertime = $fct_servertimedata['sec']; $fct_serverbias = $fct_servertimedata['minuteswest']; $fct_totalbias = $fct_serverbias – $fct_clientbias; $fct_totalbias = $fct_totalbias * 60; $fct_clienttimestamp = $fct_servertime + $fct_totalbias; $fct_time = time(); $fct_year = strftime("%Y", $fct_clienttimestamp); $fct_month = strftime("%B", $fct_clienttimestamp); $fct_day = strftime("%d", $fct_clienttimestamp); $fct_hour = strftime("%I", $fct_clienttimestamp); $fct_minute = strftime("%M", $fct_clienttimestamp); $fct_second = strftime("%S", $fct_clienttimestamp); $fct_am_pm = strftime("%p", $fct_clienttimestamp); echo $fct_day.", ".$fct_month." ".$fct_year." ( ".$fct_hour.":".$fct_minute.":".$fct_second." ".$fct_am_pm." )"; } showclienttime(); ?> But as per my point of view, it’s better to ask to the users if registration is mandatory in your project. A: I still have not seen a detailed answer here that gets the time zone. You shouldn't need to geocode by IP address or use PHP (lol) or incorrectly guess from an offset. Firstly a time zone is not just an offset from GMT. It is an area of land in which the time rules are set by local standards. Some countries have daylight savings, and will switch on DST at differing times. It's usually important to get the actual zone, not just the current offset. If you intend to store this timezone, for instance in user preferences you want the zone and not just the offset. For realtime conversions it won't matter much. Now, to get the time zone with javascript you can use this: >> new Date().toTimeString(); "15:46:04 GMT+1200 (New Zealand Standard Time)" //Use some regular expression to extract the time. However I found it easier to simply use this robust plugin which returns the Olsen formatted timezone: https://github.com/scottwater/jquery.detect_timezone A: Don't use the IP address to definitively determine location (and hence timezone)-- that's because with NAT, proxies (increasingly popular), and VPNs, IP addresses do not necessarily realistically reflect the user's actual location, but the location at which the servers implementing those protocols reside. Similar to how US area codes are no longer useful for locating a telephone user, given the popularity of number portability. IP address and other techniques shown above are useful for suggesting a default that the user can adjust/correct. A: JavaScript: function maketimus(timestampz) { var linktime = new Date(timestampz * 1000); var linkday = linktime.getDate(); var freakingmonths = new Array(); freakingmonths[0] = "jan"; freakingmonths[1] = "feb"; freakingmonths[2] = "mar"; freakingmonths[3] = "apr"; freakingmonths[4] = "may"; freakingmonths[5] = "jun"; freakingmonths[6] = "jul"; freakingmonths[7] = "aug"; freakingmonths[8] = "sep"; freakingmonths[9] = "oct"; freakingmonths[10] = "nov"; freakingmonths[11] = "dec"; var linkmonthnum = linktime.getMonth(); var linkmonth = freakingmonths[linkmonthnum]; var linkyear = linktime.getFullYear(); var linkhour = linktime.getHours(); var linkminute = linktime.getMinutes(); if (linkminute < 10) { linkminute = "0" + linkminute; } var fomratedtime = linkday + linkmonth + linkyear + " " + linkhour + ":" + linkminute + "h"; return fomratedtime; } Simply provide your times in Unix timestamp format to this function; JavaScript already knows the timezone of the user. Like this: PHP: echo '<script type="text/javascript"> var eltimio = maketimus('.$unix_timestamp_ofshiz.'); document.write(eltimio); </script><noscript>pls enable javascript</noscript>'; This will always show the times correctly based on the timezone the person has set on his/her computer clock. There is no need to ask anything to anyone and save it into places, thank god! A: Easy, just use the JavaScript getTimezoneOffset function like so: -new Date().getTimezoneOffset()/60; A: All the magic seems to be in visitortime.getTimezoneOffset() That's cool, I didn't know about that. Does it work in Internet Explorer etc? From there you should be able to use JavaScript to Ajax, set cookies whatever. I'd probably go the cookie route myself. You'll need to allow the user to change it though. We tried to use geo-location (via maxmind) to do this a while ago, and it was wrong enough to make it not worth doing. So we just let the user set it in their profile, and show a notice to users who haven't set theirs yet. A: The most popular (==standard?) way of determining the time zone I've seen around is simply asking the users themselves. If your website requires subscription, this could be saved in the users' profile data. For anon users, the dates could be displayed as UTC or GMT or some such. I'm not trying to be a smart aleck. It's just that sometimes some problems have finer solutions outside of any programming context. A: There are no HTTP headers that will report the clients timezone so far although it has been suggested to include it in the HTTP specification. If it was me, I would probably try to fetch the timezone using clientside JavaScript and then submit it to the server using Ajax or something. A: If you happen to be using OpenID for authentication, Simple Registration Extension would solve the problem for authenticated users (You'll need to convert from tz to numeric). Another option would be to infer the time zone from the user agent's country preference. This is a somewhat crude method (won't work for en-US), but makes a good approximation. A: Here is an article (with source code) that explains how to determine and use localized time in an ASP.NET (VB.NET, C#) application: It's About Time In short, the described approach relies on the JavaScript getTimezoneOffset function, which returns the value that is saved in the session cookie and used by code-behind to adjust time values between GMT and local time. The nice thing is that the user does not need to specify the time zone (the code does it automatically). There is more involved (this is why I link to the article), but provided code makes it really easy to use. I suspect that you can convert the logic to PHP and other languages (as long as you understand ASP.NET). A: It is simple with JavaScript and PHP: Even though the user can mess with his/her internal clock and/or timezone, the best way I found so far, to get the offset, remains new Date().getTimezoneOffset();. It's non-invasive, doesn't give head-aches and eliminates the need to rely on third parties. Say I have a table, users, that contains a field date_created int(13), for storing Unix timestamps; Assuming a client creates a new account, data is received by post, and I need to insert/update the date_created column with the client's Unix timestamp, not the server's. Since the timezoneOffset is needed at the time of insert/update, it is passed as an extra $_POST element when the client submits the form, thus eliminating the need to store it in sessions and/or cookies, and no additional server hits either. var off = (-new Date().getTimezoneOffset()/60).toString();//note the '-' in front which makes it return positive for negative offsets and negative for positive offsets var tzo = off == '0' ? 'GMT' : off.indexOf('-') > -1 ? 'GMT'+off : 'GMT+'+off; Say the server receives tzo as $_POST['tzo']; $ts = new DateTime('now', new DateTimeZone($_POST['tzo']); $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. $user_timestamp = strtotime($user_time); Insert/update date_created=$user_timestamp. When retrieving the date_created, you can convert the timestamp like so: $date_created = // Get from the database $created = date("F j, Y, g:i a",$date_created); // Return it to the user or whatever Now, this example may fit one's needs, when it comes to inserting a first timestamp... When it comes to an additional timestamp, or table, you may want to consider inserting the tzo value into the users table for future reference, or setting it as session or as a cookie. P.S. BUT what if the user travels and switches timezones. Logs in at GMT+4, travels fast to GMT-1 and logs in again. Last login would be in the future. I think... we think too much. A: You could do it on the client with moment-timezone and send the value to server; sample usage: > moment.tz.guess() "America/Asuncion" A: Getting a valid TZ Database timezone name in PHP is a two-step process: * *With JavaScript, get timezone offset in minutes through getTimezoneOffset. This offset will be positive if the local timezone is behind UTC and negative if it is ahead. So you must add an opposite sign to the offset. var timezone_offset_minutes = new Date().getTimezoneOffset(); timezone_offset_minutes = timezone_offset_minutes == 0 ? 0 : -timezone_offset_minutes; Pass this offset to PHP. *In PHP convert this offset into a valid timezone name with timezone_name_from_abbr function. // Just an example. $timezone_offset_minutes = -360; // $_GET['timezone_offset_minutes'] // Convert minutes to seconds $timezone_name = timezone_name_from_abbr("", $timezone_offset_minutes*60, false); // America/Chicago echo $timezone_name;</code></pre> I've written a blog post on it: How to Detect User Timezone in PHP. It also contains a demo. A: Try this PHP code: <?php $ip = $_SERVER['REMOTE_ADDR']; $json = file_get_contents("http://api.easyjquery.com/ips/?ip=" . $ip . "&full=true"); $json = json_decode($json,true); $timezone = $json['LocalTimeZone']; ?> A: A simple way to do it is by using: new Date().getTimezoneOffset(); A: First, understand that time zone detection in JavaScript is imperfect. You can get the local time zone offset for a particular date and time using getTimezoneOffset on an instance of the Date object, but that's not quite the same as a full IANA time zone like America/Los_Angeles. There are some options that can work though: * *Most modern browsers support IANA time zones in their implementation of the ECMAScript Internationalization API, so you can do this: const tzid = Intl.DateTimeFormat().resolvedOptions().timeZone; console.log(tzid); The result is a string containing the IANA time zone setting of the computer where the code is running. Supported environments are listed in the Intl compatibility table. Expand the DateTimeFormat section, and look at the feature named resolvedOptions().timeZone defaults to the host environment. * *Some libraries, such as Luxon use this API to determine the time zone through functions like luxon.Settings.defaultZoneName. *If you need to support an wider set of environments, such as older web browsers, you can use a library to make an educated guess at the time zone. They work by first trying the Intl API if it's available, and when it's not available, they interrogate the getTimezoneOffset function of the Date object, for several different points in time, using the results to choose an appropriate time zone from an internal data set. Both jsTimezoneDetect and moment-timezone have this functionality. // using jsTimeZoneDetect var tzid = jstz.determine().name(); // using moment-timezone var tzid = moment.tz.guess(); In both cases, the result can only be thought of as a guess. The guess may be correct in many cases, but not all of them. Additionally, these libraries have to be periodically updated to counteract the fact that many older JavaScript implementations are only aware of the current daylight saving time rule for their local time zone. More details on that here. Ultimately, a better approach is to actually ask your user for their time zone. Provide a setting that they can change. You can use one of the above options to choose a default setting, but don't make it impossible to deviate from that in your app. There's also the entirely different approach of not relying on the time zone setting of the user's computer at all. Instead, if you can gather latitude and longitude coordinates, you can resolve those to a time zone using one of these methods. This works well on mobile devices. A: Here's how I do it. This will set the PHP default timezone to the user's local timezone. Just paste the following on the top of all your pages: <?php session_start(); if(!isset($_SESSION['timezone'])) { if(!isset($_REQUEST['offset'])) { ?> <script> var d = new Date() var offset= -d.getTimezoneOffset()/60; location.href = "<?php echo $_SERVER['PHP_SELF']; ?>?offset="+offset; </script> <?php } else { $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); $index = array_keys($zonelist, $_REQUEST['offset']); $_SESSION['timezone'] = $index[0]; } } date_default_timezone_set($_SESSION['timezone']); //rest of your code goes here ?> A: There's no such way to figure the timezone in the actual HTML code or any user-agent string, but what you can do is make a basic function getting it using JavaScript. I don't know how to code with JavaScript yet so my function might take time to make. However, you can try to get the actual timezone also using JavaScript with the getTzimezoneOffset() function in the Date section or simply new Date().getTimezoneOffset();. A: I think that @Matt Johnson-Pints is by far the best and a CanIuse search reveals that now it is widely adopted: https://caniuse.com/?search=Intl.DateTimeFormat().resolvedOptions().timeZone One of the challenges though is to consider why you want to know the Timezone. Because I think one of the things most people have missed is that they can change! If a user travels with his laptop from Europe to America if you had previously stored it in a database their timezone is now incorrect (even if the user never actually updates their devices timezone). This is also the problem with @Mads Kristiansen answer as well because users travel - you cannot rely on it as a given. For example, my Linux laptop has "automatic timezone" turned off. Whilst the time might update my timezone doesn't. So I believe the answer is - what do you need it for? Client side certainly seems to give an easier way to ascertain it, but both client and server side code will depend on either the user updating their timezone or it updating automatically. I might of course be wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/13", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "701" }
Q: Difference between Math.Floor() and Math.Truncate() What is the difference between Math.Floor() and Math.Truncate() in .NET? A: Math.Floor() rounds toward negative infinity Math.Truncate rounds up or down towards zero. For example: Math.Floor(-3.4) = -4 Math.Truncate(-3.4) = -3 while Math.Floor(3.4) = 3 Math.Truncate(3.4) = 3 A: Math.floor sliiiide to the left... Math.ceil sliiiide to the right... Math.truncate criiiiss crooooss (floor/ceil always towards 0) Math.round cha cha, real smooth... (go to closest side) Let's go to work! (⌐□_□) To the left... Math.floor Take it back now y'all... -- Two hops this time... -=2 Everybody clap your hands ✋✋ How low can you go? Can you go down low? All the way to the floor? if (this == "wrong") return "i don't wanna be right"; Math.truncate(x) is also the same as int(x). by removing a positive or negative fraction, you're always heading towards 0. A: Math.Floor rounds down, Math.Ceiling rounds up, and Math.Truncate rounds towards zero. Thus, Math.Truncate is like Math.Floor for positive numbers, and like Math.Ceiling for negative numbers. Here's the reference. For completeness, Math.Round rounds to the nearest integer. If the number is exactly midway between two integers, then it rounds towards the even one. Reference. See also: Pax Diablo's answer. Highly recommended! A: Math.floor() will always round down ie., it returns LESSER integer. While round() will return the NEAREST integer math.floor() Returns the largest integer less than or equal to the specified number. math.truncate() Calculates the integral part of a number. A: Some examples: Round(1.5) = 2 Round(2.5) = 2 Round(1.5, MidpointRounding.AwayFromZero) = 2 Round(2.5, MidpointRounding.AwayFromZero) = 3 Round(1.55, 1) = 1.6 Round(1.65, 1) = 1.6 Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6 Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7 Truncate(2.10) = 2 Truncate(2.00) = 2 Truncate(1.90) = 1 Truncate(1.80) = 1 A: Follow these links for the MSDN descriptions of: * *Math.Floor, which rounds down towards negative infinity. *Math.Ceiling, which rounds up towards positive infinity. *Math.Truncate, which rounds up or down towards zero. *Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3). The following diagram and table may help: -3 -2 -1 0 1 2 3 +--|------+---------+----|----+--|------+----|----+-------|-+ a b c d e a=-2.7 b=-0.5 c=0.3 d=1.5 e=2.8 ====== ====== ===== ===== ===== Floor -3 -1 0 1 2 Ceiling -2 0 1 2 3 Truncate -2 0 0 1 2 Round (ToEven) -3 0 0 2 3 Round (AwayFromZero) -3 -1 0 2 3 Note that Round is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example: n = 3.145; a = System.Math.Round (n, 2, MidpointRounding.ToEven); // 3.14 b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15 With the other functions, you have to use multiply/divide trickery to achieve the same effect: c = System.Math.Truncate (n * 100) / 100; // 3.14 d = System.Math.Ceiling (n * 100) / 100; // 3.15 A: They are functionally equivalent with positive numbers. The difference is in how they handle negative numbers. For example: Math.Floor(2.5) = 2 Math.Truncate(2.5) = 2 Math.Floor(-2.5) = -3 Math.Truncate(-2.5) = -2 MSDN links: - Math.Floor Method - Math.Truncate Method P.S. Beware of Math.Round it may not be what you expect. To get the "standard" rounding result use: float myFloat = 4.5; Console.WriteLine( Math.Round(myFloat) ); // writes 4 Console.WriteLine( Math.Round(myFloat, 0, MidpointRounding.AwayFromZero) ) //writes 5 Console.WriteLine( myFloat.ToString("F0") ); // writes 5 A: Math.Floor() : It gives the largest integer less than or equal to the given number. Math.Floor(3.45) =3 Math.Floor(-3.45) =-4 Math.Truncate(): It removes the decimal places of the number and replace with zero Math.Truncate(3.45)=3 Math.Truncate(-3.45)=-3 Also from above examples we can see that floor and truncate are same for positive numbers. A: Try this, Examples: Math.Floor() vs Math.Truncate() Math.Floor(2.56) = 2 Math.Floor(3.22) = 3 Math.Floor(-2.56) = -3 Math.Floor(-3.26) = -4 Math.Truncate(2.56) = 2 Math.Truncate(2.00) = 2 Math.Truncate(1.20) = 1 Math.Truncate(-3.26) = -3 Math.Truncate(-3.96) = -3 Also Math.Round() Math.Round(1.6) = 2 Math.Round(-8.56) = -9 Math.Round(8.16) = 8 Math.Round(8.50) = 8 Math.Round(8.51) = 9 math.floor() Returns the largest integer less than or equal to the specified number. MSDN system.math.floor math.truncate() Calculates the integral part of a number. MSDN system.math.truncate A: Math.Floor() rounds "toward negative infinity" in compliance to IEEE Standard 754 section 4. Math.Truncate() rounds " to the nearest integer towards zero." A: Math.Floor(): Returns the largest integer less than or equal to the specified double-precision floating-point number. Math.Round(): Rounds a value to the nearest integer or to the specified number of fractional digits. A: Truncate drops the decimal point. A: Going by the Mathematical Definition of Floor, that is, "Greatest integer less than or equal to a number", This is completely unambiguous, whereas, Truncate just removes the fractional part, which is equivalent to round towards 0.
{ "language": "en", "url": "https://stackoverflow.com/questions/14", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "491" }
Q: Filling a DataSet or a DataTable from a LINQ query result set How do you expose a LINQ query as an ASMX web service? Usually, from the business tier, I can return a typed DataSet or a DataTable which can be serialized for transport over ASMX. How can I do the same for a LINQ query? Is there a way to populate a typed DataSet or a DataTable via a LINQ query? public static MyDataTable CallMySproc() { string conn = "..."; 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; } How could I put the result set of a LINQ query into a DataSet or a DataTable? Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service? A: As mentioned in the question, IEnumerable has a CopyToDataTable method: IEnumerable<DataRow> query = from order in orders.AsEnumerable() where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1) select order; // Create a table from the query. DataTable boundTable = query.CopyToDataTable<DataRow>(); Why won't that work for you? A: If you use IEnumerable as the return type, it will return your query variable directly. MyDataContext db = new MyDataContext(); IEnumerable<DataRow> query = (from order in db.Orders.AsEnumerable() select new { order.Property, order.Property2 }) as IEnumerable<DataRow>; return query.CopyToDataTable<DataRow>(); A: To perform this query against a DataContext class, you'll need to do the following: MyDataContext db = new MyDataContext(); IEnumerable<DataRow> query = (from order in db.Orders.AsEnumerable() select new { order.Property, order.Property2 }) as IEnumerable<DataRow>; return query.CopyToDataTable<DataRow>(); Without the as IEnumerable<DataRow>; you will see the following compilation error: Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?) A: Make a set of Data Transfer Objects, a couple of mappers, and return that via the .asmx. You should never expose the database objects directly, as a change in the procedure schema will propagate to the web service consumer without you noticing it. A: For the sake of completeness, these solutions do not work for EF Core (at least not for EF Core 2.2). Casting to IEnumerable<DataRow>, as suggested in the other answers here, fails. Implementing this class and extension methods worked for me https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/implement-copytodatatable-where-type-not-a-datarow. Why it's not built into EF Core, I have not idea. A: If you use a return type of IEnumerable, you can return your query variable directly. A: Create a class object and return a list(T) of the query.
{ "language": "en", "url": "https://stackoverflow.com/questions/16", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "157" }
Q: Binary Data in MySQL How do I store binary data in MySQL? A: For a table like this: CREATE TABLE binary_data ( id INT(4) NOT NULL AUTO_INCREMENT PRIMARY KEY, description CHAR(50), bin_data LONGBLOB, filename CHAR(50), filesize CHAR(50), filetype CHAR(50) ); Here is a PHP example: <?php // store.php3 - by Florian Dittmer <dittmer@gmx.net> // Example php script to demonstrate the storing of binary files into // an sql database. More information can be found at http://www.phpbuilder.com/ ?> <html> <head><title>Store binary data into SQL Database</title></head> <body> <?php // Code that will be executed if the form has been submitted: if ($submit) { // Connect to the database (you may have to adjust // the hostname, username or password). mysql_connect("localhost", "root", "password"); mysql_select_db("binary_data"); $data = mysql_real_escape_string(fread(fopen($form_data, "r"), filesize($form_data))); $result = mysql_query("INSERT INTO binary_data (description, bin_data, filename, filesize, filetype) ". "VALUES ('$form_description', '$data', '$form_data_name', '$form_data_size', '$form_data_type')"); $id= mysql_insert_id(); print "<p>This file has the following Database ID: <b>$id</b>"; mysql_close(); } else { // else show the form to submit new data: ?> <form method="post" action="<?php echo $PHP_SELF; ?>" enctype="multipart/form-data"> File Description:<br> <input type="text" name="form_description" size="40"> <input type="hidden" name="MAX_FILE_SIZE" value="1000000"> <br>File to upload/store in database:<br> <input type="file" name="form_data" size="40"> <p><input type="submit" name="submit" value="submit"> </form> <?php } ?> </body> </html> A: I strongly recommend against storing binary data in a relational database. Relational databases are designed to work with fixed-size data; that's where their performance strength is: remember Joel's old article on why databases are so fast? because it takes exactly 1 pointer increment to move from a record to another record. If you add BLOB data of undefined and vastly varying size, you'll screw up performance. Instead, store files in the file system, and store file names in your database. A: While you haven't said what you're storing, and you may have a great reason for doing so, often the answer is 'as a filesystem reference' and the actual data is on the filesystem somewhere. http://www.onlamp.com/pub/a/onlamp/2002/07/11/MySQLtips.html A: It depends on the data you wish to store. The above example uses the LONGBLOB data type, but you should be aware that there are other binary data types: TINYBLOB/BLOB/MEDIUMBLOB/LONGBLOB VARBINARY BINARY Each has its use cases. If it is a known (short) length (e.g. packed data), BINARY or VARBINARY will work most of the time. They have the added benefit of being able to index on them. A: While it shouldn't be necessary, you could try base64 encoding data in and decoding it out. That means the db will just have ascii characters. It will take a bit more space and time, but any issue to do with the binary data will be eliminated. A: The answer by phpguy is correct but I think there is a lot of confusion in the additional details there. The basic answer is in a BLOB data type / attribute domain. BLOB is short for Binary Large Object and that column data type is specific for handling binary data. See the relevant manual page for MySQL. A: If the - not recommended - BLOB field exists, you can save data this way: mysql_query("UPDATE table SET field=X'".bin2hex($bin_data)."' WHERE id=$id"); Idea taken from here. A: When I need to store binary data I always use VARBINARY format as introduced by d0nut in one of the previous answers. You can find documentation at MySQL website under documented topic: 12.4.2 The BINARY and VARBINARY Types. If you are asking what are advantages, please read the question: why-varbinary-instead-of-varchar. A: The question also arises how to get the data into the BLOB. You can put the data in an INSERT statement, as the PHP example shows (although you should use mysql_real_escape_string instead of addslashes). If the file exists on the database server, you can also use MySQL's LOAD_FILE
{ "language": "en", "url": "https://stackoverflow.com/questions/17", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "198" }
"Q: What is the fastest way to get the value of π? I'm looking for the fastest way to obtain the va(...TRUNCATED)
{"language":"en","url":"https://stackoverflow.com/questions/19","timestamp":"2023-03-29T00:00:00","s(...TRUNCATED)
"Q: Throw an error preventing a table update in a MySQL trigger If I have a trigger before the updat(...TRUNCATED)
{"language":"en","url":"https://stackoverflow.com/questions/24","timestamp":"2023-03-29T00:00:00","s(...TRUNCATED)

The StackOverflow posts retrieval source for code-rag-bench.

Downloads last month
137

Collection including code-rag-bench/stackoverflow-posts