I have this code that calculates time. but when it goes in to the next day it sort of resets and doesn't keep going forward. what im trying to do is when it goes past 12AM, to keep counting the hours and print the result as 10, and not go back to 3
string entry_T = dt.Rows[0][3].ToString();
int delta_day = Int32.Parse(entry_T.Substring(8, 2)) - Int32.Parse(DT.Substring(8, 2));
int st_h = Int32.Parse(entry_T.Substring(11, 2));
int ed_h = Int32.Parse(DT.Substring(11, 2));
int st_m = Int32.Parse(entry_T.Substring(14, 2));
int ed_m = Int32.Parse(DT.Substring(14, 2));
double delta_T = ((ed_h + 24 * delta_day) * 60 + ed_m - st_h * 60 - st_m) / 60.0;
if (delta_T <= 1) print = 3;
else if (delta_T <= 2) print = 5;
else if (delta_T <= 3) print = 7;
else if (delta_T <= 4) print = 8;
else print = 10;
return cost;
You can subtract 2 DateTimes to get a TimeSpan.
var dt1 = DateTime.Parse(your_string);
var timeSpan = DateTime.Now - dt1;
//timeSpan will tell you the difference, corrected for anomalies like leap years.
see: https://learn.microsoft.com/en-us/dotnet/api/system.timespan?view=netcore-3.1
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 would like to write a converter from milliseconds to the highest possible time value before reaching a 0,x value.
Let me clarify this with examples.
Let's assume you have 1500ms this should result in 1,5secs, because its the highest possible digit value not resulting in 0,x.
So different examples would be
10ms = 10,0ms
100ms = 100,0ms
1000ms = 1,0sec
10000ms = 10,0sec
100000ms = 1,6min
1000000ms = 16,0min
10000000ms = 2,7hours
(The method should more or less be endless, so from hours to days, to weeks, to months, to years, to decades and so on...)
Is there a .net method for this?
Something like the following
public static string ConversionMethod(UInt64 ms)
{
// change output format as needed
string format = "######.###";
var cutoffs = new List<UInt64>() {
1000, // second
60000, // minute
3600000, // hour
86400000, // day
604800000, // week = day * 7
2592000000, // month = day * 30
31536000000, // year = day * 365
315360000000, // decade = year * 10
3153600000000, // century = decade * 10 (100 years)
31536000000000, // millenia = century * 10 (1000 years)
31536000000000000 // megayear = year * 100000
// 18446744073709551615 // UInt64 MaxValue
// 31536000000000000000 // gigayear = year * 100000000
};
var postfix = new List<String>() {
"second",
"minute",
"hour",
"day",
"week",
"month",
"year",
"decade",
"century",
"millenia",
"megayear"
};
// The above are listed from smallest to largest for easy reading,
// but the comparisons need to be made from largest to
// smallest (in the loop below)
cutoffs.Reverse();
postfix.Reverse();
int count = 0;
foreach (var cutoff in cutoffs)
{
if (ms > cutoff)
{
return ((decimal)((decimal)ms / (decimal)cutoff)).ToString(format) + " " + postfix[count];
}
count++;
}
return ms + " ms";
}
Conversion for the fraction is a bit dirty, might want to clean that up. Also, you'll have to decide how you want to handle leap years (and leap seconds), etc.
While not the final solution, maybe TimeSpan can help you achieve what you are looking for.
It is to be noted however, TimeSpan supports only up to TotalDays.
var timespan = TimeSpan.FromMilliseconds(1500);
var seconds = timespan.TotalSeconds; // equals: 1.5
It seems the TimeSpan class is the closest thing that meets your need, but clearly it's not exactly what you want. My take on it would look something like this:
public static string ScientificNotationTimespan(int milliseconds)
{
var timeSpan = new TimeSpan(0, 0, 0, 0, milliseconds);
var totalDays = timeSpan.TotalDays;
if (totalDays < 7)
{
if (timeSpan.TotalDays > 1) return timeSpan.TotalDays.ToString() + " days";
if (timeSpan.TotalHours > 1) return timeSpan.TotalHours.ToString() + " hours";
if (timeSpan.TotalMinutes > 1) return timeSpan.TotalMinutes.ToString() + " minutes";
if (timeSpan.TotalSeconds > 1) return timeSpan.TotalSeconds.ToString() + " seconds";
return milliseconds.ToString() + "milliseconds";
}
var weeks = totalDays / 7;
//How long is a month? 28, 29, 30 or 31 days?
var years = totalDays / 365;
if (years < 1) return weeks.ToString() + " weeks";
var decades = years / 10;
if (decades < 1) return years.ToString() + " years";
var centuries = decades / 10;
if (centuries < 1) return decades.ToString() + " decades";
var millenia = centuries / 10;
if (millenia < 1) return centuries.ToString() + " centuries";
return millenia.ToString() + " millenia";
}
Here is solution for years, months using DateTime and Gregorian calendar (meaning leap years, calendar months). Then it uses the TimeSpan solution as already submitted.
static string ToMostNonZeroTime(long ms) {
const int hundretsNanosecondsInMillisecond = 10000;
long ticks = (long)ms * hundretsNanosecondsInMillisecond;
var dt = new DateTime(ticks);
if((dt.Year - 1) > 0) { // starts with 1
double daysToYear = (dt.DayOfYear - 1) * 1.0 / (DateTime.IsLeapYear(dt.Year) ? 366 : 365);
daysToYear += dt.Year - 1;
return $"{daysToYear:0.0} years";
}
if((dt.Month - 1) > 0) {
double daysToMonth = (dt.Day - 1) * 1.0 / DateTime.DaysInMonth(dt.Year, dt.Month);
daysToMonth += dt.Day - 1;
return $"{daysToMonth:0.0} months";
}
// can use TimeSpan then:
var ts = TimeSpan.FromMilliseconds(ms);
if(ts.TotalDays >= 1)
return $"{ts.TotalDays:0.0} days";
if(ts.TotalHours >= 1)
return $"{ts.TotalHours:0.0} hours";
if(ts.TotalMinutes >= 1)
return $"{ts.TotalMinutes:0.0} minutes";
if(ts.TotalSeconds >= 1)
return $"{ts.TotalSeconds:0.0} seconds";
return $"{ms} milliseconds";
}
It prints
100ms: 100 milliseconds
1000ms: 1.0 seconds
10000ms: 10.0 seconds
100000ms: 1.7 minutes
1000000ms: 16.7 minutes
10000000ms: 2.8 hours
100000000ms: 1.2 days
1000000000ms: 11.6 days
20000000000ms: 19.6 months
200000000000ms: 6.3 years
Have a look at https://ideone.com/QZHOM4
I'm trying to convert a Julian Date which includes hours minutes and seconds to a DateTime in C#.
This is the number: 2457285.7795969
I can calculate the DateTime excluding the hours and the minutes with this function.
public static DateTime FromJulian(long julianDate)
{
long L = julianDate + 68569;
long N = (long)((4 * L) / 146097);
L = L - ((long)((146097 * N + 3) / 4));
long I = (long)((4000 * (L + 1) / 1461001));
L = L - (long)((1461 * I) / 4) + 31;
long J = (long)((80 * L) / 2447);
int Day = (int)(L - (long)((2447 * J) / 80));
L = (long)(J / 11);
int Month = (int)(J + 2 - 12 * L);
int Year = (int)(100 * (N - 49) + I + L);
return new DateTime(Year, Month, Day);
}
It should be as simple as:
public static DateTime FromJulian(double julianDate)
{
return new DateTime(
(long)((julianDate - 1721425.5) * TimeSpan.TicksPerDay),
DateTimeKind.Utc);
}
As you can see, 1721425.5 is the so-called Gregorian epoch, i.e. the value the Julian date had at the beginning of the proleptic Gregorian calendar, at 0001 January 1, 00:00:00.0000000, where the .NET DateTime has its origin.
EDIT: If you want to make sure your method throws an exception on "extreme" inputs instead of returning an invalid value, do this:
public static DateTime FromJulian(double julianDate)
{
return new DateTime(
checked((long)((julianDate - 1721425.5) * TimeSpan.TicksPerDay)),
DateTimeKind.Utc);
}
Note that we do the multiplication with the double operator *(double, double) overload (built-in in C#). This gives an error as little as possible. The conversion from double to long will throw in checked context if the double is outside the range of long. If that conversion goes well, the DateTime constructor may throw if the value of the long is out of range for a .NET DateTime.
NEW EDIT: Inspired by another thread (Convert DateTime to Julian Date in C# (ToOADate Safe?)) you can also work out a very simple solution using DateTime.FromOADate. However, see another Stack Overflow post by myself on precision short-comings of the FromOADate method.
Is this what you are looking for: Convert Julian Date with Time (H/m/s) to Date Time in C#?
Applying that answer, converting your value of 2457285.7795969 results in 9/19/2015 11:42:37 PM.
Before Ladi answered with what I was looking for....
double L = DateTime.Now.ToOADate() + 2415018.5 + 68569;
double HMS = L-(int)L-0.5;
int Hours = (int)(24*HMS);
HMS=HMS - (double)(Hours/24.0);
int Mins = (int)(24*60*HMS);
HMS=HMS - (double)(Mins/(24.0*60));
int Secs = (int)(24*60*60*HMS);
long N = (long)((4 * L) / 146097);
L = L - ((long)((146097 * N + 3) / 4));
long I = (long)((4000 * (L + 1) / 1461001));
L = L - (long)((1461 * I) / 4) + 31;
long J = (long)((80 * L) / 2447);
int Day = (int)(L - (long)((2447 * J) / 80));
L = (long)(J / 11);
int Month = (int)(J + 2 - 12 * L);
int Year = (int)(100 * (N - 49) + I + L);
DateTime test = new DateTime(Year, Month, Day);
Console.WriteLine("Hours-"+Hours);
Console.WriteLine("Mins-" + Mins);
Console.WriteLine("Secs-"+ Secs);
Console.WriteLine(test);
Console.WriteLine(DateTime.Now.ToString());
I have two properties of time stamp without AM/PM. What's needed is to find the total time spent in quarter unit determined by _factor. Then there is a rounddown & roundup concept which is determined by _roundDown value as cut off point. Finally, returning a decimal value back after the calculation.
This resides in a class definition that sets up a property TotalTime. Because of this reason, I would like the code to be efficient. Excuse my code as this is the last piece of the project and want to get it done.
How can I improve the code: I am using mod calculation.
private decimal ComputeTotalTime(int _increment)
{
decimal _TotalHours = 0;
int _roundDown = 7, _factor = 15;
int int_TotalHours = 0;
if (String.IsNullOrEmpty(StartTime) || String.IsNullOrEmpty(EndTime)) return _TotalHours;
DateTime timeFromInput = DateTime.ParseExact(StartTime, "H:m", null);
DateTime timeToInput = DateTime.ParseExact(EndTime, "H:m", null);
//Here found a problem that we need to ensure that EndTime is greater than StartTime
//In one run, StartTime is 10:30 and EndTime is 2:32
//but the DateTime variables took is as 10:30 PM and 2:32 PM hence producing negative difference
TimeSpan ts = timeToInput.Subtract(timeFromInput)
int_TotalHours = ts.Hours * 60 + ts.Minutes;
if (int_TotalHours % _factor == 0) { /*I'm Perfect, no need to round*/ }
else if (int_TotalHours % _factor <= _roundDown) {
//Round down to nearest 15th, quarter
int_TotalHours = int_TotalHours - (int_TotalHours % _factor); }
else { //Round up to nearest quarter
int_TotalHours = int_TotalHours + (_factor - int_TotalHours % _factor); }
_TotalHours = Convert.ToDecimal(int_TotalHours / 60.00);
_TotalHours = (_TotalHours * 100) / 100;
return _TotalHours;
}
Thank you for your help.
I am trying to calculate the difference between two dates. This is what I'm currently using:
int currentyear = DateTime.Now.Year;
DateTime now = DateTime.Now;
DateTime then = new DateTime(currentyear, 12, 26);
TimeSpan diff = now - then;
int days = diff.Days;
label1.Text = days.ToString() + " Days Until Christmas";
All works fine except it is a day off. I am assuming this is because it does not count anything less than 24 hours a complete day. Is there a way to get it to do so? Thank you.
int days = (int)Math.Ceiling(diff.TotalDays);
The question is rather philosophic; if Christmas was tomorrow, would you consider it to be 1 day left, or 0 days left. If you put the day of tomorrow into your calculation, the answer will be 0.
Your problem goes away if you replace your:
DateTime.Now
with:
DateTime.Today
as your difference calculation will then be working in whole days.
I normally use the following code to get the output as intended by the unit in which the output is required:
DateTime[] dd = new DateTime[] { new DateTime(2014, 01, 10, 10, 15, 01),new DateTime(2014, 01, 10, 10, 10, 10) };
int x = Convert.ToInt32((dd[0] - dd[1]).TotalMinutes);
String unit = "days";
if (x / 60 == 0)
{
unit = "minutes";
}
else if (x / 60 / 24 == 0)
{
unit = "hours";
x = x / 60;
}
else
{
x = x / (60 * 24);
}
Console.WriteLine(x + " " + unit);