Here I am using C# and SQL Server 2005. And my problem is, I have table in SQL Server like this
Status ID CreationDate AccNo Amount
1 1001 5/27/2011 7:56:16 PM 100001 686700
1 1002 5/27/2011 7:56:16 PM 10009 40000
when I am retrieving data like select * from tablename, then the date column will be displayed like below
Status ID CreationDate AccNo Amount
1 1001 2011-05-27 19:56:16.110 100001 686700
1 1002 2011-05-27 20:04:20.470 10009 40000
why it is changing like that and, how to change the date format 2011-05-27 19:56:16.110 to 5/27/2011 7:56:16 PM ?
Thanks,
Anuradha J
A datetime column just stores a date and time value. It doesn't apply, nor store, any formatting information.
If you need these datetimes in a particular format for presentation, then you either need to specify that format during SELECT (by using CONVERT with an appropriate format specifier), or better, leave it up to whatever is consuming the results to perform conversion and formatting.
Looking at the format specifiers available for CONVERT, I can't actually see one that allows mm/dd/yyyy hh:mm:ss, so you'd need to perform two conversions, separately, for the date and time components, or as I say, leave it up to your C# code to perform the formatting. Ugly SQL way:
SELECT
Status,
ID,
CONVERT(varchar(16),CreationDate,101) + ' ' +
CONVERT(varchar(16),CreationDate,8) as CreationDate,
AccNo,
Amount
FROM
tablename
answer dont change it the databse, change how you use the data from the database. in your code.
store the retrieved result in a date time object, then you can do anything you want with it.
the data is the same.
or write a stored proc that changes the output to what ever you want.
look up time handeling in TSQL.
In the code behind you can do the following. Bring the date without converting it into string.
DateTime dt;
string Temp1 = "Your Date from database";
if (DateTime.TryParse(Temp1, out dt))
{
// If it is a valid date
string date = dt.ToShortDateString();
string time = dt.ToShortTimeString();
}
Related
I'm trying to save date in yyyy-mm-dd format instead of yyyy-dd-mm format to my database. I added
[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
to the model class, but result didn't change. Date is still yyyy-dd-mm format in database.
Is it necessary doing it with C# code I can't change anything in database table. How can I do that ?
Dates in a (relational) database should be stored in a datetime column, or the equivalent for whatever flavour of database you are using (SQL server documentation). You can choose any format to display the date in your application, that has no bearing on how is stored.
If you're storing the dates in a database in a text format, you are storing up a world of pain that will come back to hurt you later on.
If your column is a string column, you should change it and use a date column as MarcE mentionned.
But, according what I understood, you have a Date column and you want to change the format.
In sql server date is not store like a string.
And the format that you see is associated the collation of your database.
If you want to change it, you should try to change date format of your db.
-- Set date format to day/month/year.
SET DATEFORMAT dmy;
GO
DECLARE #datevar datetime2 = '31/12/2008 09:01:01.1234567';
SELECT #datevar;
GO
-- Result: 2008-12-31 09:01:01.123
SET DATEFORMAT dmy;
GO
DECLARE #datevar datetime2 = '12/31/2008 09:01:01.1234567';
SELECT #datevar;
GO
-- Result: Msg 241: Conversion failed when converting date and/or time -- from
character string.
GO
https://learn.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql?view=sql-server-ver15
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.
this might be a silly question for most of you but i need serious help here,
I've one application in which reporting is needed
I am storing date in SQL Server DB in two columns as 'dd/MMM/yyyy hh:mm:ss tt' format(screen shot attached) the column data type is nvarchar(50). Now whenever i try to select the range from the front end and try to generate the result it is not giving me any records or not proper records, maybe it is not comparing it properly or i am making any mistakes.
Please check this image for DB
Please check the below query where i wanted to generate records from 01 Nov 2016 to 01 DEC 2016, it gave me no records, and i checked that records are present in DB.
select * from WEIGHT where Odate between '01-Nov-2016 00:00:00.000' and '01-Dec-2016 99:99:99.999' or wdatetime between '01-Nov-2016 00:00:00.000' and '01-Dec-2016 99:99:99.999'
following is the front end query code
Public DEFAULT_DATE_FORMAT As String = "dd/MMM/yyyy hh:mm:ss tt"
DAILYREPORTQRY = "select * from WEIGHT where Odate between '" & fromDate.Value.ToString(DEFAULT_REPORT_DATE_FORMAT) & " 00:00:00.000' and '" & toDate.Value.ToString(DEFAULT_REPORT_DATE_FORMAT) & " 99:99:99.999' or wdatetime between '" & fromDate.Value.ToString(DEFAULT_REPORT_DATE_FORMAT) & " 00:00:00.000' and '" & toDate.Value.ToString(DEFAULT_REPORT_DATE_FORMAT) & " 99:99:99.999'"
I've used two Date time pickers to select the date with Custom Format as 'dd/MMM/yyyy' it displays the date in format which I want but if the system date format changes it changes itself, so whats the point of having custom format.
So basically 2 major questions are as follow,
1) How to query through records with date format as in stored in DB
2) How to hard code the format for Front end application to search by the default format without taking care of system date format.
Please advice I've 5000 records which need to be taken care.
Thank you.
For dates you need use correct data-type, in this case DateTime . So you can compare values in the same format, and you handle with datetime in easy way.
To convert that dates (in wrong type) to datetime you can see this link: how to convert nvarchar to datetime datatype
Try use CONVERT, for example try with:
SELECT convert(datetime, '23 Oct 2016 11:02:07:577', 113)
you convert: 23 Oct 2016 11:02:07:577 to 2016-10-23 11:02:07.577
and here you have differents format to convert: how to convert format
Hope this help!
I have a SQLite database where I store the dates as ticks. I am not using the default ISO8601 format. Let's say I have a table defined as follows:
CREATE TABLE TestDate (LastModifiedTime DATETIME)
Using SQL, I wish to insert the current date and time. If I execute any of the below statements, I end up getting the date and time stored as a string and not in ticks.
INSERT INTO TestDate (LastModifiedTime) VALUES(CURRENT_TIMESTAMP)
INSERT INTO TestDate (LastModifiedTime) VALUES(DateTime('now'))
I have looked at the SQLite documenation, but I do not seem to find any option to obtain the current timestamp in ticks.
I can of course define a parameter in C# and store the value as a System.DateTime. This does result in the datetime getting stored to the database in ticks.
What I would like to do is be able to insert and update the current timestamp directly from within the SQL statement. How would I do this?
Edit:
The reason I want the data stored as ticks in the database, is that the dates are stored in the same format as stored by the ADO.Net data provider, and so that when the data is also queried using the ADO.Net provider it is correctly retrieved as a System.DataTime .Net type.
This particular oddity of SQLite caused me much anguish.
Easy way - store and retrieve as regular timestamp
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (datetime('now'));
select datetime(LastModifiedTime), strftime('%s.%f', LastModifiedTime) from TestDate;
Output: 2011-05-10 21:34:46|1305063286.46.000
Painful way - store and retrieve as a UNIX timestamp
You can use strftime to retrieve the value in ticks. Additionally, to store a UNIX timestamp (roughly equivalent to ticks), you can can surround the number of seconds in single-quotes.
insert into TestDate (LastModifiedTime) values ('1305061354');
SQLite will store this internally as some other value that is not a UNIX timestamp. On retrieval, you need to explicitly tell SQLite to retrieve it as a UNIX timestamp.
select datetime(LastModifiedTime, 'unixepoch') FROM TestDate;
To store the current date and time, use strftime('%s', 'now').
insert into TestDate (LastModifiedTime) VALUES (strftime('%s', 'now'));
Full example:
create table TestDate (
LastModifiedTime datetime
);
insert into TestDate (LastModifiedTime) values (strftime('%s', 'now'));
select datetime(LastModifiedTime, 'unixepoch') from TestDate;
When executed by sqlite3, this script with print:
2011-05-10 21:02:34 (or your current time)
After further study of the SQLite documentation and other information found on date number conversions, I have come up with the following formula, which appears to produce correct results:
INSERT INTO TestDate(LastModifiedTime)
VALUES(CAST((((JulianDay('now', 'localtime') - 2440587.5)*86400.0) + 62135596800) * 10000000 AS BIGINT))
Seems like a painful way to produce something that I would expect to be available as a built-in datetime format, especially that the database supports the storing of datetime values in ticks. Hopefully, this becomes useful for others too.
Update:
The above formula is not perfect when it comes to daylight savings. See section Caveats And Bugs in SQLite docs regarding local time calculation.
The following will return the number of milliseconds since the UNIX Epoch:
SELECT (strftime('%s', 'now') - strftime('%S', 'now') + strftime('%f', 'now')) * 1000 AS ticks
It works by grabbing the number of seconds since the Unix Epoch (%s), subtracting the number of seconds in the current time (%S), adding the number of seconds with decimal places (%f), and multiplying the result by 1000 to convert from seconds to milliseconds.
The subtraction and addition are to add precision to the value without skewing the result. As stated in the SQLite Documentation, all uses of 'now' within the same step will return the same value.
I store datetime values in the database as sql float type (Converted from an DateTime.OADate) for a myriad of reasons however in certain circumstances it is nice to get a human readable date/time column back from the database. I have found that I can execute the statement
SELECT CAST (timerecorded_utc as DATETIME) FROM tablename
and it will give me the date time string I am looking for but it seems to be off by exactly 2 days. I realize I can just modify the statement (since in time represented as a double 1 day = 1.0) to be
SELECT CAST (timerecorded_utc-2.0 as DATETIME) FROM tablename
BUT I was wondering if this is consistent AND it seems to me there is some reason for the discrepancy that I am missing.
It's because the epochs the dates use are different.
SQL Server's DATETIME uses 01/01/1900 00:00:00 as the epoch, which you can see by running the following query: SELECT CAST(0 AS DATETIME)
OADate is a bit odd, as it could have an epoch of 30/12/1899 00:00:00 or 31/12/1899 00:00:00 depending on whether you believe the Visual Basic or Excel guys, respectively. It would appear that from your two day difference, the .NET version goes with the 30th.
So, epoch off by two days gives two days difference in the outcome when you convert between the two types of date via a raw number.
Epic Epochs... Here is my TSQL solution in SQL Server using the built in
"DateAdd" function:
Select DateAdd(DAY, cast([ENDING DATE] as decimal(10,0)), '12/30/1899')
from YourTable
In my case I was importing a string saved in Excel via C# Core App and uploading to a SQL Server database so my [Ending Date] is a string which I casted as a decimal with no precision as I only needed the actual date, and not the time of day. As #GregBeech mentioned, your base date might be '12/31/1899'.