Subtracting an unknown interval from a datetime - c#

I am setting up a system to gather data from a database based on a user inputted start date and end date. The system will gather data averaged over an interval(1 hour, 6 hours, or one day for example). If the user does not input a start or end date I would like the program to set the start date to the current time minus the interval.
I currently have the user inputting the interval in the following format.
1m = 1 minute
1h = 1 hour
12h = 12 hours
3d = 3 days
So these values are not formatted like datetime. I could take the current datetime and subtract it by either minutes, hours, or days depending on the value appended (splitting on the number), but this would mean many if statements. What I would really like is a method to subtract a datetime by an arbitrary value Does anyone have a better solution?

Instead of providing predefined time intervals (that are implemented e. g. via a separate type/enum), it is much easier to let the user freely specify a TimeSpan.
This has two advantages:
The user is not restricted to predefined intervals
You can subtract the TimeSpan directly from your DateTime.Now
If restriction to limited intervals is a requirement, you can implement this in the view/window. But still this should be a TimeSpan.

Related

Subscription system with days count down?

I'm trying to make a subscription system where each user has a specific number of days on their account and everyday the number of days goes down by one until it reaches 0 days. How can I decrease the number of days of all accounts that have over 0 days, everyday and also output the date when the number of days will reach 0 in the format DD-MM-YYYY.
Thanks.
EDIT:
I found a way to convert days into date form in C# but how do I convert a date format into just the number of days?
Converting days into date format:
DateTime.Now.AddDays(subDayz).ToString("d-MMM-yyyy", new CultureInfo("en-GB"));
Maybe there is a way to do it in PHP, or do it in C# but prevent the user from changing the date to get more days?
Instead of a countdown, when you create a new account set a database column to the date when the account expires (aka when the countdown ends) in DD-MM-YYYY format. For example, if the account is created today ("31-03-2018") and expires in 15 days, set this field to "15-04-2018".
Now there's no need to update this (and all other active accounts) every day! If in the future the current day's date is greater than this expiry date, then the account is expired (aka countdown ended).
BTW, to make it easier to compare dates, store in YYYY-MM-DD format and do simple string comparison. Reformat if needed and as required for display purposes.

Calculate length of time between two times in AM/PM

I have three DrowDownLists for selecting start time and another three for selecting end time. I need an asp.net program which will give duration between two time and after i entered start time then end time should be greater than start time. First DrowDownList contains 1 to 12 hours and second contains 0 to 59 minutes and third one is for selecting am/pm.
I don't know where to start in codebehind.
You could first turn your strings into TimeSpan, try out TimeSpan.Parse:
https://msdn.microsoft.com/en-us/library/se73z7b9(v=vs.110).aspx
With two TimeSpan objects, you will be able to calculate durations without having to worry on how to do it. To get the duration between two timespans, try out TimeSpan.Subtract:
https://msdn.microsoft.com/en-us/library/system.timespan.subtract(v=vs.110).aspx
hope this helps!

Accuracy of comparing DateTime.now of C# and GetDate() from SQL

