What is the easiest way to subtract time in C#? - c#

I'm trying to put together a tool that will help me make work schedules. What is the easiest way to solve the following?
8:00am + 5 hours = 1:00pm
5:00pm - 2 hours = 3:00pm
5:30pm - :45 = 4:45
and so on.

These can all be done with DateTime.Add(TimeSpan) since it supports positive and negative timespans.
DateTime original = new DateTime(year, month, day, 8, 0, 0);
DateTime updated = original.Add(new TimeSpan(5,0,0));
DateTime original = new DateTime(year, month, day, 17, 0, 0);
DateTime updated = original.Add(new TimeSpan(-2,0,0));
DateTime original = new DateTime(year, month, day, 17, 30, 0);
DateTime updated = original.Add(new TimeSpan(0,-45,0));
Or you can also use the DateTime.Subtract(TimeSpan) method analogously.

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.
AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.
AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.
AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.
AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.
AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.
AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.
AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.
AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

This works too:
System.DateTime dTime = DateTime.Now();
// tSpan is 0 days, 1 hours, 30 minutes and 0 second.
System.TimeSpan tSpan = new System.TimeSpan(0, 1, 3, 0);
System.DateTime result = dTime + tSpan;
To subtract a year:
DateTime DateEnd = DateTime.Now;
DateTime DateStart = DateEnd - new TimeSpan(365, 0, 0, 0);

Hi if you are going to subtract only Integer value from DateTime then you have to write code like this
DateTime.Now.AddHours(-2)
Here I am subtracting 2 hours from the current date and time

Use the TimeSpan object to capture your initial time element and use the methods such as AddHours or AddMinutes. To substract 3 hours, you will do AddHours(-3). To substract 45 mins, you will do AddMinutes(-45)

try this
namespace dateandtime
{
class DatesTime
{
public static DateTime Substract(DateTime now, int hours,int minutes,int seconds)
{
TimeSpan T1 = new TimeSpan(hours, minutes, seconds);
return now.Subtract(T1);
}
static void Main(string[] args)
{
Console.WriteLine(Substract(DateTime.Now, 36, 0, 0).ToString());
}
}
}

TimeLeftToOpen= new TimeSpan(TimeLeftToOpen.Hours, TimeLeftToOpen.Minutes, TimeLeftToOpen.Seconds - 1);

Related

How can I convert the number of seconds since Jan 1st 1970 into a datetime value?

I have a number that is the number of seconds since January 1st 1970. It was created with this:
var utcNow = (int) Math.Truncate(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds);
Now need to convert that number to a date in string form like this:
Tue, Jan 15, 2019
Can someone give me some suggestions on how I can do this. I think I can format it myself but I need a suggestion on how to convert the integer utcNow into a datetime first.
static readonly DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
...
DateTime time = epoch.AddSeconds(utcNow);
You can also use this in reverse:
var seconds = (time - epoch).TotalSeconds;
(which gives a double, but you can cast it to int or long etc)
Some answer are already given, and work. But this is, I believe, the most elegant way of doing it. I'm using DateTimeOffset.FromUnixTimeSeconds(int64)
DateTimeOffset dt = DateTimeOffset.FromUnixTimeSeconds(utcNow);
And now you can convert it into a DateTime Struct with help of this blog entry
Substract the given time from current time and it gives timespan instance, from that you can get total seconds
var fromDate = new DateTime(1970,1 ,1);
var diffrance = DateTime.UtcNow.Subtract(fromDate);
Console.WriteLine(diffrance.TotalSeconds);

C# date format over 1 day

