ASP.Net C# sqlDr.GetValue(a) Date Column Displaying Time too - c#

I tried to use
sqlDr.GetValue(a).ToString()
to display a DATE column from my database which looks like this..(the Date Submitted column)
But the problem is , when i display it using getValue(8).toString(), something like this is displayed..
Thanks for taking your time to read my post , any reply is much appreciated!

The problem is .Net does not have a Date-only primitive type. Therefore the Sql Server Date column type maps to a full DateTime value in .Net, which always includes a time component. If you don't provide a time component, the DateTime struct will have a 0-value time component, which maps to 12:00:00.000 AM.
To get around this, you need to specify the output format for your column, so that it explicitly does not include a time value. You want something like this:
((DateTime)getValue(8)).ToString("d")
However, the exact code you need will vary wildly depending on how your result table is created. If necessary, check the SqlDataReader.GetDataTypeName() function to know what type you're dealing with.

Try using the DateTime.ToShortTimeString Method ():
Console.WriteLine("Short date string: \"{0}\"\n", myDateTime.ToShortDateString());
Output: Short date string: "5/16/2001"

Related

My datagridview binded with MS Access Database displays wrong time format

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

Postgres and c# - DateTime with timezone confusion

Hopefully not a repost of another... a rather simple question, but I think I'm fundamentally confused about how dates/times with timezones are handled between Postgres and c#.
Simple situation, at one point in the program I call DateTime.Now and save to a variable 'now'. This is inserted into a Postgres DB.
cmd.Parameters.AddWithValue("createdat", now);
Great. The column that this is inserted into is of type "timestamp with time zone". When I view the result from something like DataGrip or DBeaver the raw data is exactly what I want (I think).
2021-03-09 15:07:51
Later on I query this table in a rather simple way.
SELECT createdat FROM mytable WHERE mycondition;
I cast it as a c# DateTime type and populate a class with it.
while (reader.Read())
{
myClass.createdAt = (DateTime) reader["createdat"];
}
However, the value is populated as the following:
3/9/2021 10:07:51 AM
Something is not working here. First, if the column in the DB is of timestamp with time zone, where is the time zone information? Second, if the time zone is working, since it is being both populated and queried from the same computer, why is there a discrepancy? Third, and the pressing issue, how do I solve this? Must I explicitly define the time zone? I'm confused as to why it is returning different data... Hopefully, someone can help me out.
I think Dbeaver is changing the time zone, but the data inserted is the same you get on c#. Try to check directly on the server using commandline because maybe dbeaver is changing it to diplay on your pc

Error when adding days to date time in windows form C#

I'm trying to add a renewal system where the user can request for extra days. I've tried to layout a a method which will take the value from a combobox and then add that value in days to the current expiry date.
As can be seen in the screen shot below, I'm having an error when trying to add days onto an existing date. I tried various SqlDbTypes including datetime with no success, maybe this isn't the best way to convert the value to days in terms of SQL?
Any ideas?
DATEADD function takes int as a second parameter. But you try to add your #days parameter with SqlDbType.VarChar type.
Add this parameter value as an SqlDbType.Int and parse your cboDays.Text to integer. For example;
com.Parameters.Add("#days", SqlDbType.Int).Value = Int32.Parse(cboDays.Text);
Also your UserID seems like a numeric column typed since it ends with ID. In this case, VarChar type does not fit for this column.

How to save date only from WPF datepicker using c#?

I wanted to save only date in my database. There is a table which holds dates in database and the column which holds date in type of "Date". Now I want to store date from UI,so I placed WPF DatePicker in UI which allows to select date, but whenever I try to get the data from datepicker it shows the date and time.But I want just the dates to be stored in database.
This is the thing i am doing. It is demo code by the way. Can t upload original code. But this explains the thing. you can see in the message box, it shows 14-10-2015 00:00:00 , i want this zeros to be removed.
The dateTime Picker has a property DisplayDate of Type DateTime. This type contains date and time information.
Just use picker.DisplayDate.Date this returns a DateTime value with the TimeOfDay component set to 00:00.00
Edit
Usually you use an SQL Statement to insert or update values in the database. You should use a parametrized SQL statement with an parameter of type DateTime. The SQL API will take care of the conversion form DateTime (.Net type) to your SQL Date type and strip all time information away. It is a good idea to set the time component to 00:00:00 however to avoid any strange "roundings".
Use ToShortDateString() at the end something like:
var date = datePicker.SelectedDate.Value.Date.ToShortDateString();
MessageBox.Show(date.ToString());

How to save and show elapsed time correctly in datagridview?

I want to save elapsed time in a form into sql table
timer started at form load event and when I click the save button try to save it with
cmd.Parameters.AddWithValue("#duration", textBox3.Text);
in sql table and duration column data saved like this: 00:22
and this absolutely correct for my job
but in datagridview's duration column time showed like this:03/16/2015 12:22pm
Why data in datagridview converted to a full date data instead of original elapsed time?
Well, you didn't give us enough information about your problem but I try my best..
first time it was a float data type but i changed it to nvarchar(255)
for better performance in saving data from c# program
Based on your data (which is 00:22) neither float not nvarchar are seem the right type in your database.
If this is a time interval, time type can be the right type since it is a time of a day. But this time type can't hold bigger than 24:00 values. You will get an error when you try to insert it a bigger value.
If this data can be more bigger than 24:00, I would suggest to parse it to TimeSpan first and save it's Ticks property to bigint typed column in your database.
Looks like your program takes your 00:22 and parse it to DateTime in somehow like DateTime.Parse("00:22"), that's why it generates a today's date with parsed time of day as a DateTime in your datagridview.
By the way, don't use AddWithValue method as a best practice. It may unexpected results sometimes. Use .Add() method overloads to specify your SqlDbType and it's size.
Further reading:
Bad habits to kick : choosing the wrong data type
Can we stop using AddWithValue() already?

Categories

Resources