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);
Related
I have two times like 100:45 and 395:50
I need to find the subtraction and addition between these two times in the asp.net web application
I will expect like this 100:45+395:50=496:35 and 100:45-395:50=295:05
assuming the times are given in a string. then you can split the times to get the equivalent minutes. now it becomes a simple mathematics problem and now perform addition and subtraction accordingly.
string time = "100:45";
string[] parts = time.Split(':');
int hours = int.Parse(parts[0]);
int minutes = int.Parse(parts[1]);
int totalMinutes = hours * 60 + minutes;
so for your case
int mins1 = 100 * 60 + 45;
int mins2 = 395 * 60 + 50;
int totalMinutes = mins1 + mins2;
int totalHours = totalMinutes / 60;
int remainingMinutes = totalMinutes % 60;
string sum = $"{totalHours}:{remainingMinutes}";
use the same concept to get the subtraction as well.
You can convert times to TimeSpan.FromMinutes and to get the desired output using TimeSpan.TotalHours and TimeSpan.Minutes
string s1 = "100:45";
string s2 = "395:50";
TimeSpan spWorkMin = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 +
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) +
int.Parse(s2.Split(':')[1]));
var sum =string.Format("{0:00}:{1:00}", (int)tSum.TotalHours, tSum.Minutes);//496:35
TimeSpan tsub = TimeSpan.FromMinutes(int.Parse(s1.Split(':')[0]) * 60 -
int.Parse(s2.Split(':')[0]) * 60 +
int.Parse(s1.Split(':')[1]) -
int.Parse(s2.Split(':')[1]));
var subtract = string.Format("{0:00}:{1:00}", Math.Abs((int)tsub.TotalHours),Math.Abs(tsub.Minutes)); //295:05
TimeSpan do the trick
TimeSpan ts1 = new TimeSpan(0, 100, 45);
TimeSpan ts2 = new TimeSpan(0, 395, 50);
var tsResult = ts1 + ts2;
string outPut = string.Format("{0}:{1}", Math.Floor(tsResult.TotalMinutes), tsResult.Seconds);
I am having a date with microseconds, it is calculated by adding ticks from 2000.1.1 basically it works and it looks like:
ulong timestampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = new DateTime(2000, 1, 1, 0, 0, 0);
string dateWithMicroseconds = startDate.AddTicks((long)timestampInTicks).ToString("HH:mm:ss.ffffff");
Problem is with return format, it returns me something like 19:34:34:260100 so miliseconds and microseconds are combined when i try HH:mm:ss.fff:fff I am getting 19:34:34:260:260 so milliseconds are doubled. Is there a way, except for using splitting string, for doing this??
Simplest custom implementation I could think of..
ulong ExtendedTimestamp = 99;
ulong timeStampInTicks = ExtendedTimestamp * TimeSpan.TicksPerMillisecond / 10;
var startDate = DateTime.Now;
string dateWithMicroseconds = startDate.AddTicks((long)timeStampInTicks).ToString("HH:mm:ss.ffffff");
string dateHHmmss = dateWithMicroseconds.Split('.')[0];
string timeffffff = dateWithMicroseconds.Split('.')[1];
int precision = 3;
string milliSecs = timeffffff.Substring(0, precision);
string microSecs = timeffffff.Substring(precision, timeffffff.Length - precision);
string customFormat = string.Format("{0}:{1}:{2}", dateHHmmss, milliSecs, microSecs);
since the microsecond is millisecond/1000, so as in reference to this date the format will return 01.01.2008 00:30:45.125.125000. Milliseconds: 125, Microseconds:125000
DateTime dates = new DateTime(2000, 1, 1, 0, 30, 45, 125);
Console.WriteLine("Date with micro and milliseconds: {0:MM/dd/yyy HH:mm:ss.fff.ffffff}",dates);
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");
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
I cant seem to get this to parse into a DateTime
double tsMin = Convert.ToDouble(ts);
double tsMinTot = ts.TotalMinutes;
short tsMinPercent = (short)(((double)tsMinTot) * PERCENT);
double tsAndPercentTot = tsMinPercent + tsMinTot;
My goal here was to find a timediff, find what 25% of that timediff is and add it to the timediff.
DateTime newTimeMinTot = Convert.ToDateTime(tsAndPercentTot);
int hours = newTimeMinTot.Hour;
int minutes = newTimeMinTot.Minute;
An attempt to get a calculated new Datetime
string newTimeStrg = string.Format("{0:d1}:{1:d2}", hours, minutes);
txtB_NewDelivT.Text = newTimeStrg;
Attempt to output new DateTime to TextBox.
Someone please explain. How can I make the user input in military time and make this work.
Do it like this:
const double PERCENT = 0.25;
DateTime t1 = Convert.ToDateTime(txtB_StartT.Text);
DateTime t2 = Convert.ToDateTime(txtB_EndT.Text);
TimeSpan ts = t1.Subtract(t2);
long tsMinPercent = ts.Ticks + (long)(ts.Ticks * PERCENT);
var tsAndPercentTot = TimeSpan.FromTicks(tsMinPercent);
string newTimeStrg = string.Format("{0:d1}:{1:d2}", tsAndPercentTot.Hours, tsAndPercentTot.Minutes);
txtB_NewDelivT.Text = newTimeStrg;
Here I am using DateTime.Ticks to calculate percentage of time of difference and TimeSpan.FromTicks to find DateTime again from calculated percentage DateTime.
Instead using TextBox you can use TimePicker.
to force your date/datetime format
DateTime mydate = DateTime.ParseExact(TextBox1.Text.Trim(), "dd/MM/yyyy", null);
Based on your comment where you write that the input values are "0945" and "1445", I suggest you to replace your TextBox controls with DateTimePicker controls.
Just to have them display values as you are doing right now, you'll have to set some properties as I show you here.
picker.Format = DateTimePickerFormat.Custom;
picker.CustomFormat = "HHmm";
picker.ShowUpDown = true;
later, the picker.Value will return a whole date with time, where minutes and seconds will resemble the input values.
You can obvously set the properties' values from the designer.
Regards,
Daniele.
Since I don't have your form, I'll leave out the UI interaction. Here's how you can parse an input stream. I've show how to parse a hh:mm format, as well as a hhmm format:
var start = TimeSpan.ParseExact("10:00", "hh\\:mm", CultureInfo.InvariantCulture);
var finish = TimeSpan.ParseExact("1100", "hhmm", CultureInfo.InvariantCulture);
Once you have the start and finish, all we have to do is the math. We'll create a new TimeSpan from the ticks (the smallest unit of measurement on a TimeSpan) multiplied by our percentage (0.25). Then we just add the adjustment to our start time and we're done! You can then assign that into where ever you need the output.
var diff = finish - start;
var adjustment = TimeSpan.FromTicks((long)(diff.Ticks * 0.25));
var adjustedStart = start + adjustment;
You can run the code out at dotNetFiddle. I've included output there so you can see the intermediate results along the way.
Ok well i took a different approach and it worked out fairly easy.
I'm not sure if I'm allowed to answer my own question but i figure it
will help someone with the same issue i had.
// Set Constant values.
const double PERCENT = .25;
const int HUN_PART = 100, SIXTY = 60, one = 1;
// Parse start time textbox value as int
// Calculate start time hours and minutes
int sT = int.Parse(textBox1.Text);
int sH = sT / HUN_PART;
int sM = sT % HUN_PART;
// Calculate total start time in minutes
int sH_M = sH * SIXTY;
int sTotM = sH_M + sM;
// Parse end time textbox value as int
// Calculate end time hours and minutes
int eT = int.Parse(textBox2.Text);
int eH = eT / HUN_PART;
int eM = eT % HUN_PART;
// Calculate total end time in minutes
int eH_M = eH * SIXTY;
int eTotM = eH_M + eM;
// Calculate time difference in minutea
// Calculate percent of time difference
double dT_M = Convert.ToInt32(eTotM - sTotM);
int perc = Convert.ToInt32(dT_M * PERCENT);
// Calculate new arrival time in total min then in hours
double newD_M = perc + eTotM;
double newD_H = newD_M / SIXTY;
// Calculate new arrivaltime in remaining minutes
double nD_H_Convert = Math.Truncate(newD_H);
int nD_H = Convert.ToInt32(nD_H_Convert);
int nD_Hours = nD_H * HUN_PART;
double nD_Min = nD_H * SIXTY;
int nD_M = Convert.ToInt32(newD_M - nD_Min);
int newDeliveryTime = (nD_H * HUN_PART) + nD_M;
// Put values for new arive time hours and minutes in appropriate string format
string newTime = string.Format("{0:d4}", newDeliveryTime);
// Output arrival time string in textbox
textBox3.Text = newTime;
I was apparently trying to do more than was actually required, so by using a few simple calculations the issue was resolved.
Thank you for the help everyone.
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();