Generating Calendars - c#

How can I code a calendar? I mean how can I determine the days of the month, is the 1st a monday, tuesday or what. how many days are there in the particular month etc.
I use mainly PHP & C#. But I am mainly looking for the logic behind

Take a look at the DateTime type in the MSDN for C#.
You can determine the Weekday of a given day the following way:
var date = DateTime.Parse("16.10.2010");
Console.WriteLine(date.DayOfWeek);
If you are looking for the amount of days in a month, try this:
Console.WriteLine(DateTime.DaysInMonth(date.Year, date.Month));

Most languages (PHP and C# included) will provide utility functions or libraries which allow you to play with dates without having to get too involved in the gritty calculations.
PHP's date() and getdate() functions will tell you most details about a given date, including the day of week, day of month and day of year, provided you start with it in timestamp format.
If you want to find the details of the first of a given month, use the PHP mktime() function to get the time stamp for the date you want, then pass that into getdate() as above.
To find out how many days long a month is, you could either use a lookup table (ie Jan=31, etc), with a special case for Feb, or use the above method to get the 1st of the next month, and subtract 24 hours to get the last of the current month.
If you're using an up-to-date version of PHP (ie 5.3), there is a very useful new date class which supersedes most of the old date/time functionality, and provides a lot more besides. (it's also there in PHP 5.2, but not nearly as good as the 5.3 version).

Take a look at the GregorianCalendar class in C#. This will tell you what you need to know regarding a date according to different date "rules".
This will help you find things like the week number of a date that the DateTime class won't manage for you.

Related

Convert user given date (January or 01. February 2017) to a timestamp

