How do DateTime.ToBinary() and DateTime.ToFileTime() differ? - c#

Can anyone help explain the difference between DateTime.ToBinary() and DateTime.ToFileTime()? As far as I can tell they seem to always return the same value (when dealing with UTC times at least). The same applies to DateTime.FromBinary() and DateTime.FromFileTime().
I've tried using Reflector and I can see some differences, I just don't understand the relevance of the magic numbers:
public long ToBinary()
{
if (this.Kind != DateTimeKind.Local)
{
return (long) this.dateData;
}
TimeSpan utcOffset = TimeZoneInfo.Local.GetUtcOffset(this, TimeZoneInfoOptions.NoThrowOnInvalidTime);
long num2 = this.Ticks - utcOffset.Ticks;
if (num2 < 0L)
{
num2 = 0x4000000000000000L + num2;
}
return (num2 | -9223372036854775808L);
}
public long ToFileTime()
{
return this.ToUniversalTime().ToFileTimeUtc();
}
public long ToFileTimeUtc()
{
long num = ((this.InternalKind & 9223372036854775808L) != 0L) ? this.ToUniversalTime().InternalTicks : this.InternalTicks;
num -= 0x701ce1722770000L;
if (num < 0L)
{
throw new ArgumentOutOfRangeException(null, Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
}
return num;
}
public static DateTime FromFileTime(long fileTime)
{
return FromFileTimeUtc(fileTime).ToLocalTime();
}
public static DateTime FromFileTimeUtc(long fileTime)
{
if ((fileTime < 0L) || (fileTime > 0x24c85a5ed1c03fffL))
{
throw new ArgumentOutOfRangeException("fileTime", Environment.GetResourceString("ArgumentOutOfRange_FileTimeInvalid"));
}
return new DateTime(fileTime + 0x701ce1722770000L, DateTimeKind.Utc);
}
public static DateTime FromBinary(long dateData)
{
long num2;
if ((dateData & -9223372036854775808L) == 0L)
{
return FromBinaryRaw(dateData);
}
long ticks = dateData & 0x3fffffffffffffffL;
if (ticks > 0x3fffff36d5964000L)
{
ticks -= 0x4000000000000000L;
}
bool isAmbiguousLocalDst = false;
if (ticks < 0L)
{
num2 = TimeZoneInfo.Local.GetUtcOffset(MinValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
}
else if (ticks > 0x2bca2875f4373fffL)
{
num2 = TimeZoneInfo.Local.GetUtcOffset(MaxValue, TimeZoneInfoOptions.NoThrowOnInvalidTime).Ticks;
}
else
{
DateTime time = new DateTime(ticks, DateTimeKind.Utc);
bool isDaylightSavings = false;
num2 = TimeZoneInfo.GetUtcOffsetFromUtc(time, TimeZoneInfo.Local, out isDaylightSavings, out isAmbiguousLocalDst).Ticks;
}
ticks += num2;
if (ticks < 0L)
{
ticks += 0xc92a69c000L;
}
if ((ticks < 0L) || (ticks > 0x2bca2875f4373fffL))
{
throw new ArgumentException(Environment.GetResourceString("Argument_DateTimeBadBinaryData"), "dateData");
}
return new DateTime(ticks, DateTimeKind.Local, isAmbiguousLocalDst);
}

ToBinary() and ToFileTimeUtc() do not return the same value. ToBinary provide a round-trip value, an Int64 that can preserve the properties of a DateTime. It uses the same time base, January 1st of the year 0. The value is always UTC. Bit 62 is set for the extreme corner case where a local time near the 1/1/00 would be negative when converted to UTC (paying attention to detail here :)). Bit 63 is set when the Kind is UTC. Convert the magic number to hex to see this.
ToFileTimeUtc() uses the same time base as Windows' FILETIME, January 1st of the year 1601. The magic number is the number of ticks for 12am, 1/1/1601.

Related

tick() method in a digital clock - c#

For my assignment, we are supposed to create a digital clock. I've been stuck at the 3rd part of the question for a while.
Here's the question :
write a Clock class to represent a single clock. You can have hours, minutes and seconds as instance variables.You can add a method to print time, assuming it is a digital clock.
write test class ClockTester and try to create clocks to represent different countries, Print their time.
Add the below methods to make the clock working better.
tick() – it will represent one tick of the clock.
incrementSeconds() - It will increase the time by 1 second.
incrementMinutes() - It will increase the time by 1 minute.
incrementHours() - It will increase the time by 1 hour.
Here's the code I tried, It does print the time of the countries but the tick method does not increment the time. -
Clock class:
public class Clock
{
//instance variables
private int hours, minutes, seconds;
public Clock()
{
SetTime(0, 0, 0);
}
public Clock(int hours, int minutes, int seconds)
{
SetTime(hours, minutes, seconds);
}
public void SetTime(int hours, int minutes, int seconds)
{
if ((seconds >= 0) && (seconds < 60) && (minutes >= 0) && (minutes < 60)
&& (hours >= 0) && (hours < 24)) {
this.hours = hours;
this.minutes = minutes;
this.seconds = seconds;
}
else
{
this.hours = 0;
this.minutes = 0;
this.seconds = 0;
}
}
public int GetHours()
{
return hours;
}
public int GetMinutes()
{
return minutes;
}
public int GetSeconds()
{
return seconds;
}
//Tick()
public void Tick()
{
IncrementSeconds();
IncrementMinutes();
IncrementHours();
}
//incrementSeconds()
public void IncrementSeconds()
{
seconds++;
if (seconds > 59)
{
seconds = 0;
IncrementMinutes();
}
}
//incrementMinutes()
public void IncrementMinutes()
{
minutes++;
if (minutes > 59)
{
minutes = 0;
IncrementHours();
}
}
//incrementHours()
public void IncrementHours()
{
hours++;
if (hours > 23)
{
hours = 0;
}
}
}
clockTester class :
public class ClockTester
{
public static void Main(string[] args)
{
//print time in UK - London
Clock clockUK = new Clock();
clockUK.SetTime(18, 29, 48);
Console.WriteLine("London, UK : {0}:{1}:{2}", clockUK.GetHours(), clockUK.GetMinutes(), clockSL.GetSeconds());
//print time in US - New York
Clock clockUS = new Clock();
clockUS.SetTime(13, 29, 48);
Console.WriteLine("New York, US : {0}:{1}:{2}", clockUS.GetHours(), clockUS.GetMinutes(), clockUS.GetSeconds());
//print time in Japan - Tokyo
Clock clockJP = new Clock();
clockJP.SetTime(02, 29, 48);
Console.WriteLine("Tokyo, Japan : {0}:{1}:{2}", clockJP.GetHours(), clockJP.GetMinutes(), clockJP.GetSeconds());
}
}
You should have heard of the ToString method/function.
All objects have one in C# because all classes inherit/descend from Object class which defines a tostring method https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netframework-4.8 and you can overload the default with your own implementation.
https://learn.microsoft.com/en-us/dotnet/api/system.object.tostring?view=netframework-4.8#overloading-the-tostring-method
Your ToString function should return a formatted string, look at https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings and https://learn.microsoft.com/en-us/dotnet/standard/base-types/custom-numeric-format-strings
e.g.
public class MyTimeClass {
// fields/variables/properties and other methods not displayed, use imagination!
public string ToString(){
return String.Format("{0:00}:{1:00}:{2:00}.{3:000}",this.hours, this.minutes, this.seconds, this.ticks);
//ideally this would be culture dependant/sensitive
}
}
https://dotnetfiddle.net/uN2H2F

Calculate datetime difference in C#

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;
}
}

