Hi I was solving a problem to calculate some library fine based on difference in return date and due date in C#. Now there are some constraints to the problem like
if the return year is changed i.e. if the return year is greater than the due date calendar year then fine is 10000. e.g. due date "31/12/2015" and return date "01/01/2016" then also fine is 10000.
if the return month is changed then fine is 500 * number of months late.
if the return day is changed then fine is 15 * number of days late.
else fine is 0.
Now i wrote the function below:
static int CalcFine (int[] returnedOn, int[] dueOn) {
int returnD = returnedOn[0];
int returnM = returnedOn[1];
int returnY = returnedOn[2];
int dueD = dueOn[0];
int dueM = dueOn[1];
int dueY = dueOn[2];
if (returnY > dueY) {
return 10000;
} else if (returnY < dueY) {
return 0;
} else {
if (returnM > dueM) {
return (returnM - dueM) * 500;
} else if (returnM < dueM) {
return 0;
} else {
if (returnD > dueD) {
return (returnD - dueD) * 15;
} else {
return 0;
}
}
}
}
I read about the DateTime class in C# that has pretty neat functions that return the difference in two dates as total days, total minutes, etc. But given the constraint of Fine being different based on year, month and days, I am not sure if there is any other inbuilt function to solve the above problem. In short I am trying to find if there is another simple way to solve the above problem without using so many if-else's.
You can get the difference in days, hours or minutes.
DateTime fromdate = new DateTime(2012,1,1);
DateTime todate = DateTime.Now;
TimeSpan diff = todate - fromdate;
int differenceInDays = diff.Days;
If you want to try differently for your validations and business rules. Follow the below code
public double GetFineAmount(DateTime DueDate)
{
DateTime dt = DateTime.Now;
int yeardiff, monthdiff, daydiff;
yeardiff = dt.Year - DueDate.Year;
if (yeardiff > 0) return 10000;
monthdiff = dt.Month - DueDate.Month;
if (monthdiff > 0) return 500 * monthdiff;
daydiff = dt.Day - DueDate.Day;
if (daydiff > 0) return 15 * daydiff;
return 0;
}
Editted again.. changed string pattern. I guess I need some sleep...
static int CalcFine (string returnedOn, string dueOn)
{
DateTime returnedDate = DateTime.ParseExact(
returnedOn, "d M yyyy", CultureInfo.InvariantCulture);
DateTime dueDate = DateTime.ParseExact(
dueOn, "d M yyyy", CultureInfo.InvariantCulture);
if (returnedDate < dueDate)
return 0;
if (returnedDate.Year > dueDate.Year)
return 10000;
if (returnedDate.Month > dueDate.Month)
return 500 * (returnedDate.Month - dueDate.Month);
if (returnedDate.Day > dueDate.Day)
return 15 * (returnedDate.Day - dueDate.Day);
else
return 0;
}
DateTime is a powerful tool. But you don't want to over-complicate this.
If you just find the difference between the two dates in days, the equation becomes a lot easier to manage versus trying to subtract dates.
static int CalcFine(DateTime returnedOn, DateTime dueOn)
{
TimeSpan dateDiff = (returnedOn - dueOn);
int TotalDays = dateDiff.Days;
if (TotalDays >= 365)
{
return 10000;
}
else if(TotalDays < 365 && TotalDays > 30 && TotalDays % 30 > 1)
{
return (500 * (TotalDays % 30));
}
else if(TotalDays < 30 && TotalDays > 0)
{
return 15 * TotalDays;
}
else
{
return 0;
}
}
Related
I have to add 15 minutes to the current time and set it to a DateTime object in C#. If my current time is say 11:50 PM, and 15 minutes is added, the hour part becomes 24 and is causing the following error: "Hour, Minute, and Second parameters describe an un-representable DateTime."
public static DateTime NewTime(this DateTime dateTime)
{
int hour = dateTime.Hour;
int minute = dateTime.Minute;
if (minute > 0)
{
minute = dateTime.Minute + (15);
if (minute >= 60)
{
hour = hour + 1;
minute = 0;
}
}
return new DateTime(dateTime.Year, dateTime.Month,
dateTime.Day, hour, minute, 0);
}
Thanks
Your logic does not make sense, you are only adding minutes if the minutes are greater than 0 so what happens if they are 0?
To add time use the methods built into the type definition, no need to reinvent the wheel. Example:
public static DateTime Add15Minutes(this DateTime dateTime)
{
return dateTime.AddMinutes(15);
}
You are checking for an overflow on the minute attribute, but not the hour attribute. You could check for an overflow on the hour attribute like this:
public static DateTime NewTime(this DateTime dateTime)
{
int hour = dateTime.Hour;
int minute = dateTime.Minute;
var day = dateTime.Day;
if (minute > 0)
{
minute = dateTime.Minute + (15);
if (minute >= 60)
{
hour = hour + 1;
minute = 0;
}
}
if (hour > 24) {
day += 1;
}
return new DateTime(dateTime.Year, dateTime.Month,
day, hour, minute, 0);
}
However, you will also run into problems with the overflow of days in a month, which is even more complicated to handle. Instead, just use the built in Add function:
public static DateTime NewTime(this DateTime dateTime)
{
return new dateTime.AddMinutes(15);
}
I think you are overthinking this maybe? DateTime already provides many support methods and this will probably do what you need without the need to create an extension method:
var myValue = new DateTime(2017,3,14,23,50,0);
var result = myValue.AddMinutes(15);
Suppose night time is set from 20.30h till 6.15h(AM). These 2 parameters are user-scoped variables.
Suppose you have an arrival date and a departure date which can span from a few minutes to more than one total day.
How do you calculate the total hours of night time?
public static double CalculateTotalNightTimeHours(DateTime arrival,
DateTime departure,
int nightTimeStartHour,
int nightTimeStartMinute,
int nightTimeEndHour,
int nightTimeEndMinute)
{
//??
}
EDIT: I understand this may be no straight forward yes/no answer, but maybe someone has an elegant solution for this problem.
To answer the comments : I indeed want to calculate the total number of hours (or minutes) that fall between a user-editable night start and end time. I'm calculating visit time, and the first date is indeed the arrival parameter.
The code I had sofar :
DateTime nightStart = new DateTime( departure.Year, departure.Month, departure.Day,
nightTimeStartHour, nightTimeStartMinute, 0);
DateTime nightEnd = new DateTime( arrival.Year, arrival.Month, arrival.Day,
nightTimeEndHour, nightTimeEndMinute, 0);
if (arrival < nightEnd)
{
decimal totalHoursNight = (decimal)nightEnd.Subtract(arrival).TotalHours;
}
//...
Just because I was up for the challenge you should be able to use the following function with success. Please note that this is probably not the most efficient way to do it, but I did it this way so I could lay out the logic. I may decide to edit this as some point to improve it, but it should work fine as is.
It is also important to note a couple of assumptions here:
the 'end' parameter is always greater than the 'start' parameter (although we check that first thing anyway)
the night end parameters are earlier than the night start parameters (i.e. night time ends on the following day, but never as much as 24 hours later)
Daylight savings time does not exist! (this is a tricky concern, one important question to address is: if either your start or end time is at 01:30 on the day the clocks go back, how will you know if the time was recorded before or after the rollback? i.e is it the first or second time the clock has hit 01:30?)
with that in mind...
public static double Calc(DateTime start, DateTime end, int startHour, int startMin, int endHour, int endMin)
{
if (start > end)
throw new Exception();//or whatever you want to do
//create timespans for night hours
TimeSpan nightStart = new TimeSpan(startHour, startMin, 0);
TimeSpan nightEnd = new TimeSpan(endHour, endMin, 0);
//check to see if any overlapping actually happens
if (start.Date == end.Date && start.TimeOfDay >= nightEnd && end.TimeOfDay <= nightStart)
{
//no overlapping occurs so return 0
return 0;
}
//check if same day as will process this differently
if (start.Date == end.Date)
{
if (start.TimeOfDay > nightStart || end.TimeOfDay < nightEnd)
{
return (end - start).TotalHours;
}
double total = 0;
if (start.TimeOfDay < nightEnd)
{
total += (nightEnd - start.TimeOfDay).TotalHours;
}
if(end.TimeOfDay > nightStart)
{
total += (end.TimeOfDay - nightStart).TotalHours;
}
return total;
}
else//spans multiple days
{
double total = 0;
//add up first day
if (start.TimeOfDay < nightEnd)
{
total += (nightEnd - start.TimeOfDay).TotalHours;
}
if (start.TimeOfDay < nightStart)
{
total += ((new TimeSpan(24, 0, 0)) - nightStart).TotalHours;
}
else
{
total += ((new TimeSpan(24, 0, 0)) - start.TimeOfDay).TotalHours;
}
//add up the last day
if (end.TimeOfDay > nightStart)
{
total += (end.TimeOfDay - nightStart).TotalHours;
}
if (end.TimeOfDay > nightEnd)
{
total += nightEnd.TotalHours;
}
else
{
total += end.TimeOfDay.TotalHours;
}
//add up any full days
int numberOfFullDays = (end - start).Days;
if (end.TimeOfDay > start.TimeOfDay)
{
numberOfFullDays--;
}
if (numberOfFullDays > 0)
{
double hoursInFullDay = ((new TimeSpan(24, 0, 0)) - nightStart).TotalHours + nightEnd.TotalHours;
total += hoursInFullDay * numberOfFullDays;
}
return total;
}
}
You can then call it something like this:
double result = Calc(startDateTime, endDateTime, 20, 30, 6, 15);
Basically you'll want to calculate when night starts and ends. Then compare those to the arrival and departure dates to see if you arrival after night starts or depart before it ends to get the values you need to subtract to determine the total night hours. Then you need to continue to calculate this for each day until the start time for night is pass the departure date. Here's my solution for that.
public static double CalculateTotalNightTimeHours(
DateTime arrival,
DateTime departure,
int nightTimeStartHour,
int nightTimeStartMinute,
int nightTimeEndHour,
int nightTimeEndMinute)
{
if (arrival >= departure)
return 0;
var nightStart = arrival.Date.AddHours(nightTimeStartHour).AddMinutes(nightTimeStartMinute);
var nightEnd = nightStart.Date.AddDays(1).AddHours(nightTimeEndHour).AddMinutes(nightTimeEndMinute);
double nightHours = 0;
while (departure > nightStart)
{
if (nightStart < arrival)
nightStart = arrival;
if (departure < nightEnd)
nightEnd = departure;
nightHours += (nightEnd - nightStart).TotalHours;
nightStart = nightStart.Date.AddDays(1).AddHours(nightTimeStartHour).AddMinutes(nightTimeStartMinute);
nightEnd = nightStart.Date.AddDays(1).AddHours(nightTimeEndHour).AddMinutes(nightTimeEndMinute);
}
return nightHours;
}
You'd probably also want to add checking to make sure the start and end hours are within range. This also assumes that night starts on one day and ends on the next, so if you wanted night to end before midnight you'd have to do something else.
Interesting issue I'm facing and I just can't come up with an algorim to calculate.
Basically, what I want is to calculate a DateTime based on DateTime.Now.AddMinutes() but the Adding of minutes should take into consideration Working Hours and weekends.
In other words, if the time is currently 16:50 and i add 20 minutes, the method should return a DateTime for tomorrow morning at 08:10 (if tomorrow is not a weekend day).
I've started with some logic, but it's not complete. Does anyone have a sample which can save me a few hours of coding? This is what i've got so far:
public DateTime CalculateSLAFromNow(int minutes)
{
DateTime now = DateTime.Now;
TimeSpan slatimeaddedon = CalculateToNextWeekDay(DateTime.Now);
TimeSpan finalMinutesAddedon = slatimeaddedon.Add(new TimeSpan(0, minutes, 0));
DateTime SLATime = DateTime.Now.AddMinutes(slatimeaddedon.TotalMinutes);
return SLATime;
}
private TimeSpan CalculateToNextWeekDay(DateTime dt)
{
//Calculate.
}
public static DateTime CalculateSLAFromNow(int minutes)
{
double days = (double)minutes / 540;
DateTime now = DateTime.Now;
DateTime later = now;
while (days >= 1)
{
later = later.AddDays(1);
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
days--;
}
days = days * 540;
later = later.AddMinutes(days);
if (later.Hour > 17)
{
later = later.AddHours(15);
}
if (later.DayOfWeek == DayOfWeek.Saturday)
{
later = later.AddDays(2);
}
else if(later.DayOfWeek == DayOfWeek.Sunday)
{
later = later.AddDays(1);
}
return later;
}
There now it accounts for any number of minutes added (not the prettiest code, but it works)
Ok. Friend of mine wrote the following which works 100%. Thanks J for this. Herewith the complete solution:
private static DateTime DoCalculation(DateTime startDate, int minutes)
{
if (startDate.DayOfWeek == DayOfWeek.Sunday)
{
// if the input date is a sunday, set the actual SLA start date to the following monday morning 7:00AM
startDate = startDate.AddHours(24);
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 7, 0, 0);
}
else if (startDate.DayOfWeek == DayOfWeek.Saturday)
{
// if the input date is a saturday, set the actual SLA start date to the following monday morning 7:00AM
startDate = startDate.AddHours(48);
startDate = new DateTime(startDate.Year, startDate.Month, startDate.Day, 7, 0, 0);
}
DateTime resultDate = startDate;
for (int i = 0; i < minutes; i++)
{
resultDate = resultDate.AddMinutes(1);
// it is 5PM and time to go home
if (resultDate.Hour >= 17)
{
// if tomorrow is saturday
if (resultDate.AddDays(1).DayOfWeek == DayOfWeek.Saturday)
{
//add 48 hours to get us through the whole weekend
resultDate = resultDate.AddHours(48);
}
// add 14 hours to get us to next morning
resultDate = resultDate.AddHours(14);
}
}
return resultDate;
}
I am making a function to check time fall between a time range in 24hr format, However there is some thing wrong with my code , can any one point out how to fix ?
My code:
bool isDoTime(int starthour, int startminute, int endhour, int endminute)
{
TimeSpan start = new TimeSpan(starthour, startminute, 0);
TimeSpan end = new TimeSpan(endhour, endminute, 0);
TimeSpan add24h = new TimeSpan(24, 0, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
if (starthour > endhour || (endhour == starthour && endminute <= startminute))
{
end += add24h;
}
if ((now > start) && (now < end))
{
return true;
}
return false;
}
Problem: i want to return true when current time between 20:30 - 3:30 , however when i run my code as below. the condition is return true only from 8:30 to 00:00 , not true from 00:00 - 3:30
if (isDoTime(20,30,3,30) //return true from 20:30 - 3:30
{
//dosomething
}
Split up in one check if it spans across midninght, and one for same day.
TimeSpan start = new TimeSpan(starthour, startminute, 0);
TimeSpan end = new TimeSpan(endhour, endminute, 0);
TimeSpan now = DateTime.Now.TimeOfDay;
//The readable version:
if(start>end){
//Must check if after start (before midnight) or before end (after midnight)
if((now > start) || (now < end)){
return true;
{
}
else
{
//Simple check - span is within same day
if ((now > start) && (now < end))
{
return true;
}
}
return false;
The short/cryptic version:
return start > end ? (now > start) || (now < end) : (now > start) && (now < end);
You want to use DateTime structures rather than integers. You can also generalise it to arbitary DateTimes. If secondTime is less than firstTime, it adds 1 day to secondTime.
public bool IsBetween(this DateTime thisTime, DateTime firstTime, DateTime secondTime) {
if (secondTime < firstTime)
secondTime = secondTime.AddDays(1);
return firstTime < thisTime && thisTime < secondTime);
}
// to use...
bool isDoTime = DateTime.Now.IsBetween(firstTime, secondTime);
I think you'd be better off using DateTime however, you will still need to check that if the start time is greater than the end time and add 24 hours in that case.
Your method would start:
bool isDoTime(int starthour, int startminute, int endhour, int endminute)
{
DateTime start = new DateTime(0, 0, 0, starthour, startminute, 0);
DateTime end = new DateTime(0, 0, 0, endhour, endminute, 0);
if (start > end)
{
end.AddDays(1);
}
DateTime now = DateTime.Now;
return start < now && now < end;
}
Though you might want <= tests depending on your logic
(Unless it's your logic of where you're adding 24 hours of course - does that code execute?)
It will be much easier to make to use DateTime's as parameters here, and avoid the whole problem of manually checking:
bool isDoTime(DateTime starttime, DateTime endtime)
{
if (DateTime.Now > starttime && DateTime.Now < endtime)
{
return true;
}
return false;
}
[TestFixture]
public class Class1
{
private DateTime _now;
[SetUp]
public void SetUp()
{
_now = DateTime.MinValue.AddDays(1).AddHours(2); //02.01.0001 02:00:00
}
[Test]
public void TestCase()
{
Assert.IsTrue(IsDoTime(20, 30, 3, 30));
}
bool IsDoTime(int starthour, int startminute, int endhour, int endminute)
{
var start1 = DateTime.MinValue.AddHours(starthour).AddMinutes(startminute); //01.01.0001 20:30:00
var end1 = endhour < starthour
? DateTime.MinValue.AddDays(1).AddHours(endhour).AddMinutes(endminute) //02.01.0001 03:30:00
: DateTime.MinValue.AddHours(endhour).AddMinutes(endminute);
return ((_now > start1) && (_now < end1));
}
}
I'm doing DateTime comparison but I don't want to do comparison at second, millisecond and ticks level. What's the most elegant way?
If I simply compare the DateTime, then they are seldom equal due to ticks differences.
What about using a timespan.
if (Math.Truncate((A - B).TotalMinutes) == 0)
{
//There is less than one minute between them
}
Probably not the most elegant way, but it allows for cases which are one second apart and yet have different days/hours/minutes parts such as going over midnight.
Edit: it occured to me that the truncate is unecessary...
if (Math.Abs((A - B).TotalMinutes) < 1)
{
//There is less than one minute between them
}
Personally I think this is more elegant...
One approach could be to create two new DateTimes from your values you want to compare, but ignore anything from the seconds on down and then compare those:
DateTime compare1 = new DateTime(year1, month1, day1, hour1, minute1, 0);
DateTime compare2 = new DateTime(year2, month2, day2, hour2, minute2, 0);
int result = DateTime.Compare(compare1, compare2);
I'd be the first to admit it's not elegant, but it solves the problem.
Using a TimeSpan you get all the granularity you want :
DateTime dt1, dt2;
double d = (dt2 - dt1).TotalDays;
double h = (dt2 - dt1).TotalHours;
double m = (dt2 - dt1).TotalMinutes;
double s = (dt2 - dt1).TotalSeconds;
double ms = (dt2 - dt1).TotalMilliseconds;
double ticks = (dt2 - dt1).Ticks;
public class DateTimeComparer : Comparer<DateTime>
{
private Prescision _Prescision;
public enum Prescision : sbyte
{
Millisecons,
Seconds,
Minutes,
Hour,
Day,
Month,
Year,
Ticks
}
Func<DateTime, DateTime>[] actions = new Func<DateTime, DateTime>[]
{
(x) => { return x.AddMilliseconds(-x.Millisecond);},
(x) => { return x.AddSeconds(-x.Second);},
(x) => { return x.AddMinutes(-x.Minute);},
(x) => { return x.AddHours(-x.Hour);},
(x) => { return x.AddDays(-x.Day);},
(x) => { return x.AddMonths(-x.Month);},
};
public DateTimeComparer(Prescision prescision = Prescision.Ticks)
{
_Prescision = prescision;
}
public override int Compare(DateTime x, DateTime y)
{
if (_Prescision == Prescision.Ticks)
{
return x.CompareTo(y);
}
for (sbyte i = (sbyte)(_Prescision - 1); i >= 0; i--)
{
x = actions[i](x);
y = actions[i](y);
}
return x.CompareTo(y);
}
}
Usage example:
new DateTimeComparer(DateTimeComparer.Prescision.Day).Compare(Date1, Date2)
How about this ComparerClass?
public class DateTimeComparer : Comparer<DateTime>
{
private string _Format;
public DateTimeComparer(string format)
{
_Format = format;
}
public override int Compare(DateTime x, DateTime y)
{
if(x.ToString(_Format) == y.ToString(_Format))
return 0;
return x.CompareTo(y);
}
}
This can be used by
List.Sort(new DateTimeComparer("hh:mm"));
You can convert them to String format and compare the string with each other.
This also gives freedom to choose your comparison parameters, like only the time without the date, etc.
if (String.Format("{0:ddMMyyyyHHmmss}", date1) == String.Format("{0:ddMMyyyyHHmmss}", date2))
{
// success
}
I've written this to help myself:
internal class ImpreciseCompareDate : IComparer<DateTime>
{
private readonly double _Tolerance;
public ImpreciseCompareDate(double MillisecondsTolerance)
{
_Tolerance = MillisecondsTolerance;
}
public int Compare(DateTime x, DateTime y)
{
return Math.Abs((x - y).TotalMilliseconds) < _Tolerance ? 0 : x.CompareTo(y);
}
}
Tolerance can be set to (10d/3d) to account for SQL servers 1/300th of a ms. If tolerance is exceeded, delegate to default comparer.
Another way is to convert first by processing on ticks level with a simple (non-rounding) calculation:
var now = DateTime.UtcNow;
// 636340541021531973, 2017-06-26T06:08:22.1531973Z
var millisecondsPrecision = new DateTime(now.Ticks / 10000 * 10000, now.Kind);
// 636340541021530000, 2017-06-26T06:08:22.1530000Z
var secondsPrecision = new DateTime(now.Ticks / 10000000 * 10000000, now.Kind);
// 636340541020000000, 2017-06-26T06:08:22.0000000Z
var minutePrecision = new DateTime(now.Ticks / (10000000*60) * (10000000*60), now.Kind);
// 636340541000000000, 2017-06-26T06:08:00.0000000Z
#ALZ's solution looks nice but it's too complicated and has a bug.
So I decided to combine it with #ChrisF's solution.
public class DateTimeComparer : Comparer<DateTime>
{
public enum Precision
{
Years = 0,
Months,
Days,
Hours,
Minutes,
Seconds,
Millisecons,
Ticks
}
private Precision _precision;
public DateTimeComparer(Precision precision = Precision.Ticks)
{
_precision = precision;
}
public override int Compare(DateTime x, DateTime y)
{
if (_precision == Precision.Ticks)
{
return x.CompareTo(y);
}
var xx = AssembleValue(x, _precision);
var yy = AssembleValue(y, _precision);
return xx.CompareTo(yy);
}
private static DateTime AssembleValue(DateTime input, Precision precision)
{
var p = (int)precision;
var i = 1;
return new DateTime(input.Year,
p >= i++ ? input.Month : 1,
p >= i++ ? input.Day : 1,
p >= i++ ? input.Hour : 0,
p >= i++ ? input.Minute : 0,
p >= i++ ? input.Second : 0,
p >= i++ ? input.Millisecond : 0);
}
}
Very simple solution from my own code:
TimeSpan timeDifference = presentLastSavedDate.Subtract(previousLastSavedDate);
if (timeDifference.Seconds > 0)
{
return Content(HttpStatusCode.Conflict, ALREADY_CHANGED_MSG);
}
I have create a very fast compare functions to compare DateTime with different Precission. All are arithmetical calculations and no new object are created.
public enum DateTimeComparePrecision : long
{
Millisecond = TimeSpan.TicksPerMillisecond,
Second = TimeSpan.TicksPerSecond,
Minute = TimeSpan.TicksPerMinute,
Hour = TimeSpan.TicksPerHour,
Day = TimeSpan.TicksPerDay,
}
public static bool DatesAreEqual(DateTime d1, DateTime d2, DateTimeComparePrecision Precision)
{
return (d1.Ticks - (d1.Ticks % (long)Precision)) == (d2.Ticks - (d2.Ticks % (long)Precision));
}
public static int DatesCompare(DateTime d1, DateTime d2, DateTimeComparePrecision Precision)
{
long Day1 = (d1.Ticks - (d1.Ticks % (long)Precision));
long Day2 = (d2.Ticks - (d2.Ticks % (long)Precision));
if (Day2 > Day1)
return 1;
if (Day2 < Day1)
return -1;
return 0;
}
How Ticks Transformed for the compare
DateTime NowIs = DateTime.UtcNow;
Console.WriteLine($"{NowIs:dd MM yyyy HH:mm:ss.fffffff}");
DateTime d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerMillisecond)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerSecond)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerMinute)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerHour)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
d1 = new DateTime((NowIs.Ticks - (NowIs.Ticks % TimeSpan.TicksPerDay)));
Console.WriteLine($"{d1:dd MM yyyy HH:mm:ss.fffffff}");
output
01 03 2022 12:51:26.7237323
01 03 2022 12:51:26.7230000
01 03 2022 12:51:26.0000000
01 03 2022 12:51:00.0000000
01 03 2022 12:00:00.0000000
01 03 2022 00:00:00.0000000