i'm trying to parse a user input of a date to a MySQL Timestamp format (YYYY-MM-DD).
User input could be something like:
input - wanted conversion
1) January - ThisYear-01-01, ThisYear-01-31
2) February 2017 - 2017-02-01, 2017-02-28
3) 01. April 2016 - 2016-04-01
4) 5.4.15 - 2015-04-05
P.S.:
The examples above are the suggested formats that we want to support (supporting only some of them would be also fine).
The users are not random or international, they will always write and understand dates in this format (Day Month Year).
Handling the missing year entry or the zero (like 5/4 in #4) isn't a problem but finding a proper way to handle the mentioned possible date input formats (DD MM YY, DD MM, DD Month, Month, Month YY, DD Month YY....etc.) with something that doesn't look very ugly and long in code is a little bit hard for me to imagine.
P.S.:
D,DD,MM,YY,YYYY are short for the numerical input.
Month is for the word input variant.
Could you please tell me if there is anything that could help me to make this process easier/more readable or at least point me to the right direction?
Thanks
Update #1:
By looking again to my question above i see that it's missing some background information, but i didn't want to write a long description to it, just only to the wanted function. Sorry.
So here are some general infos about the Program:
The Program is a Chatbot written in C# (UWP) which accepts a user request in natural language and give back the requested info (if recognized) from a mySQL DB (DB is based on a OSTicket support system).
Internally we send the user input to LUIS.ai to get it recognized and we get back the intents and entities from the service, which we then parse to a SQL Query and send it to the DB.
The results from the DB are then sent back to the user.
Many parsed queries work perfectly, that's why i want now to extend it by letting the user give a certain date in the request (e.g. give me all the support tickets from April).
What i only want is to take this new input "April" and convert it to a MySQL TimeStamp format, so that it would be also recognized from MySQL.
My current approach is to build a string like this:
string convertedTS = year + "-" + month + "-" + day;
And using 3 functions try to detect all three variables. But that's it for now.
E.g. "give me all the tickets from April":
April (recognized from LUIS AI as given date) will be converted to (04)
Year will be taken from
DateTime.Today.Year
and inserted too (2018-04)
The first day is always 01 and the last day of the month will be:
DateTime.Today.Year
Final Query from the example:
select ..........between '2018-04-01' AND '2017-04-30'
If you're worried about formatting the years, months, days, etc, you're doing it wrong. You have C#, and you have a date string from the user. Your concern is getting that string into a C# DateTime value. MySql has no part of this.
Once you have the DateTime value, let your connection provider worry about formatting via parameterized queries:
DateTime d = GetMyDateTimeValueFromUser();
string sql = "pretend SQL comnand with a datetime #variable";
using (var cn = new MySqlConnection("connection string here"))
using (var cmd = new MySqlCommand(sql, cn))
{
cmd.Parameters.Add("#variable", MySqlDbType.Timestamp).Value = d;
cn.Open();
//pick one.
cmd.ExecuteReader();
cmd.ExecuteNonQuery();
}
No special SQL format needed. If you're not using parameterized queries, you're not doing it right! This applies to much more than just DateTime values. All data used in an SQL statement should be handled this way. This has security and performance implications that go way beyond simple date values. Go parameters, or go home (I mean that: go home. Don't write bad code. We don't need any more.)
As it applies to the question, it means the problem is entirely about parsing a string to a C# DateTime value. The next step of moving this data to SQL is just not relevant. Thankfully, .Net has some options for you here. Specifically, take a look at the Parse family of functions, including:
DateTime.Parse()
DateTime.TryParse()
DateTime.ParseExact()
DateTime.TryParseExact()
The latter two allow you specify a set of allowed formats that can match the formats actually seen by your system. NuGet can be a further resource in this area.
What's that, you say? You want to allow the user to input anything? That just won't work. Period. Real humans can and will come up with far more ways to enter a date than you could possibly ever handle. Not to mention you need to know what to do when a British citizen inputs the value 1/2/2018 into your system, because that person almost certainly believes it means February 1, 2018, and not January 2. Cultural differences like this mean it is impossible to accept date inputs without some kind of contextual input filter on the front end. You must look to your user interface to help your users create values your code will understand... but we don't have enough info in the question to provide any guidance yet in that area.
I fixed that for the purpose of using it in my program.
Now i can detect and understand such inputs:
"09 11 2008"
"2017"
"today"
"yesterday"
"09/11/2002"
"march 2017"
"01.01.2010"
"01-01-2010"
"01 may 2019"
"31.October 2020"
"01 april"
"december"
If anyone is also interested in writing a similar function leave a comment, because the code is almost 300 lines.

how to specify day and month but not the year in DateTime in c#

Hi All
I am using DateTime class to do some processing on dates. The issue I am facing is that in some cases i would like it to initialize to date component excluding the year part of date. How do i do that?
Example: For date 11/March/2011, I only want to store 11-March. How do i do that?
Thanks
You can't with the DateTime class (actually a struct). You can ignore the year value in your processing, however. You could also create your own class to do what you want.
You can't to that with DateTime because it is used to represent a specific moment time.
Since a day and a month are not sufficient information to represent a date, you can't store these information in DateTime only.
Maybe you should explain further what you would like to achieve.
If your concern is about outputting/formatting this date please view the following document in MSDN for format options you can apply to the toString() method of DateTime.
MSDN: Standard Date and Time Format Strings
Something you could do if you are really forced to use DateTime is to rebase each entered date to a specific year, although I can't see how this should make any sense, especially when it comes to leap years
One way you can do this is to use the TimeSpan structure. Then you can use that on top of any DateTime calculations you need

Representing date having 32 as maximum value for Day

I am building application in asp.net using Sql server 2005. In my application I have to represent many dates & dates are of Nepali(Bikram sambhat) in which the maximum day for some month can be 32.
So what is the best option to represent the date in sql server so that 32 can be placed for day value & that can be easily compared(manipulated) in sql server as well as in asp.net?
There is a guy that has implemented some classes for converting between Nepali dates and Gregorian dates. This way you can input dates in the Nepali format but store them in a format that SQL Server understands. Look here: http://rrajbhandari.blogspot.com/2010/06/bikram-sambat-classes-and-controls.html
Remember that a date in either calendar can be converted to another calendar - they point to the same day.
I would recommend using the built in Date type. It sounds like any date in your format can be easily converted into the standard sql format.
I would just write a utility to convert any date from sql server into your display format whenever you load or write to the database.
There isn't an easy conversion from Nepali to Gregorian. Think of it in two ways:
need to show Nepali date
need to manipulate (e.g. find difference between months, days etc)
The first one is easy - store as a varchar
The 2nd one is not. If you wanted to know the difference between 2 Nepali dates, you can store the date a 2nd date as the Gregorian equivalent and use datediff/dateadd(day) between them. However, dateadd(month) will be useless for you here unless you wanted to know the difference of 2 Nepali dates in Gregorian date months - not common.
Sounds like just storing in varchar and having a library for Nepali dates, either in the front end or as a CLR, would go down better.
It may help for conversions to have a fully materialized Nepali date table with the corresponding Gregorian date, so the layout would be
NepaliYear NepaliMonth NepaliDay Gregorian
x 4 2 2014-21-23
etc
But I am not sure it would help much for (Nepali) date maths beyond conversion - and only if you need such conversion within SQL Server.
EDIT
#pst's comment
There is a reason to prefer VARCHAR to datetime. I assumed that the frequency, most of the activity is reading/writing a Nepali date - which is stored and read as a VARCHAR - no conversion. If and only when date maths is required does it involve the library - in which case you invoke conversion, and only then if you need at any point in time the Gregorian calendar equivalent. If all you wanted is maths between NepaliDate/scalar or NepaliDate/NepaliDate - again, datetime offers no benefit whatsoever - it cannot handle day #32 in a month.
Check out Nepali calendar, it may help.

Strategy for Incomplete Dates

Working on an application where we would like the user to be able to enter incomplete dates.
In some cases there will only be a year - say 1854, or there might be a year and a month, for example March 1983, or there may be a complete date - 11 June 2001.
We'd like a single 'date' attribute/column - and to be able to sort on date.
Any suggestions?
Store the date as an integer -- yyyymmdd.
You can then zero out any month or day component that has not been entered
Year only: 1954 => 19540000
Year & Month: April 2004 => 20040400
January 1st, 2011 => 20110101
Of course I am assuming that you do not need to store any time of day information.
You could then create a struct to encapsulate this logic with useful properties indicating which level of granularity has been set, the relevant System.DateTime, etc
Edit: sorting should then work nicely as well
I can't think of a good way of using a single date field.
A problem you would get if you used January as the default month and 1 as the default day like others have suggested is, what happens when they actually pick January? How would you track if it's a selected January or a defaulted January.
I think you're going to have to store a mask along with the date.
You would only need a bit per part of the date, which would only be 6 bits of data.
M|D|Y|H|Min|S
Month Only 1|0|0|0|0|0 = 32
Year Only 0|0|1|0|0|0 = 8
Month+Year 1|0|1|0|0|0 = 40
AllButMinSec 1|1|1|1|0|0 = 60
You could put this into a Flag Enum to make it easier to use in code.
Well, you could do it via a single column and field that says 'IsDateComplete'.
If you only have the date field, then you'll need to encode the "incompleteness" in the date format itself, such that if the date is, say, < 1900, it's considered "Incomplete".
Personally, I'd go with an field on the side, that marks it as such. Easier to follow, easier to make decisions on, and allows for any dates.
It goes without saying, perhaps, that you can just create a date from DateTime.MinValue and then set what you "know".
Of course, my approach doesn't allow you to "know" what you don't know. (That is, you don't know that they've set the month). You could perhaps use a date-format specifier to mask that, and store it alongside as well, but it's potentially getting cumbersome.
Anyway, some thoughts for you.
One option is to use January as the default month, 1 as the default day, and 1900 or something like that as the default year. Incomplete dates would get padded out with those defaults, and incomplete dates would sort before complete ones in the same year.
Another, slightly more complex option is to use -1 for default day and year, and -1, 'NoMonth', or some such as the default month. Pad incomplete dates as above. This may make sorting a little hard depending on how you do it, but it gives you a way of telling which parts of the date are valid.
I know you'd rather have 1 column but, Instead of a single column one can always have a separate column for day, month and year. Not very difficult to do queries against, and it allways any of the components to be null.
Smehow encoding these states in the datetime itself will be harder to query.
What I did when last solving this problem, was to create a custom date type that kept track of which date parts was actually set and provided conversions to and from a DateTime. For storing in database i used one date field and then one boolean/bit to keep track of which date components that were actually set by the user.

Building a Datetime Object for SQL database insert

I'm working on a small web form that requires the user to input (among other things), the scheduled backup time of whatever server they're adding to the system. The problem is, I'm struggling to find out the best way to take the user input and build a DateTime object (which is what the database requires).
I only really care about the Day of Week, Time of Day (12 or 24 hour clock).
I thought about just creating an empty DateTime object and then just adding my input values from the user, but you can only get, not set, the day of week, time of day, etc.
I've been looking at the Calender asp control, which would work for the day of the week selection, but I can't seem to find any support of time of day.
Thanks.
I don't think you want to use a DateTime for a recurring event such as a backup. A DateTime is useful for storing a particular date and time, but not a "template" for a recurring event. Instead I'd use separate columns to store the day of week value (0-6) and time of date (minutes after midnight) for the event.
If you going to use datepicker here is one great sample for adding JQuery date picker using C#. That helped me including in my project evrn if I did know anything abaut JQuery and java sripts at all.
DateTime is a immutable value type. You cannot set anything on it.
Assumed that you stick with DateTime on the DB and you don't want to use a DateTimePicker control.
You have to specify how the day of week and the time should be represented in the DateTime. You can start with DateTime.MinValue, the 1.1.0001, 12:00 at midnight, and add the day of week and the time. unfortunately, a regular DateTime field in a SqlServer 2005 is not able to store this date. So lets move it to the year 2000. The 1.1.2000 was a Saturday. You could calculate the DateTime like this:
int dayOfWeek; // 0 = mon, 6 = son
DateTime time;
DateTime scheduleTime = new DateTime(2000, 1, (dayOfWeek + 2) % 6 + 1)
+ time.TimeOfDay;
But honestly, I wouldn't do it. It smells. I just answered your question. Listen to tvanfosson. He said everything that needs to be said.

Categories

Resources