Ways to format time/duration in C# using short version - c#

I'm looking for a way to format time duration originally expressed in hours (as a 'double' variable) for an ASP.NET web app written in C#. I need a short version that has only 2 significant values. For instance:
1h:20m
2d:20h
2mo:12d
5y:2mo
I searched and it seems like C# does not have a built-in function for what I need.
So I decided to write my own but I'm stumped with correct formatting of all the parts. For instance, I may get a string, such as "1d:24h", or for a simple 2 months, I may get "1mo:29d"
PS. The problem I've encountered is in defining how many days are in a month and in a year.

DateTime's are renowned for being an annoying task.
As there is no indication as to which months you are referring to, with the given information this would be impossible. Months can have 28, 29, 30 and 31 days depending on what month/year you are taking into consideration..
Without an indication as to which months you are dealing with, the flip from 1 to 2 months would be a random guess as to which day you make the transition. You will either have to add in more incoming parameters to account for this, or explain to the user that a month is considered x days and only x days.
Another thing to consider would be daylight savings. 1pm + 24 hours may not be 1pm the next day. In such circumstances with you or the end user may wish to consider such days 23h=1d or 25h=1d.

Related

Can DateTime represent a date before Christ / before our time? or How is this managed?

So, I noticed DateTime.MinValue defaults to 01-01-0001 (dd-MM-yyyy), so for example let's say we have a museum database/class object whatever, how do you store an object that is from 10,000 BC or how about dinosaur bones that are from millions of years prior to today?
Can it be a signed value? like, the year "-10000" represents BC?
or we would need to rely on strings and be unable to natively work with dates prior to year 1?
I checked this question out that asks for year zero, but it doesn't have any helpful insights, other than apparently not everyone knows there is no such thing as year zero. how make a datetime object in year 0 with python
No, DateTime doesn't handle anything before 1CE.
My Noda Time project does support BCE dates, but still limited to about 9998 BCE as the earliest it can handle.
Once you're talking about prehistoric times, you probably have a different set of use cases from normal date/time types anyway - so just extending the range of the existing types may well not help you much. (As an example, quite often ancient history deals with relative dates: "I know battle X took place 3 years into the reign of king Y, but I don't know exactly when either of them happened.") I'd suggest you think about what your actual use cases are, and what you need to do with the date/time information. Then you can look into whether existing libraries meet your needs, or whether you need to write your own abstractions.
After digging around, I've found that other than creating one's own types, there is no easy native solutions to this specific use case for dates, so I want to propose my solution in case its of use to anyone. Just add a column that will have a sign, a - and a + (or a 0 and 1 I guess with a boolean type). Dates with + are AC and dates with - are BC. On your code or otherwise you'll have to handle the sign. Its simple and requires no extra libraries or technologies.
Since dates have no zeros the sign should not create interference, and just minding negative dates move in reverse order in your logic will solve any issues with that. However this solution only works for dates up to year 9999, so in order to be able to handle even farther away dates, a more complex sistem would have to be programmed. like handling each part of a date in a separate column so it can cover as many years as int or double can do numbers.
However, I do think positive dates from the year 3000 up to the year 9999 will hardly ever be used, much less towards millions of years into the future. But maybe it will be of use for fan proyect databases for sci-fi universes like 40K or SW or ST.

Alexa understand 24 hour

I am trying to build an Alexa skill that asks the user for an arrival time and I am expecting the answer to be in 24 hour format. So the user would say eighteen o five for 18:05.
I am struggling to find a way for Alexa to understand this without forcing the user down the 12 hour route.
Any suggestions welcome.
The AMAZON.TIME slot type is available but, unfortunately, doesn't work like you want.
If you're happy for users to say "six fifteen pm" it will pass a 24H time to your skill.
This might be unconventional, but have you tried
AMAZON.FOUR_DIGIT_NUMBER
If you think about it 24 hour format is also a 4 digit number
I got around this in the end by using just the one custom slot type which takes the whole time in a malformed state. 18:05 comes in as 18o5. I then use a method within my code to tidy that up. Not the most scientific way to do this, but seems to work.

DateTime with same amounts of days for each month

is there an easy way or a ready to go class for having a DateTime where every month has the same amount of days?
I'm writing a calculation tool for resource planning and we use a standard month, no leap years etc.
Update:
OK maybe I should have mentioned a little big detail - I tried going for 365/12 = 30,42days/month. I can't see that happening as I always run into trouble when for example trying to get the days from my ticks (division and 1.999999999 etc).
In the financial markets, there are a lot of ways of counting the numbers of days in a year, the number of days in a month, etc. A particular way is called a "day count convention", see e.g. the wikipedia article on day count conventions. One type of day count conventions tries to do exactly what you're talking about, namely have 30 days in each month. These day count conventions are called 30/360, and as you can see from the wikipedia page there are several variations on this. All these conventions are very straightforward to implement, so my suggestion would be to choose one of these day count conventions and code it yourself.

Get dayspan according to dates, not duration?

I am trying to get the number of days between two datetimes, but not according to the exact timespan, rather according to the "day date" difference between date a and date b. No hours taken in account.
So far, I calculated the age of an item using :
(DateTime.Now - creationDate).Days
The problem with this code is that, for something that was created the day before but less than 24h ago, it will output "0 days", which is not very clear to my users apparently.
So what I want to accomplish is, even for an item that was created at 11:59pm for example, to get an output of "1 day old" as soon as the clock hits midnight. How could I accomplish this?
Two options:
1) Take the two dates first:
var days = (DateTime.Today - creationDate.Date).Days;
2) Use my Noda Time date/time library instead, using LocalDate for the two dates involved, and then Period.Between(start, end, PeriodUnits.Days) to get a period of just days. (You can also get weeks, months etc.) Admittedly getting "today's date" is deliberately a bit trickier in Noda Time - where .NET implicitly uses "the system time zone," Noda Time forces you to be more explicit.
I would use it simply like
int days =(int)DateTime.Now.Subtract(creationDate).TotalDays;
hope this helps

Add 1 week to current date

I've got something like this DateTime.Now.ToString("dd.MM.yy"); In my code, And I need to add 1 week to it, like 5.4.2012 to become 12.4.2012 I tried to convert it to int and then add it up, but there is a problem when it's up to 30.
Can you tell me some clever way how to do it?
You want to leave it as a DateTime until you are ready to convert it to a string.
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
First, always keep the data in it's native type until you are ready to either display it or serialize it (for example, to JSON or to save in a file). You wouldn't convert two int variables to strings before adding or multiplying them, so don't do it with dates either.
Staying in the native type has a few advantages, such as storing the DateTime internally as 8 bytes, which is smaller than most of the string formats. But the biggest advantage is that the .NET Framework gives you a bunch of built in methods for performing date and time calculations, as well as parsing datetime values from a source string. The full list can be found here.
So your answer becomes:
Get the current timestamp from DateTime.Now. Use DateTime.Now.Date if you'd rather use midnight than the current time.
Use AddDays(7) to calculate one week later. Note that this method automatically takes into account rolling over to the next month or year, if applicable. Leap days are also factored in for you.
Convert the result to a string using your desired format
// Current local server time + 7 days
DateTime.Now.AddDays(7).ToString("dd.MM.yy");
// Midnight + 7 days
DateTime.Now.Date.AddDays(7).ToString("dd.MM.yy");
And there are plenty of other methods in the framework to help with:
Internationalization
UTC and timezones (though you might want to check out NodaTime for more advanced applications)
Operator overloading for some basic math calcs
The TimeSpan class for working with time intervals
Any reason you can't use the AddDays method as in
DateTime.Now.AddDays(7)

Categories