When a method returns a value from an if else statement what should be contained in the else statement?

Just a beginner here, I have a console app that calculates the charge payable for a car park that's working fine, at least until you put in a value that's a positive number.
We've just started using multiple methods and my problem is that the method I'm passing the 'hours' value to use an If else statement to get the charge value but as the method passes back a double I'm a little confused as to what would be best practice for the else.
Ideally I'd want to be able to enter an invalid value (a negative integer) for 'hours' and the program would return an error message and bounce back to the start of the program again.
To get that effect now I'm setting the return on the else to change the value passed back to 0 and then using an if statement in the main method to deal with the situation where 'hours' = 0. Then I'm using a goto to do it right now but I'm not sure that's best practice. If it is, great, but if there's a better way I'd prefer not to be relying on a something that's messier.
Cheers for any and all help.
class Program
{
static void Main(string[] args)
{
double charge = 0;
double hours = 0;
string reg;
start:
while (hours != -999)
{
Console.Write("\nEnter hours : ");
hours = Convert.ToDouble(Console.ReadLine());
charge = CalcCharge(hours);
if (charge == 0)
{
Console.Write("Invalid hour value. Please try again.\n");
goto start;
}
Console.Write("\nEnter reg : ");
reg = Console.ReadLine();
if (reg == "Sligo")
charge = charge - ((charge / 100) * 10);
if (charge > 100)
charge = 100;
Console.Write("\nThe charge is ${0:f2}.", charge);
Console.ReadLine();
}
}
static double CalcCharge(double hours)
{
double result;
if (hours > 0 && hours < 7)
{
result = hours * 2;
return result;
}
if (hours >= 7 && hours <= 10)
{
result = hours * 3;
return result;
}
if (hours >= 11 && hours <= 15)
{
result = hours * 4;
return result;
}
if (hours > 15)
{
result = hours * 3;
return result;
}
else
{
return 0;
}
}
}
You should probably not use an else but instead throw an exception. An ArgumentException is probably correct to use here. Catch the exception instead of checking the return value:
public static void Main(string[] args)
{
//your code
try
{
charge = CalcCharge(hours);
}
catch(ArgumentException)
{
Console.Write("Invalid hour value. Please try again.\n");
continue;
}
...
static double CalcCharge(double hours)
{
//Your code
throw new ArgumentException("hours");
}
Also, avoid using goto as it's bad practice and can lead to very messy, spaghetti gross code. If you look at the example I use a continue, which basically says "go back to the start of the loop".
I would probably change your function to this:
static double CalcCharge(double hours)
{
double result = 0;
if (hours > 0 && hours < 7)
{
result = hours * 2;
}
else if ((hours >= 7 && hours <= 10) || hours > 15)
{
result = hours * 3;
}
else if (hours >= 11 && hours <= 15)
{
result = hours * 4;
}
else
{
throw new ArgumentOutOfRangeException("there was a problem!");
}
return result;
}
This is a little more concise and it lets you catch the exception in the parent function if something goes wrong.

Return True When Time fall between a Time Range?

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));
}
}

DateTime Comparison Precision

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

Categories

Resources