What i am doing is that, i need to select a row that i have just recently added through DateTime to get the PK since i need it.
I store the DateTime through:
DateTime nw = DateTime.now and i use nw to search through my table.
My question is that, what if let's say i put 2 rows within a span of 1 minute?
My sql table stores them like this:
Since milliseconds isn't visible, will both of them be selected?(assuming everything happened within 1 minute)
Edit: this is from my asp mvc project. So the DateTime is new everytime my action is run.
The problem is precision. The GetDate() function in TSQL is not at the precision as c# DateTime, as GetDate() returns an TSQL DateTime.
TSQL DateTime:
Defines a date that is combined with a time of day with fractional seconds that is based on a 24-hour clock.
Rounded to increments of .000, .003, or .007 seconds
C# DateTime:
The Ticks property expresses date and time values in units of one ten-millionth of a second, and the Millisecond property returns the thousandths of a second in a date and time value. However, if you are using repeated calls to the DateTime.Now property to measure elapsed time, and you are concerned with small time intervals less than 100 milliseconds, you should note that values returned by the DateTime.Now property are dependent on the system clock, which on Windows 7 and Windows 8 systems has a resolution of approximately 15 milliseconds.
However you could use the newer (avail as of SQL Server 2008) SysDateTime() which returns a datetime2(7) value that should match the precision of C# Datetime.
datetime2(7):
Defines a date that is combined with a time of day that is based on 24-hour clock. datetime2 can be considered as an extension of the existing datetime type that has a larger date range, a larger default fractional precision, and optional user-specified precision.
This only academically interesting because you should never use a datetime as a PK.
Let's say it's Nov 6, 2016 at 1:15AM. You create a record:
MyPk
------
2016-11-06 01:15:00
One hour later you create another record...
MyPk
------
2016-11-06 01:15:00
2016-11-06 01:15:00
Duplicate PKs due to daylight savings. Don't have daylight savings? There are a multitude of reasons to not use DateTime for a PK (simply google search for datetime as primary key).
Just to name a few:
Exact select can be very difficult (milliseconds matter!)
Foreign Keys become a Nightmare
Replication is very difficult unless all systems are in the same timezone
If you really want to use the DateTime.Now with second precision as a way to find the PK of your data, you should not declared it once and use it everywhere. Rather, you should use it like this:
insertDataToDataBase(data, DateTime.Now);
and then 10-20 seconds later
insertDataToDataBase(data, DateTime.Now); //still use DateTime.Now
This way your DateTime.Now will always be updated

How can I get the duration in terms of minutes by subtracting a previous time stamp stored in a DB from the present time in C#?

How can I get the duration in terms of minutes by subtracting a previous time stamp stored in a DB from the present time in C#?
The previous time stamp format is 13:00.
I want to calculate how many minutes have passed. How to do it?
Plus the fact that the previous datetime Stamp is stored in a DB as e.g.13:00 (hh:mm). So I do not understand how I am able to substract 13:00 from the current DateTime.Now.ToShortString().
You can substract two DateTime objects and get a TimeSpan object. Then use TimeSpan.TotalMinutes.
DateTime dateTimeFromDatabase = DateTime.Parse("13:00");
double minutes = (DateTime.Now - dateTimeFromDatabase).TotalMinutes;

What is a meaningfull datatype to save hours

What is a good data-type for saving hours in .net?
Is it better to use the decimal type or is the double data-type more appropriate. With hours I mean values such as:
2 for two hours
1.5 for 90 minutes
8.25 for 8 hours and 15 minutes.
A good way to represent a number of hours is to use a TimeSpan:
TimeSpan hours = TimeSpan.FromHours(2);
Given the choice between decimal or double I'd probably go for double as there is typically no expectation that the amount of time is represented exactly. If you need an exact decimal representation of your fractional number of hours (which seems unlikely) then use decimal.
You could also consider storing it as an integer in for example seconds, milliseconds or ticks.
The best datatype to store hours is the one designed for it - TimeSpan.
It has methods that allow you to add/subtract/convert it.
As for storage in a database, it really depends on what you are using this for and what kind of resolution is required.
I would use the time datatype - as it will hold the range:
00:00:00.0000000 through 23:59:59.9999999
However, if you need to hold more than 24 hours in this field, you may want to consider a tinyint or int holding the number of minutes (assuming that is the maximum time resolution you require).
In SQL Server use INT or DECIMAL. TIME isn't really ideal for storing a duration because TIME defines a point in time within the 24 hour clock whereas duration is simply an integer or decimal value. You cannot do addition or subtraction with TIME values and there is no obvious way to use TIME to store durations greater than 24hrs.
Why don't use TIME?
You can use DATEADD with TIME to manipulate it easier:
SELECT DATEADD(minute, 30, CAST('2:00:00' AS TIME))
becomes 02:30:00.0000000. And so on..

Categories

Resources