private void button1_Click(object sender, EventArgs e)     {         DateTime dob = new DateTime();         textBox1.Text = dob.ToString();         int age;         age = Convert.ToInt32(textbox2.Text);         age = DateTime.Now.Year - dob.Year;         if (DateTime.Now.DayOfYear &lt; dob.DayOfYear)             age = age - 1;      }   How to claculate the age from dob.This is my form1.cs.any ideas please
1660
Given a DateTime representing a person's birthday, how do I calculate their age in years?
9379
What would be the best way to calculate someone's age in years, months, and days in T-SQL (SQL Server 2000)?  The datediff function doesn't handle year boundaries well, plus getting the months and days separate will be a bear.  I know I can do it on the client side relatively easily, but I'd like to have it done in my .
103578
I'm trying to call a stored procedure (on a SQL 2005 server) from C#, .NET 2.0 using DateTime as a value to a SqlParameter.  The SQL type in the stored procedure is 'datetime'.  Executing the sproc from SQL Management Studio works fine.  But everytime I call it from C# I get an error about the date format.    When I run SQL Profiler to watch the calls, I then copy paste the exec call to see what's going on.  These are my observations and notes about what I've attempted:  1)  If I pass the DateTime in directly as a DateTime or converted to SqlDateTime, the field is surrounding by a PAIR of single quotes, such as  @Date_Of_Birth=N''1/8/2009 8:06:17 PM''   2)  If I pass the DateTime in as a string, I only get the single quotes  3)  Using SqlDateTime.ToSqlString() does not result in a UTC formatted datetime string (even after converting to universal time)  4)  Using DateTime.ToString() does not result in a UTC formatted datetime string.  5)  Manually setting the DbType for the SqlParameter to DateTime does not change the above observations.  So, my questions then, is how on earth do I get C# to pass the properly formatted time in the SqlParameter?  Surely this is a common use case, why is it so difficult to get working?  I can't seem to convert DateTime to a string that is SQL compatable (e.g. '2009-01-08T08:22:45')  EDIT  RE: BFree, the code to actually execute the sproc is as follows:  using (SqlCommand sprocCommand = new SqlCommand(sprocName)) {     sprocCommand.Connection = transaction.Connection;     sprocCommand.Transaction = transaction;     sprocCommand.CommandType = System.Data.CommandType.StoredProcedure;     sprocCommand.Parameters.AddRange(parameters.ToArray());     sprocCommand.ExecuteNonQuery(); }   To go into more detail about what I have tried:  parameters.Add(new SqlParameter("@Date_Of_Birth", DOB));  parameters.Add(new SqlParameter("@Date_Of_Birth", DOB.ToUniversalTime()));  parameters.Add(new SqlParameter("@Date_Of_Birth",      DOB.ToUniversalTime().ToString()));  SqlParameter param = new SqlParameter("@Date_Of_Birth",      System.Data.SqlDbType.DateTime); param.Value = DOB.ToUniversalTime(); parameters.Add(param);  SqlParameter param = new SqlParameter("@Date_Of_Birth",      SqlDbType.DateTime); param.Value = new SqlDateTime(DOB.ToUniversalTime()); parameters.Add(param);  parameters.Add(new SqlParameter("@Date_Of_Birth",      new SqlDateTime(DOB.ToUniversalTime()).ToSqlString()));   Additional EDIT  The one I thought most likely to work:  SqlParameter param = new SqlParameter("@Date_Of_Birth",       System.Data.SqlDbType.DateTime); param.Value = DOB;   Results in this value in the exec call as seen in the SQL Profiler  @Date_Of_Birth=''2009-01-08 15:08:21:813''   If I modify this to be:  @Date_Of_Birth='2009-01-08T15:08:21'   It works, but it won't parse with pair of single quotes, and it wont convert to a DateTime correctly with the space between the date and time and with the milliseconds on the end.  Update and Success  I had copy/pasted the code above after the request from below.  I trimmed things here and there to be concise.  Turns out my problem was in the code I left out, which I'm sure any one of you would have spotted in an instant.  I had wrapped my sproc calls inside a transaction.  Turns out that I was simply not doing transaction.Commit()!!!!!  I'm ashamed to say it, but there you have it.  I still don't know what's going on with the syntax I get back from the profiler.  A coworker watched with his own instance of the profiler from his computer, and it returned proper syntax.  Watching the very SAME executions from my profiler showed the incorrect syntax.  It acted as a red-herring, making me believe there was a query syntax problem instead of the much more simple and true answer, which was that I need to commit the transaction!    I marked an answer below as correct, and threw in some up-votes on others because they did, after all, answer the question, even if they didn't fix my specific (brain lapse) issue.
31644
I'm looking for a clear, concise and accurate answer.    Ideally as the actual answer, although links to good explanations welcome.  This also applies to VB.Net, but the keywords are different - ByRef and ByVal.
51350
I want to record the time using System.currentTimeMillis() when a user begins something in my program. When he finishes, I will subtract the current System.currentTimeMillis() from the start variable, and I want to show them the time elapsed using a human readable format such as "XX hours, XX mins, XX seconds" or even "XX mins, XX seconds" because its not likely to take someone an hour.  What's the best way to do this?
2568
I saw a potential answer here but that was for YYYY-MM-DD:   I modified the code code above for MM-DD-YYYY like so but I still can't get it to work:  String.prototype.isValidDate = function()  {      var IsoDateRe = new RegExp("^([0-9]{2})-([0-9]{2})-([0-9]{4})$");      var matches = IsoDateRe.exec(this);      if (!matches) return false;      var composedDate = new Date(matches[3], (matches[1] - 1), matches[2]);      return ((composedDate.getMonth() == (matches[1] - 1)) &amp;&amp;       (composedDate.getDate() == matches[2]) &amp;&amp;       (composedDate.getFullYear() == matches[3])); }   How can I get the above code to work for MM-DD-YYYY and better yet MM/DD/YYYY?  Thanks.
71224
I have this function...  private string dateConvert(string datDate) {         System.Globalization.CultureInfo cultEnGb = new System.Globalization.CultureInfo("en-GB");         System.Globalization.CultureInfo cultEnUs = new System.Globalization.CultureInfo("en-US");          DateTime dtGb = Convert.ToDateTime(datDate, cultEnGb.DateTimeFormat);         datDate = dtGb.ToString(cultEnUs.DateTimeFormat.ShortDatePattern);          return datDate; }   But I want it with the leading zero still on lower digits (1-9) so the date is 11-09-2009 (mm-dd-yyyy)...  Now If I wasn't converting it id use string.Format("{0:d}", dateVar) how do I do this in the conversion?  ***** Solution ***** Used a slightly modified version of the answer below (i.e. one that would render).  Convert.ToDateTime(datDate).ToString("MM-dd-yyyy");
76797
I'm using a DateTime in C# to display times. What date portion does everyone use when constructing a time?  E.g. the following is not valid because there is no zero-th month or zero-th day:  // 4:37:58 PM DateTime time = new DateTime(0, 0, 0, 16, 47, 58);   Do I use COM's zero date?  // 4:37:58 PM DateTime time = new DateTime(1899, 12, 30, 16, 47, 58);   Or perhaps SQL Server's?  //4:37:58 PM DateTime time = new DateTime(1900, 1, 1, 16, 47, 58);   I realize it's arbitrary, since I'll be ignoring the date portions in code, but it would still be nice to be able to use:  DateTime duration = time2 - time1;     Answer  I think I like MinValue   DateTime time = DateTime.MinValue.Date.Add(new TimeSpan(16, 47, 58));     Note: I can't use a TimeSpan, because that doesn't store times of the day. And the reason I know that is because there's no way to display its contents as a time.  Which is to say that TimeSpan records a span of time, not a time of day, e.g.:  TimeSpan t = new TimeSpan(16, 47, 58); t.ToString();   returns a span of time in the format hours:minutes:seconds, e.g.:  16:47:58   rather than a time:  4:47:58 PM    (United States) 04:47:58 nm   (South Africa) 4:47:58.MD    (Albania) 16:47:58      (Algeria) 04:47:58 م    (Bahrain) PM 4:47:58    (Singapore) 下午 04:47:58  (Taiwan) 04:47:58 PM   (Belize) 4:47:58 p.m.  (New Zealand) 4:47:58 μμ    (Greece) 16.47.58      (Italy) 오후 4:47:58   (Korea) 04:47:58 ب.ظ  (Iran) ਸ਼ਾਮ 04:47:58   (India) 04:47:58 p.m. (Argentina) etc   In other words, there is a difference between a timespan, and a time. And also realize that TimeSpan doesn't provide a mechanism to convert a span of time into a time of day - and there is a reason for that.
79610
an example code what I try to do will surely do better than my english:  public bool IsNumericValueInBounds (string value, Type numericType) {   double d = double.NaN;         bool inBounds = (bool)numericType.GetMethod ("TryParse").Invoke (null, new object[] { value, d });    return inBounds; }   Unfortunately the TryParse method needs an out parameter so this doesn't work. any ideas how to solve this?  (ps.: would'nt this be a nice example for duck typing? - because i know every numericType has an "TryParse" or I am mistaken?)
12890
I am using the datetime Python module.  I am looking to calculate the date 6 months from the current date. Could someone give me a little help doing this?  The reason I want to generate a date 6 months from the current date is to produce a review date.  If the user enters data into the system it will have a review date of 6 months from the date they entered the data.
11000
What is the difference between Parse() and TryParse()?  int number = int.Parse(textBoxNumber.Text);  // The Try-Parse Method int.TryParse(textBoxNumber.Text, out number);   Is there some form of error-checking like a Try-Catch Block?
30301
I've tried this:  string newScript = textBox1.Text; HtmlElement head = browserCtrl.Document.GetElementsByTagName("head")[0]; HtmlElement scriptEl = browserCtrl.Document.CreateElement("script"); lblStatus.Text = scriptEl.GetType().ToString(); scriptEl.SetAttribute("type", "text/javascript"); head.AppendChild(scriptEl); scriptEl.InnerHtml = "function sayHello() { alert('hello') }";   scriptEl.InnerHtml and scriptEl.InnerText both give errors:  System.NotSupportedException: Property is not supported on this type of HtmlElement.    at System.Windows.Forms.HtmlElement.set_InnerHtml(String value)    at SForceApp.Form1.button1_Click(Object sender, EventArgs e) in d:\jsight\installs\SForceApp\SForceApp\Form1.cs:line 31    at System.Windows.Forms.Control.OnClick(EventArgs e)    at System.Windows.Forms.Button.OnClick(EventArgs e)    at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)    at System.Windows.Forms.Control.WmMouseUp(Message&amp; m, MouseButtons button, Int32 clicks)    at System.Windows.Forms.Control.WndProc(Message&amp; m)    at System.Windows.Forms.ButtonBase.WndProc(Message&amp; m)    at System.Windows.Forms.Button.WndProc(Message&amp; m)    at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m)    at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)   Is there an easy way to inject a script into the dom?
113519
I'm having a save method with several Conditions in it.Here is my apex class  invoiceset = [select SiteUrl__c, Prefix__c,Seperator__c,Seperator1__c,DateValue__c,DateValue1__c,Date_Format__c,Incrementer__c,Counter_Val1__c,counter__c from Invoice_setting__c limit 1];        if(invoiceSet[0].DateValue__c == 'Date' &amp;&amp; invoiceSet[0].DateValue1__c == 'Date'){         if(invoiceSet[0].Date_Format__c == 'dd-mm-yyyy'){              datenow = DateTime.now().format('dd-MM-yyyy');                   }else if(invoiceSet[0].Date_Format__c == 'MM-dd-yyyy'){              datenow = DateTime.now().format('MM-dd-yyyy');                     }else if(invoiceSet[0].Date_Format__c == 'dd/MM/yyyy'){              datenow = DateTime.now().format('dd/MM/yyyy');          }else if(invoiceSet[0].Date_Format__c == 'mm/dd/yyyy'){              datenow = DateTime.now().format('mm/dd/yyyy');          }else if(invoiceSet[0].Date_Format__c == 'yy'){              datenow = DateTime.now().format('yy');          }else if(invoiceSet[0].Date_Format__c == 'yyyy'){              datenow = DateTime.now().format('yyyy');          }           prefixName = invoiceset[0].prefix__c + invoiceSet[0].seperator__c + datenow + invoiceset[0].Seperator1__c + datenow;       }      else if(invoiceSet[0].DateValue__c == 'Counter' &amp;&amp; invoiceSet[0].DateValue1__c == 'Counter'){       if(invoiceSet[0].counter_val1__c == null){          invoiceSet[0].Counter_Val1__c = invoiceset[0].Counter__c;        }else if(invoiceSet[0].Counter_Val1__c == invoiceset[0].Counter__c){            intt = integer.valueof(invoiceSet[0].Counter__c) + integer.valueOf(invoiceSet[0].Incrementer__c) ;            invoiceSet[0].Counter_Val1__c = string.valueOf(intt) ;        }else {             intt = integer.valueof(invoiceSet[0].Counter_Val1__c) + integer.valueOf(invoiceSet[0].Incrementer__c) ;            invoiceSet[0].Counter_Val1__c = string.valueOf(intt) ;        }        update invoiceset;         prefixName = invoiceset[0].prefix__c + invoiceSet[0].seperator__c + invoiceSet[0].Counter_Val1__c + invoiceset[0].Seperator1__c +invoiceset[0].Counter_Val1__c;       } &amp;&amp; so on........   Inorder to cover all this conditions should I write those many methods or any other easy way?  Here is my Test Code  public static testmethod void test(){    invoice_setting__c setng = new invoice_setting__c(Name='Invoice Settings',SiteUrl__c='www.google.com',Prefix__c='Test',Seperator__c = '-',dateValue__c = 'Date',Seperator1__c = '/',dateValue1__c = 'Date',date_format__c='dd-mm-yyyy');     insert setng; } public static testmethod void test1(){     invoice_setting__c setng1 = new invoice_setting__c(Name='Invoice Settings',Prefix__c='Test',Seperator__c = '-',dateValue__c = 'Counter',Seperator1__c = '/',Counter_Val1__c=null,dateValue1__c = 'Counter',date_format__c='dd-mm-yyyy',Incrementer__c='10');     insert setng1; } &amp; so on......   Any Suggestions for this please
122501
The following code returns the time of the current date:  System.debug('Current date: ' + Date.today().toStartOfMonth());   Output:     2018-08-01 00:00:00   How to remove time from date?
93098
In SQL Server, how do I "floor" a DATETIME to the second/minute/hour/day/year?  Let's say that I have a date of 2008-09-17 12:56:53.430, then the output of flooring should be:   Year:  2008-01-01 00:00:00.000 Month: 2008-09-01 00:00:00.000 Day: 2008-09-17 00:00:00.000 Hour: 2008-09-17 12:00:00.000 Minute: 2008-09-17 12:56:00.000 Second: 2008-09-17 12:56:53.000
88507
I have a string as,  field name : start Date: 2016-11-14 08:00 AM ( string type)  how to convert this to Date time. I tried Date.parseDate and below option also.  String val = recruiters[j].Start_Time_Formula__c;                              system.debug('val ::'+ val);                             DateTime date1 = (DateTime)Json.deserialize('"'+val+'"', DateTime.class);                             system.debug('date1 ::' + date1);   but I am getting error as,     System.JSONException: Invalid format: "2016-11-14 08:00 AM" is malformed at " 08:00 AM": (System Code)   I referred the below link and got with the above error.    any help ?
99745
Is there a way to display previous and current year with dynamic text?    If so, what is the formatting?   I'm using ArcMap 10.0