How do I subtract one DateTime from another? - c#

I have an instance of DateTime that I get from my database, I want to subtract it from DateTime.Now and find out if 4 hours were passed. How do I do that?
Also when should i use DateTime.UTCNow or DateTimeOffset

You can use the subtraction operator to get a TimeSpan:
private static readonly TimeSpan MinimumTime = TimeSpan.FromHours(4);
...
if ((dateFromDatabase - DateTime.Now) > MinimumTime)
{
...
}
As for whether you need UTCNow or Now... it will depend on what happens to time zones when you fetch the data from the database. DateTime is not terribly clear on this front :(
If you can fetch the value as a DateTimeOffset to start with, then you can use DateTimeOffset.Now instead and it should be simpler to work out any time zone issues.

DateTime.Subtract
First Google hit..

Try this:
bool fourHoursPassed = date.AddHours(4) < DateTime.Now;
or this to actually perform a subtraction:
bool fourHoursPassed = (DateTime.Now - date).TotalHours > 4;

DateTime.Subtract
or
DateTime myDateTime = someValue;
TimeSpan ts = DateTime.Now -myDateTime;
if(ts.Hours>=4)
{
doSomething();
}
Hope it helps.

DateTime dt = new DateTime(2011, 07, 10);
DateTime dob = new DateTime(1987, 07, 10);
You can simply subtract as:
TimeSpan age = dt - dob;

Related

offset datetime with each other - Must tell the number of days in total

I must have built up such that I have a datetime which gets added antale day as it should go forward. and then I have time as it should set off in relation to 04/10/16 to 10/09/16
I do not care about the time which is in datetime. It should not I use for anything. What I need out of this is exactly how many days there are from that time.
Datetime dateString = "4/10/2016 8:30:52" //I pretend that it comes from the database, it was more in terms of see what come there.
DateTime dt = DateTime.Now.AddDays(5);
What I need out of this is that it tell me how many days there are in between the two datetime as I entered.
You can substract DateTime objects to obtain a TimeSpan:
Datetime dateString = DateTime.Parse("4/10/2016 8:30:52");
DateTime dt = DateTime.Now;
TimeSpan duration = dt-dateString;
From the TimeSpan object, you can get how many (full) days with :
int totalCompleteDays = (int)duration.TotalDays;
Or if you want a rounded results :
int roundedTotalDays = (int)Math.Round(duration.TotalDays);
DateTime objects support basic operators and will return TimeSpan objects.
DateTime DateTimeB = DateTime.Now.AddDays(5);
DateTime DateTimeA = DateTime.Now;
TimeSpan difference = DateTimeA - DateTimeB;
...
you can then use the TotalDays property of the timeSpan.
...
Console.out.WriteLine(difference.TotalDays);

How to get a DateTime from total amount of seconds?

Let's say I have
int seconds = 43200;
(amount of seconds from the beginning of the current day, 00:00:00) and I want to get related DateTime representation ("12:00:00"). Is there any c# utility function?
You need the TimeSpan, then you can get the DateTime in this way:
TimeSpan timeOfDay = TimeSpan.FromSeconds( seconds );
DateTime dt = DateTime.Today.Add( timeOfDay );
It is not a DateTime representation, it looks like a TimeSpan representation to me instead.
For this, you can use TimeSpan.FromSeconds method like;
int seconds = 43200;
var ts = TimeSpan.FromSeconds(seconds);
If you really need to add this to generate current day midday, you can use DateTime.Today property and add this to that.
DateTime dt = DateTime.Today.Add(ts);
You can calculate it directly:
int seconds = 43200;
DateTime dateTime = DateTime.Today.AddSeconds(seconds);

How do i assign back the DateTime.Now from a string?

The code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime.Now = time;
}
time now for example show the saved datetime.now could be minute ago or an hour ao.
the datetime.now is saved after my program is finished to make an operation.
dt = the current datetime now i use this method in the constructor.
What i want to do is to calculate the time that have been passed between the last saved datetime.now(time) and the current datetime.now(dt).
If the time that have been passed is 20 minutes or more enable true a button.
You cannot set DateTime.Now You need to create an instance of the DateTime object.
Then to get the difference you can say
TimeSpan diff = DateTime.Now - MyDateTime;
This has a property called TotalMinutes that you can use for your check.
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
You can try this code
DateTime date;
if (DateTime.TryParse(time, out date))
{
TimeSpan diff = date - dt;
if (diff.TotalMinutes >= 20)
{
//Do sommething
}
}
Every time you run this method you need to persist the value somewhere. I'm going to call that variable _lastTime. That's going to be a DateTime. Further, you'll need a variable for the actual elapsed time between those two, we'll call that _elapsedTime. That's going to be a TimeSpan. With that in mind, consider this code:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
var dt = DateTime.Parse(time);
_elapsedTime = dt.Subtract(_elapsedTime);
_lastTime = dt;
}
You get an instance of a DateTime from a string using Parse
DateTime dt = DateTime.Parse(time)
and then you get get the time Now using
DateTime.UtcNow; or DateTime.Now;
and subtract one from the other and format as appropriate for you output
You can do this using TimeSpan.
you need to get the Difference in Minutes
DateTime dt1;//get your first date
TimeSpan duration = DateTime.Now - dt1;
if(duration.Minutes>20)
Button1.Enabled=true;
I think your looking for this:
private void beginOperstionChecker(DateTime dt)
{
string time = Options_DB.Get_OperationLastTime();
DateTime lastTime = DateTime.Parse(time);
if (DateTime.Now - lastTime > new TimeSpan(0, 20, 0))
{
//It's passed more than 20mins from last save.
}
}
You can check the time elapsed by using the TimeSpan class.
private void beginOperstionChecker(DateTime dt)
{
if(TimeSpan.FromMinutes(20) == DateTime.Now - dt)
{
//do your stuff here
}
}