I'm trying to format a date from now, to few seconds, hours, maybe days, similar as Clash of Clans working timers Like this :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(80000);
return dateTime.ToString("H'h' mm'min'");
It works great actually, I get '22h 13min', only for minutes and hours. If I try to print days with it, like this :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(80000);
return dateTime.ToString("d'd' H'h' mm'min'");
I'll have '1d 22h 13min' returned. So for example if I try to convert 1 day to second (86400sec), this code will return 2 days, instead of 1 day.
How can I solve this problem properly without tricks like hard substract by 1 the day returned ?
EDIT1:
For example, expected result for one day is :
System.DateTime dateTime = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
dateTime = dateTime.AddSeconds(86400);
return dateTime.ToString("d'j' H'h' mm'min'");
return 2d 0h 00min, instead of 1d 0h 00min.
For DateTime, day is the day of the month. What you want is a TimeSpan.
var span = TimeSpan.FromSeconds(80000);
Console.WriteLine(span.ToString(#"d'd 'h'h 'm'min'"));
outputs
0d 22h 13min
Your code dateTime = dateTime.AddSeconds(80000); will assign the value 1/1/1970 10:13:20 to the dateTime variable, hence you are getting the output as 1d 22h 13min by dateTime.ToString("d'd' H'h' mm'min'");. So if you want to get the next day you can use dateTime = dateTime.AddDays(1); or add it as seconds as you did. ie., dateTime = dateTime.AddSeconds(86400);
The "d" format specifier returns the day number of month. Since you add 1 day to 1st January, it will be 2nd January and that's why this specifier returns 2.
If I understand clearly, you might wanna use TimeSpan instead.
TimeSpan ts = TimeSpan.FromSeconds(86400);
ts.ToString("d'd 'h'h 'mm'min'"); // 1d 0h 00min
or
TimeSpan ts = TimeSpan.FromSeconds(80000);
ts.ToString("d'd 'h'h 'mm'min'"); // 0d 22h 13min
Then you can format this value.
Or you can use DateTime.AddDays method to subctact 1 day like
dateTime = dateTime.AddDays(-1);
for your dateTime if you really wanna use DateTime.

Converting TimeSpan Hours to DateTime

Commented Code As Posted by Arif Eqbal the below Converts a TimeSpan to a DateTime
A problem with the above is that the conversion returns the incorrect number of days as specified in the TimeSpan. Using the above, the below returns 3 and not 2 as specified. The minutes and seconds are preserved. ~~ Ideas on how to preserve the 2 days in the TimeSpan arguments and return them as the DateTime day?
A second problem of this conversion is that if I want to add the hours in days to the hours in the TimeSpan and return them as DateTime hours, e.g. Format = "hh:mm" or 49:30, there is no way to add the hours together in a DateTime object. Essentially I want to convert TimeSpan.TotalHours to the Hours component of the DateTime object. I understand this likely requires a string conversion, but there doesn't seem to be an elegant solution in .Net 3.5. Unfortunately I do not have the luxury of the converters from 4.0 or 4.5.
public void test()
{
// Arif Eqbal
//DateTime dt = new DateTime(2012, 01, 01);
//TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);
//dt = dt + ts;
_ts = new TimeSpan(2, 1, 30, 10);`
var format = "dd";
var returnedVal = _ts.ToString(format);
Assert.That(returnedVal, Is.EqualTo("2")); //returns 3 not 2
}
Thanks - Glenn
It returns "02" when I try it.
The "dd" format makes it put leading zeroes if necessary, but you have failed to account for this in your Is.EqualTo("2")
Therefore your assertion fails (but you mistakenly thought that it was returning 3).
I tested this by copy/pasting your code into a Console app:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
var returnedVal = _ts.ToString(format);
Console.WriteLine(returnedVal); // Prints "02"
[EDIT] Aha! Now I know what you've done. Your code is actually like this:
var _ts = new TimeSpan(2, 1, 30, 10);
var format = "dd";
DateTime formatDateTime = new DateTime(2012, 01, 01);
var conversionResult = formatDateTime + _ts;
string result = conversionResult.ToString(format);
But note what the type of conversionResult is DateTime, not TimeSpan.
So you're doing here is using the format "dd" with a DateTime object, and "dd" for a DateTime means "The day of the month".
So you took the date 2012-01-01 and added 2 days (and a bit) to it to make it 2012-01-03, and then you made a string out of the day of the month part, which of course is 3.
Problem explained!

How many days belong to a certain range of dates?

Let's say I have a start DateTime object containing 2012/09/21 23:59:59 and an end DateTime object containing 2012/09/22 00:01:02. The difference between these two objects is little more than a minute, but the number of days belonging to this range of dates is equal to 2.
I have read other similar questions, and I think that TimeSpan and DateTime classes do not provide methods to perform this type of calculation. How to calculate the number of days belonging to a certain range of dates?
Use:
DateTime dateTime1 = DateTime.Parse("2012/09/21 23:59:59");
DateTime dateTime2 = DateTime.Parse("2012/09/22 00:01:02");
TimeSpan difference = dateTime1 - dateTime2;
The variable difference contains the time between the two dates. For example use the TotalDays property to get the difference in days.
If you want to exclude the time portion, use the Date property on DateTime, for example:
TimeSpan difference = dateTime1.Date - dateTime2.Date;
TotalDays will be 1 in this case rather than 0.
You can do the following:
System.DateTime dtTodayNoon = new System.DateTime(2006, 9, 13, 12, 0, 0);
System.DateTime dtTodayMidnight = new System.DateTime(2006, 9, 13, 0, 0, 0);
System.TimeSpan diffResult = dtTodayNoon.Subtract(dtYestMidnight);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.Days);
Console.WriteLine("Yesterday Midnight - Today Noon = " + diffResult.TotalDays);
Console.ReadLine();
If you want to include the daylight savings:
System.TimeSpan diffResult = dtTodayNoon.ToUniversalTime().Subtract(dtYestMidnight.ToUniversalTime());
You could use DateTimeOffSet too if timezones are important
Doesn't
(dateTime2 - dateTime1).TotalDays
work for you?
I have read other similar questions, and I think that TimeSpan and
DateTime classes do not provide methods to perform this type of
calculation.
Of course that they do.
TimeSpan is the class to use. I guess you are looking for the TotalDays property, aren't you?
DateTime date1 = ...;
DateTime date2 = ...;
TimeSpan difference = date2 - date1;
int totalNumberOfDays = difference.TotalDays;

How can I convert CFAbsoluteTime to DateTime in C#?

Can anyone tell me how can I convert a value which I know to be CFAbsoluteTime from MacOS into DateTime value in C#?
A CFAbsoluteTime is a double, the number of seconds since January 1st, 2001, 12am. Thus:
public static DateTime CFAbsoluteTimeToDateTime(double abs) {
long ticks = (long)(abs * 1E7); // 1 tick == 100 nsec
return new DateTime(new DateTime(2001, 1, 1).Ticks + ticks);
}
It turned out, that I can convert it using following code:
TimeSpan span = TimeSpan.FromSeconds(CFAbsoluteTimeFloatValue);
var cshartpDateTime = new DateTime(2001, 1, 1).Add(span);

Categories