I was trying to make a small birthday (years) calculator, and somehow the value after the timespan disappears.
I've tried converting to DateTime and then to double but still no effect.
DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());
TimeSpan age = (today - b);
string s = age.ToString();
double final = double.Parse(s) / 365.2425;
Console.WriteLine("You have" + final + "years");
Use age.Days. age.ToString() will return you something like dddd.00:00:00 where dddd are days. But you only need days, so age.Days will do the job.
But I suggest that you use age.TotalDays because it returns a double so you don't have to parse it. Complete snippet:
DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());
TimeSpan age = (today - b);
double final = age.TotalDays / 365.2425;
Console.WriteLine("You have" + final + "years");
If you see the result of age.ToString() you will see a value like 10265.00:00:00 which cant be correctly parsed as double.
Use the .Days property of the TimeSpan class, and you can omit the parsing altogether.
DateTime today = DateTime.Today;
Console.WriteLine("Type your birthday: ");
DateTime b = DateTime.Parse(Console.ReadLine());
TimeSpan age = (today - b);
double final = age.Days / 365.2425;
Console.WriteLine("You have" + final + "years");
Related
Count Number of days by comapaing two date, When you want to compare two date like due Date and return date of a book in library then you can get no of days in this manner
int TotalDay;
DateTime due = OldDate;
int day = due.Day;
int nday = DateTime.Now.Day;
int mnt = due.Month;
int nmnt = DateTime.Now.Month;
int yr = due.Year;
int nyr = DateTime.Now.Year;
if (nyr <= yr)
{
if (nmnt <= mnt)
{
if (nday > day)
{
TotalDay = nday - day;
}
}
else
{
TotalDay = nday - day;
m = nmnt - mnt;
TotalDay = d + (m * 30);
}
}
else
{
TotalDay = nday - day;
m = nmnt - mnt;
TotalDay = d + (m * 30);
int y = nyr - yr;
TotalDay = d + (y * 365);
}
Use TimeSpan
TimeSpan ts = dateTime1 - dateTime2;
ts.TotalDays will give you the difference in number of days.
In your case due is the due date and DateTime.Now is the current date. You may use:
TimeSpan ts = DateTime.Now - due;
or use the TimeSpan.TotalDays property:
TimeSpan ts = DateTime.Now.Subtract(due);
double NumberOfDays = ts.TotalDays;
You could use TimeSpan as shown in other answers - but you need to be careful about the time of day. Are you actually trying to think of these as dates or as dates with times? What about time zones? Are you using "local" DateTime values for both?
While DateTime can handle all of this, it leaves things unclear. I'd personally use Noda Time (which shouldn't surprise anyone as it's my own library...)
LocalDate startDate = ...;
LocalDate endDate = ...;
long days = Period.Between(startDate, endDate, PeriodUnits.Days).Days;
Note that finding "today's date" requires knowing the appropriate time zone, too. (DateTime.Now and DateTime.Today assume the system time zone where your code is running, but that may or may not be what you want.)
You need TimeSpan
Timespan t = ReturnDateTime - DateTime.Now;
Then use
t.Days
for calculating how many days are left.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calculating age from birthday
How do you calculate age in years, taking input from TextBox in the format dd/MM/yyyy?
e.g.
input: txtDOB.Text 20/02/1989 (String format)
output: txtAge.Text 23
You can use the Substract method of DateTime (link) and then use the Days property to determine the actual age:
DateTime now = DateTime.Now;
DateTime givenDate = DateTime.Parse(input);
int days = now.Subtract(givenDate).Days
int age = Math.Floor(days / 365.24219)
TimeSpan TS = DateTime.Now - new DateTime(1989, 02, 20);
double Years = TS.TotalDays / 365.25; // 365 1/4 days per year
As already noted in a comment, the correct answer is here: Calculate age in C#
You just need to get the birthday as a DateTime:
DateTime bday = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
The following will work once you have parsed the birth date into a DateTime:
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
Parse the date like so:
DateTime dob = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", CultureInfo.InvariantCulture);
And a sample program:
using System;
namespace Demo
{
class Program
{
static void Main(string[] args)
{
DateTime dob = new DateTime(2010, 12, 30);
DateTime today = DateTime.Now;
int age = AgeInYears(dob, today);
Console.WriteLine(age); // Prints "1"
}
static int AgeInYears(DateTime birthday, DateTime today)
{
return ((today.Year - birthday.Year) * 372 + (today.Month - birthday.Month) * 31 + (today.Day - birthday.Day)) / 372;
}
}
}
This answer isn't the most efficient as it uses a loop, but it doesn't rely on using 365.25 magic numbers either.
A function to return the whole number of years from a datetime to today:
public static int CalcYears(DateTime fromDate)
{
int years = 0;
DateTime toDate = DateTime.Now;
while (toDate.AddYears(-1) >= fromDate)
{
years++;
toDate = toDate.AddYears(-1);
}
return years;
}
Usage:
int age = CalcYears(DateTime.ParseExact(txtDateOfBirth.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture));
var date = DateTime.ParseExact("20/02/1989", "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
var age = (DateTime.Today.Year - date.Year);
Console.WriteLine(age);
Try this
string[] AgeVal=textbox.text.split('/');
string Year=AgeVal[2].tostring();
string CurrentYear= DateTime.Now.Date.Year.ToString();
int Age=Convert.ToInt16((Current))-Convert.ToInt16((Year));
Subtract the two values and get your age.
I have two times, and their values are picked up from a XML from web.
XElement xmlWdata = XElement.Parse(e.Result);
string SunRise = xmlWdata.Element("sun").Attribute("rise").Value;
string SunSet = xmlWdata.Element("sun").Attribute("set").Value;
DateTime sunrise = Convert.ToDateTime(SunRise.Remove(0,11));
DateTime sunset = Convert.ToDateTime(SunSet.Remove(0, 11));
This gives med the time: 04:28 for sunrise, and 22:00 for sunset.
How to then do a calculation where i take:
(sunrise + (sunset-sunrise)/2)
I think you want to do this:
TimeSpan span = sunset-sunrise;
TimeSpan half = new TimeSpan(span.Ticks / 2);
DateTime result = sunrise + half;
It can be written in one line if you want.
TimeSpan sunnyTime = TimeSpan.FromTick(sunrise.Ticks + (sunset.Ticks - sunrise.Ticks) / 2);
How do I subtract two DateTime values from another DateTime value and have the result saved to a double?
In .NET, if you subtract one DateTime object from another, you will get a TimeSpan object. You can then use the Ticks property on that TimeSpan object to get the number of ticks between the two DateTime objects. However, the ticks will be represented by a Long, not a Double.
DateTime date1;
DateTime date2;
Long diffTicks = (date2 - date1).Ticks;
There are other interesting properties on the TimeSpan object like TotalMilliseconds and TotalMinutes and things like that which can help you out, and may be more what you are looking for.
DateTime startTime = DateTime.Now;
DateTime endTime = DateTime.Now.AddSeconds( 75 );
TimeSpan span = endTime.Subtract ( startTime );
Console.WriteLine( "Time Difference (seconds): " + span.Seconds );
Console.WriteLine( "Time Difference (minutes): " + span.Minutes );
Console.WriteLine( "Time Difference (hours): " + span.Hours );
Console.WriteLine( "Time Difference (days): " + span.Days );
I think this is what you need.
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.UtcNow;
var result = d1 - d2;
double dResult = result.Ticks;
Use DateTime.Subtract which will return TimeSpan , then use TotalSeconds property of the result which is of type double.
var Date1 = new DateTime(2018, 12, 15);
var Date2 = new DateTime(2019, 1, 1);
TimeSpan result1 = Date2.Subtract(Date1);
Console.WriteLine(result1);
//To calculate difference between two dates use TotalDays() method
double result2 = Date2.Subtract(Date1).TotalDays;
Console.WriteLine(result2);
//Output:
17.00:00:00
17
Note:
Date2 should be greater than Date1 or else the method will return a negative value
Subtract() method returns value of type TimeSpan while TotalDays() method returns value of type double
You should try in this.
DateTime prevDate = DateTime.Parse("25-Feb-2011 12:30");
double subDouble = DateTime.Now.Ticks - prevDate.Ticks;
I am not sure what is you want to store
if you need a double
double difference = date2.ToOADate() - date1.ToOADate();
I see that this question has been answered for Java, JavaScript, and PHP, but not C#. So, how might one calculate the number of days between two dates in C#?
Assuming StartDate and EndDate are of type DateTime:
(EndDate - StartDate).TotalDays
The top answer is correct, however if you would like only WHOLE days as an int and are happy to forgo the time component of the date then consider:
(EndDate.Date - StartDate.Date).Days
Again assuming StartDate and EndDate are of type DateTime.
Use TimeSpan object which is the result of date substraction:
DateTime d1;
DateTime d2;
return (d1 - d2).TotalDays;
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
DateTime xmas = new DateTime(2009, 12, 25);
double daysUntilChristmas = xmas.Subtract(DateTime.Today).TotalDays;
// Difference in days, hours, and minutes.
TimeSpan ts = EndDate - StartDate;
// Difference in days.
int differenceInDays = ts.Days; // This is in int
double differenceInDays= ts.TotalDays; // This is in double
// Difference in Hours.
int differenceInHours = ts.Hours; // This is in int
double differenceInHours= ts.TotalHours; // This is in double
// Difference in Minutes.
int differenceInMinutes = ts.Minutes; // This is in int
double differenceInMinutes= ts.TotalMinutes; // This is in double
You can also get the difference in seconds, milliseconds and ticks.
In case someone wants numer of whole days as a double (a, b of type DateTime):
(a.Date - b.Date).TotalDays
There often is a debate on time (hours) when it comes to counting days between two dates. The responses to the question and their comments show no exception.
Considering StartDate and EndDate are of type DateTime: if performance is not a concern, I would strongly recommend documenting your calculation through intermediate conversions. For example, (EndDate - StartDate).Days is unintuitive because rounding will depend on the hour component of StartDate and EndDate.
If you want the duration in days to include fractions of days, then as already suggested
use (EndDate - StartDate).TotalDays.
If you want the duration to reflect
the distance between two days, then use (EndDate.Date - StartDate.Date).Days
If you want the duration to reflect the
duration between the morning of the start date, and the evening of
the end date (what you typically see in project management software), then use
(EndDate.Date - StartDate.Date).Days + 1
You can try this
EndDate.Date.Subtract(DateTime.Now.Date).Days
Using a timespan would solve the problems as it has many attributes:
DateTime strt_date = DateTime.Now;
DateTime end_date = Convert.ToDateTime("10/1/2017 23:59:59");
//DateTime add_days = end_date.AddDays(1);
TimeSpan nod = (end_date - strt_date);
Console.WriteLine(strt_date + "" + end_date + "" + "" + nod.TotalHours + "");
Console.ReadKey();
For a and b as two DateTime types:
DateTime d = DateTime.Now;
DateTime c = DateTime.Now;
c = d.AddDays(145);
string cc;
Console.WriteLine(d);
Console.WriteLine(c);
var t = (c - d).Days;
Console.WriteLine(t);
cc = Console.ReadLine();
For beginners like me that will stumble upon this tiny problem, in a simple line, with sample conversion to int:
int totalDays = Convert.ToInt32((DateTime.UtcNow.Date - myDateTime.Date).TotalDays);
This calculates the total days from today (DateTime.UtcNow.Date) to a desired date (myDateTime.Date).
If myDateTime is yesterday, or older date than today, this will give a positive (+) integer result.
On the other side, if the myDateTime is tomorrow or on the future date, this will give a negative (-) integer result due to rules of addition.
Happy coding! ^_^
First declare a class that will return later:
public void date()
{
Datetime startdate;
Datetime enddate;
Timespan remaindate;
startdate = DateTime.Parse(txtstartdate.Text).Date;
enddate = DateTime.Parse(txtenddate.Text).Date;
remaindate = enddate - startdate;
if (remaindate != null)
{
lblmsg.Text = "you have left with " + remaindate.TotalDays + "days.";
}
else
{
lblmsg.Text = "correct your code again.";
}
}
protected void btncal_Click(object sender, EventArgs e)
{
date();
}
Use a button control to call the above class. Here is an example:
You can use the code below:
int DateDifInSecond = EndDate.Subtract(StartDate).TotalSeconds
Get the difference between the two dates and then get the days from:
int total_days = (EndDate - StartDate).TotalDays
try this truly worked Get actual days diff. date format is "dd/MM/yyyy"
string[] d1 = txtFromDate.Values.Split('/');
string[] d2 = txtToDate.Values.Split('/');
DateTime FrmDt = new DateTime(Convert.ToInt32(d1[2]), Convert.ToInt32(d1[1]), Convert.ToInt32(d1[0]));
DateTime ToDt = new DateTime(Convert.ToInt32(d2[2]), Convert.ToInt32(d2[1]), Convert.ToInt32(d2[0]));
TimeSpan TDiff = ToDt.Subtract(FrmDt);
String DaysDiff = TDiff.TotalDays.ToString();
protected void Calendar1_SelectionChanged(object sender, EventArgs e)
{
DateTime d = Calendar1.SelectedDate;
// int a;
TextBox2.Text = d.ToShortDateString();
string s = Convert.ToDateTime(TextBox2.Text).ToShortDateString();
string s1 = Convert.ToDateTime(Label7.Text).ToShortDateString();
DateTime dt = Convert.ToDateTime(s).Date;
DateTime dt1 = Convert.ToDateTime(s1).Date;
if (dt <= dt1)
{
Response.Write("<script>alert(' Not a valid Date to extend warranty')</script>");
}
else
{
string diff = dt.Subtract(dt1).ToString();
Response.Write(diff);
Label18.Text = diff;
Session["diff"] = Label18.Text;
}
}