How can I setup DateTime hour,minute and second?

private void StartAuction()
{
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
}
I am able to set the date,month and year but I want the hours,minutes and seconds to setup automatically to the current time of the day. for example if the current time is 15:24, I want the user to add the date which could be 21/03/2013 and then I want the time to be 15:24:00 and not 00:00:00 as it currently does.
Any suggestions?
Well you can use DateTime.Now to get the current time, then take the TimeOfDay from that and add it to the Date of your existing DateTime:
private void StartAuction()
{
DateTime closeDate = DateTime.Parse(Console.ReadLine());
DateTime closeDateAtCurrentTime = closeDate.Date + DateTime.Now.TimeOfDay;
...
}
(I'm explicitly using the Date property so that even if the user does enter a time as well, it's basically stripped.)
As a blatant plug, you might also want to consider using my Noda Time library, which separates out the ideas of "date", "time" and "date/time" into different types. (As well as "local" values vs ones where you know the UTC offset or the time zone.)
var now = DateTime.Now;
var date = new DateTime(input.Year, input.Month, input.Day, now.Hour, now.Minute, now.Second);
First you need to parse with DateTime.Parse what you read from command line.
Then, you can do that using DateTime.Now.TimeOfDay like;
DateTime closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + DateTime.Now.TimeOfDay;
You could do
closeDate = DateTime.Parse(Console.ReadLine() + " " + DateTime.Now.TimeOfDay);
Which works, but does look a little roundabout and I wouldn't recommend it considering you're converting from a time format to a string and then back to a time format again. Lots of immutable objects being created, there.
There are other options, including to parse the date, as you do, and then add TimeOfDay to it.
DateTime closeDate;
closeDate = DateTime.Parse(Console.ReadLine());
closeDate = closeDate.Date + Date.Now.TimeOfDay;
You can do this:
closeDate = DateTime.Parse(Console.ReadLine())
.Add(DateTime.Now - DateTime.Today);
Well how about this little function:
public static DateTime ChangeTime(DateTime dateTime)
{
return new DateTime(
dateTime.Year,
dateTime.Month,
dateTime.Day,
DateTime.Now.Hour,
DateTime.Now.Minute,
DateTime.Now.Second,
DateTime.Now.Millisecond,
DateTime.Now.Kind);
}
This is a possible solution:
store DateTime.Now in a variable
var date = DateTime.Now;
Then u can access the Hours, Minutes and Seconds like this:
date.Hour;
date.Minute;
date.Second;

DateTime.now subtraction with value from database

I need to be able to get the difference from the current date with the date from my database. If the difference is 30, I need to display a expiry date message. My code block looks as such:
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
The thing is, this returns some weird numbers which I can't seem to manage. How would I go about getting just the number of days and then check if it is 30?
Thanks for having a look guys!
DateTime dt1 = DateTime.Now;
DateTime dt2 = DateTime.Parse(user[3]);
TimeSpan ts = dt1 - dt2;
int days = ts.Days;
if (days == 30){
//do something
}
(DateTime.Now - DateTime.Parse(user[3])).TotalDays //this will give you the days.
var timespan = DateTime.Now - DateTime.Parse(user[3]);
var days = timespan.Days;
System.TimeSpan diffResult = dt1 - dt2;
if(diffResult < 0)
{
//your code
}
When you subtract two DateTime instances you get a Timespan.
Validate your value against the TotalDays property of this timespan
var expiryDate = DateTime.Now - DateTime.Parse(user[3]);
expiryDate.TotalDays > 30 // check in this fashion

Categories