I am creating a desktop application in which I have to query data in SQL Server by providing date and time. Interval is in seconds and every second I run the query again, with the next date.
In this scenario I am getting data from SQL Server and saving date column value on a label, after processing that data, I am running that query again with the date stored on that label and again..
But there's a problem that my SQL Server datetime column is showing as
2016-12-01 18:36:32.000
and when I access that column in my Winform label, it shows as
12/1/2016 6:36 PM
As I have mentioned that I have to consider seconds also, like in SQL Server my query is working fine because I can change minutes easily but when I try to load that same field on label, it is not showing as it is showing in SQL Server.
All I want is to get that column value the same as it is showing in SQL Server.
This is the code I am using to display datetime value on label.
I have selected the column from a simple SQL query like
SELECT [column name]
FROM [table name]
if (dataset.Tables[0].Rows.Count>0)
{
lblDate.Text = dataset.Tables[0].Rows[0]["CHECKTIME"].ToString();
dgv.DataSource = dataset.Tables[0].DefaultView;
}
Screenshots of error
http://imgur.com/a/Qhb5x
http://imgur.com/a/sQtzu
You must strictly separate
the value of a date-time
and
the textual representation
What you see is not the actual value. Especially with date-time values this might get quite tricky: How this is translated into readable text is depending on many factors: System's culture, language, settings...
When you read a date-time from SQL-Server column (DATETIME) into C# variable (DateTime) there exists no readable text. But when you set the lable's Text-property, you probably used .ToString(). At this moment the default settings are used.
However you set the value to the lable's text, you must pass in culture/format info to get this in the way you need it.
Related
I am using C# and MySql. I have a requirement where I need to save DateTime.MaxValue to one of the column.
ADO.NET code gives me below value for DateTime.MaxValue
12/31/9999 11:59:59 PM
When I save this in mysql, I see that the value for that datetime(3) column is saved as:
0000-00-00 00:00:00.000
Sample ADO.NET Code
DateTime time = DateTime.MaxValue;
sqlCommand.Parameters.AddWithValue("Expires", time);
sqlCommand.ExecuteNonQuery();
DataType of the column is datetime(3)
I still cannot figure it out why DateTime.MaxValue is saved as 0000-00-00 00:00:00.000
Any thoughts around this?
A DATETIME column can store values up to '9999-12-31 23:59:59'. DateTime.MaxValue is actually 9999-12-31 23:59:59.9999999. When you try to insert it, the fractional seconds overflow the maximum size of the field.
Normally (in STRICT mode), MySQL Server would issue a datetime field overflow error. But if you're running your server in ANSI mode, the overflow is silently converted to the "invalid" date time value 0000-00-00.
One way to fix this problem is to use STRICT mode in your MySQL Server.
Another way is to specify the column type as DATETIME(6), which allows the fractional seconds to be stored.
A third way is to truncate the fractional seconds from your DateTime objects in C# before inserting them in the database.
Maybe some trigger prevents from saving such a high date to your column?
Have u tried inserting that date from SQL query ?
I did some tests in Oracle DB, and all went smoothly.
It shouldnt be different in mysql ...
I am trying to update a datetime column in a SQL Server 2012 table by using
newItem.DateSaved = DateTime.Today;
I want to save only the Date part of DateTime, but when I am checking in the table I can see that it saves also the time part: 2018-07-27 00:00:00.000 .
How I can make it to store only date part? 2018-07-27 ?
Edit
Because my column is datetime, I see that I can't store only the date part. But how I can show to the user only the date part without time? Here is the select part of the Linq-to-SQL query:
select new { Date = smv.DateSaved.Value.Date }).Distinct();
A datetime column always has a time part - just, in your case it will all be zeros. A datatime is just a number under the hood; it doesn't have any choice about what it has / doesn't have; similarly, it doesn't have any notion of formatting until your code tries to display it, and then it is the dispalying code that chooses the format.
If you don't want a time part, use date instead of datetime for your column.
Change column type in SQL Server from datetime to date (https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017)
If you want to store only the date without time in SQL Server database you can set the column type to date
ALTER TABLE table_name
ALTER COLUMN DateSaved date;
Reference: https://learn.microsoft.com/en-us/sql/t-sql/data-types/date-transact-sql?view=sql-server-2017
If you have a DateTime property in your model and you want to show only the date part just format it in your control in the View. For example:
$"{newItem.DateSaved:yyyy-MM-dd}"
or
newItem.DateSaved.ToString("yyyy-MM-dd")
You can also use "d" or "D" (short and long version) instead of specific format like "yyyy-MM-dd" if you want to have default formatting.
If your view is written in HTML or XAML do it there using the same formatting technique.
It is because your field on the database is DateTime. If you want to store just date, you should have a field with date data type. In this link, you can see the difference between the date data types.
In my database I have used Timestamp in each table to see when data was inserted.
It stores data in byte[] of 8 byte.
Now I want to read that time using C#.
How can I get DateTime object from Timestamp which is byte[]?
SQL Server's TIMESTAMP datatype has nothing to do with a date and time!
It's just a binary representation of a consecutive number - it's only good for making sure a row hasn't change since it's been read.
In never versions of SQL Server, it's being called RowVersion - since that's really what it is. See the MSDN docs on ROWVERSION:
Is a data type that exposes automatically generated, unique binary numbers within a database. rowversion is generally used as a mechanism
for version-stamping table rows. The
rowversion data type is just an incrementing number and does not
preserve a date or a time. To record a date or time, use a datetime2
data type.
So you cannot convert a SQL Server TIMESTAMP to a date/time - it's just not a date/time.
But if you're saying timestamp but really you mean a DATETIME column - then you can use any of those valid date formats described in the CAST and CONVERT topic in the MSDN help. Those are defined and supported "out of the box" by SQL Server. Anything else is not supported, e.g. you have to do a lot of manual casting and concatenating (not recommended).
The format you're looking for looks a bit like the ODBC canonical (style = 121):
DECLARE #today DATETIME = SYSDATETIME()
SELECT CONVERT(VARCHAR(50), #today, 121)
gives:
2011-11-14 10:29:00.470
SQL Server 2012 will finally have a FORMAT function to do custom formatting......
I'm trying to take a 'calendar.selecteddate' from a web form calendar, and pass that date to my sql database date data-type column.
If I select the 5th of January 2014 the entry works fine (2014/05/01). If I select 13th January there is an exception while sending the data to the database. It's converting the date to a yyyy/mm/dd format. Is there a way to change either my sql database data type format - or, a nice bit of code that'll convert it before I pass it to the database?
SqlHandler.SqlQuery(String.Format("INSERT INTO Sessions VALUES ('{0}', '0')"
, Calendar.SelectedDate.ToString()));
thanks as always
In the current project I'm working the initial developer had used ASP.NET Membership to handle the user login validation. As such the LastLoginDate and the LastActivityDate in the aspnet_Membership table are save in UTC format.
Is there anyway to save it in the local time format? Or does anyone know which stored procedure could be modified to compensate for the time difference (by using the DATEADD() method)?
I would caution against changing the data from UTC to local time.
SqlMembershipProvider returns MembershipUser.LastLoginDate and other similar properties in local time: i.e. it converts the database value from UTC to local.
So if you're accessing this data via the Membership API, you don't need to do this.
If you're accessing the data in the database directly, and you really, really want SQL Server to return it in local time, why not just convert it when you're reading from the database.
For example, you could create a VIEW on the aspnet_Membership table something like:
SELECT
...
LastLoginDate + GETDATE() - GETUTCDATE() AS LastLoginDateLocal
...
FROM aspnet_Membership
Note that by doing the conversion in SQL Server, you'll be getting the local time of the SQL Server, which may not be the same as the local time on the machine hosting your application.
UPDATE
From comments:
I want to know why #Leo approach didn't work.
#Leo suggested modifying the aspnet_Membership_UpdateUserInfo SP; you need to modify all SPs that update the columns you're interested in. For example, LastLoginDate is also updated by aspnet_Membership_UpdateUser.
Also, if you follow this approach, the time returned in MembershipUser.LastLoginDate property will be incorrect, since the SqlMembershipProvider code assumes the database value is in UTC. To correct this problem, you would need to modify all the Membership SPs that SELECT this column, to convert back to UTC. E.g. aspnet_Membership_GetAllUsers, aspnet_Membership_FindUsersByEmail, aspnet_Membership_FindUsersByName, ...
Note also that converting between UTC and local in SQL Server as above will sometimes give incorrect values (+/- 1h) due to DST (e.g. the difference GETDATE() - GETUTCDATE() is calculated during a period when DST is in operation, but the user last logged in before DST started).
Another reason why it's better to leave the database value in UTC, and do any conversion in your application.
aspnet_Membership_UpdateUserInfo is the Sp which update the LastLoginDate. You can modify this SP and cast the data format according to your requirement.