The max date accepted by Datetime data type in SQL Server and C# seems to be 31/12/9999 23:59:59. I have tried to assign a data value (01/01/9999 00:00:00) from database to a datetime picker. It failed saying
DateTimePicker does not support dates after 31/12/9998 00:00:00.
Parameter name: MaxDate
Now my question is when both the datatypes are compatible (datetime), why does these is restriction in Datetimepicker. This seems to be by design. Can any let me know why this restriction and how this feature in design is going to help?
Thank you
In normal operations the date time picker has to be able to display dates after the selected date. This means that if you selected the max date (31st Dec 9999) then theoretically it would have to display 1st Jan 10,000 - which it can't.
Therefore the picker itself restricts the initial value to be some arbitrary value before the max date so subsequent dates can be shown.
I don't see that this is a problem. When, in a real world application, is the user going to want to set a date 7000+ years in the future?
If your application has unset dates then perhaps you need to consider storing them as null in the database (i.e. make the column nullable) so that it's presented as a blank on the UI. This may actually make it easier for the user to spot dates that haven't been set.
It's as simple as that DateTimePicker checks against
DateTimePicker.MaximumDateTime
which is defined as december 31 9998
here's the relevant portion from the referencesource
public DateTime Value {
set {
bool valueChanged = !DateTime.Equals(this.Value, value);
// Check for value set here; if we've not set the value yet, it'll be Now, so the second
// part of the test will fail.
// So, if userHasSetValue isn't set, we don't care if the value is still the same - and we'll
// update anyway.
if (!userHasSetValue || valueChanged) {
if ((value < MinDate) || (value > MaxDate)) {
throw new ArgumentOutOfRangeException("Value", SR.GetString(SR.InvalidBoundArgument, "Value", FormatDateTime(value), "'MinDate'", "'MaxDate'"));
}
}
And MaxDate checks DateTimePicker.MaximumDateTime
http://referencesource.microsoft.com/#System.Windows.Forms/winforms/Managed/System/WinForms/DateTimePicker.cs,040fca665238ae30
Related
I am trying to print pdf report using itextsharp pdf and all the values are correct except the values from column "Date" and "Time".
The date and time is displayed in a format like "dd/MM/yyyy tt hh:mm:ss" for eg. Date is: 08/10/2021 AM 12:00:00 and Time is: 30/12/1899 AM 07:46:37.
I have done everything mentioned below:
Inserting the date value from the datetimepicker as datetimepicker.Value.ToString("dd/MM/yyyy") and time value to be DateTime.Now.ToString("hh:mm:ss tt")
My datatype for Date and Time column in MS Access database is Date/Time
My database is showing correct formatted value and datagridview has incorrect format of Time column and generated pdf report have incorrect date and time format. My only question is how can this be possible as database consist of correct data but after displaying it in datagridview the format changes and even after printing it. Below I have attached images that will help you get the scenario.
Datatype for the column from database↓
Values in database↓
Values in Datagridview↓
you can try to set the DefaultStyle property like this
dataGridView1.Columns["YourColumn"].DefaultCellStyle.Format = "HH:mm:ss";
Or set it in the designer, whatever you like most.
In your database your Time column seems to have only a time value, but it has not. It uses the lowest possible date value, which is 30/12/1899 for an Access Database.
This happens when you only feed that column with a time, and no date. Acces (and other databases also) will simply use their lowest possible date value to fill up the missing date value.
The DataGridView therefor has no choice but to also show the date along with its time.
The property above will simply instruct the DataGridView to not show the date part, only the time part.
If you need to display the time in code in C#, you could use this
YourDateTimeVariable.ToString("T");
But, since you are storing both date and time in datetime columns, why do you store them seperate ?
You could just store them in one column, and show/use only the part you need.
EDIT
to respond to the code you posted in the comments (please add this code in your question, not in the comments)
change this
invoicesDatagridview.Rows[i].Cells[1].Value.ToString())
into this
((datetime)invoicesDatagridview.Rows[i].Cells[1].Value).ToString("T"))
in case this column can by null you will need some extra checks to avoid cast errors.
Also, the format in the GridCell willl never be used in a ToString(), you are doing the ToString() on the value, not on the display text.
Try the code above to fix this
EDIT
To respond to your comment below:
Printing code is not the point. I just want to know that how can datagridview cell value and print value be of different format –
karan ugale
By setting the DefaultCellStyle you tell the DataGridView what format to use to display the value. When you print this value with your own code using ToString(), how on earth should this ToString() know of the DefaultCellStyle setting ? The print code with ToString() has absolutly no connection with the DataGridView, you just pass it the value nothing more.
Look at this example
invoicesDatagridview.Rows[i].Cells[1].Value.ToString())
this can be written like this
var someValue = invoicesDatagridview.Rows[i].Cells[1].Value;
someValue.ToString();
now tell me, how should someValue.ToString() know of any format ?
The epoc of data type Date in Access is 1899-12-30, and as you display both date and time, that date is displayed as well.
In .Net you can apply the format string "T" to display hour-minute-second only. For example:
DateTime time = new DateTime(1899, 12, 30, 8, 12, 16);
Console.WriteLine(time.ToString("T"));
// 08:12:16
I want to insert date into database in dd/MM/yyyy format. For that I have written like below:
drExpInfo[0]["CHEQUE_DT"] = string.IsNullOrWhiteSpace(e.Record["CHEQUE_DT"].ToString())
? DBNull.Value : (object)Convert.ToDateTime(e.Record["CHEQUE_DT"]);
And it is working perfectly fine on my local machine, but on my server it is taking format as dd/MM/yyyy hh:mm:ss. So how to set the same format there too. Kindly suggest.
Use DateTime.ToShortDateString:
drExpInfo[0]["CHEQUE_DT"] = string.IsNullOrWhiteSpace(e.Record["CHEQUE_DT"].ToString())
? DBNull.Value : (object)Convert.ToDateTime(e.Record["CHEQUE_DT"]).ToShortDateString();
But, I suggest you keep the time part of your date (without using the ToShortDateString as it will insert a time set to midnight, cf. highlighted text in Oracle documentation below) when inserting and get the format you want (without time) when you're using the date.
From Oracle documentation:
Oracle Database automatically converts character values that are in the default date format into date values when they are used in date expressions.
If you specify a date value without a time component, then the default time is midnight. If you specify a date value without a date, then the default date is the first day of the current month.
Oracle Database DATE columns always contain fields for both date and time. If your queries use a date format without a time portion, then you must ensure that the time fields in the DATE column are set to midnight. You can use the TRUNC (date) SQL function to ensure that the time fields are set to midnight, or you can make the query a test of greater than or less than (<, <=, >=, or >) instead of equality or inequality (= or !=). Otherwise, Oracle Database may not return the query results you expect.
So you can convert you're date in any format you want in c#, removing the time part, Oracle will automatically set the time part of your date as midnight (00:00:00).
You can set CultureInfo;
var cultureInfo = new CultureInfo("en-GB", false).DateTimeFormat;
string result = Convert.ToDateTime(e.Record["CHEQUE_DT"], cultureInfo).ToString();
Check this Discussion
Here you can find two or more ways to setting date format while insert records into database.
insert into sampleDate(Start_Date) values (to_date('25-Jun-2017','YYYYMMDD'))
Try:
public static DateTime? DateFromString(string value)
{
if (string.IsNullOrWhiteSpace(value))
{
return null;
}
else
{
return DateTime.ParseExact(dateString, "dd/MM/yyyy", System.Globalization.CultureInfo.InvariantCulture);
}
}
DateTime? date=DateFromString(e.Record["CHEQUE_DT"]);
drExpInfo[0]["CHEQUE_DT"] = date==null? DBNull.Value : (object)date);
I am having hard time to store date information into the datetime column of SQL Server.
I get the input from the user for three columns:
Creation Date
Preparation Date
Next Preparation Date
I use calendarextender and format the date as "yyyy/MM/dd". When all the fields have date, they are stored in the DB as for instance, 16-10-2016 (dd-MM-yyyy).
At this point I have two issues:
These columns are optional, when some of them are empty my code does not work (I assume because datetime cannot be null). To overcome this, I am using the following code snippet but still does not work.
DateTime? creationDate= null;
if (creationDateTextbox.Text != null && creationDateTextbox.Text != "")
{
creationDate= Convert.ToDateTime(creationDateTextbox.Text);
}
When I fetch the dates from DB, they are shown as 10/16/2016 (MM-dd-yyyy) which is different how I formatted it. I would like to show it in the format user enters them.
Dates do not have a format while stored in a database. It is actually usually just a very large long that counts the number of milliseconds from a set starting date.
If you want to store the format you need to stop storing it as dates and instead just treat the text as text in the database, however if you do this you won't get the advantage of sorting or filtering by a date range because it will just be seen as text.
Date time doesn't have any format You can format is as a string, suppose your DateTime type database field dt which contain date as 10/16/2016 (MM-dd-yyyy) then you can convert it
string s = dt.ToString("yyyy/MM/dd");
The answer to one of your questions is here: MSDN
You can use data annotations to format the dates that you get from your SQL DB. I'm assuming that you're using EF6; if not, you can change the field to a varchar in SSMS, and store the date as a String.
And the second, I'm unclear about, but if what you want is for your SQL DB column to be optional, you can use the Optional data annotation for that.
I'm new to date timepickers. I was wondering if someone could explain them to me properly. I have a booking system that you must be able to book a date and specific time in the future and reserve that time frame in a sql database. Can I do it with date timepickers? It has a nice interface when its on my form but I cant see a way for the user to set the time? it always just gives me the default time. Any help? thanks
http://imgur.com/arZPxA5
The DateTimePicker-Control has a Format-Property, which will set the format of the date and time displayed in the control.
AS stated in this answer you can use following format to show Date and time:
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM.dd.yyyy hh:mm:ss";
Here you can get a list of all format string and their descriptions:
List of CustomFormat-String
The result will look like this:
.NET also has a structure called DateTime to save your selected value.
You can save it with following code
DateTime yourSelectedDateTime = dateTimePicker1.Value;
textBox1.Text = yourSelectedDateTime.ToString();
Date Time pickers are pretty useful to use when you want people to be able to visually select a date/time. once the user selects a datetime, you can access it like this
int mymonth = this.datetimepicker1.Value.Month
int myday = this.datetimepicker1.Value.day
etc...
Furthermore, you can use events to trigger when stuff happens with them. So for instance, they select a date, you can use the ValueChanged event to make other fun stuff happen too.
this is just weird and is giving me a headache. I looked over my code and I don't see any logical errors causing it.
Any other date set to my birthDate DateTime variable in my class works when I add it as the value in my conn.AddParam, but when I send back 1/1/0001 12:00:00 AM (which was sent by setting it to MinValue) to SQL 2008's Date field, it remains the default which I have set to null in the databse for that field:
conn.AddParam("#birthDate", birthDate);
birthDate is type DateTime. It's set to DateTime.MinValue; I don't see why it wouldn't take this.
I may not be understanding the question, but I believe January 1, 1753 is the earliest date supported by SQL Server.
Source
If you need to go back that far, use DateTime2. It allows you to go back as far as 1/1/0001 http://technet.microsoft.com/en-us/library/bb677335.aspx
Just a guess but it might be caused by a casting issue. Since your birthDate variable has a time component (12:00 AM), SQL might be casting it to a DateTime before its inserted into the Date field. Since 1/1/0001 is an invalid SQL DateTime it might be having problems. Try setting your #birthDate parameter to birthDate.Date instead.
In SQL server 2008 :
Date data type : - will allow you to store only date (YYYY-MM-DD) and as range 0001-01-01 through 9999-12-31.Its accurate to 1 day
Time data type : It stores in the format hh:mm:ss:nnnnnnn , with range 00:00:00.0000000 through 23:59:59:9999999 and is accurate to 100 nanoseconds
DateTime2 : the format is YYYY-MM_DD hh:mm:ss:nnnnnnnm with a range 0001-01-01 00:00:00.0000000 through 999-12-31:59 9999999,accuracy is 100 nano seconds
DateTimeOffset:It includes additional information to track the time zone.The format is YYYY-MM-DD hh:mm:ss[.nnnnnnn][+/-]hh:mm with a range of 0001-01-01 00:00:00.000000 through 9999-12-31 23:59:50.9999999.storage 8 yo 10 bytes.
DateTime is a value type. Therefore if a DateTime variable hasn't been assigned it's value would be the default one which happens to be DateTime.MinValue. That's why when you explicitly set your birthDate to DateTime.MinValue it's treated as it was not assigned at all (e.g. as null) and thus gets replaced by the default value for that parameter in your stored proc.