How to get current date time format in SQlite? - sqlite

I am using sqlite for local database in mobile and in my database. i want to know that
How to get current date format in SQLITE? I want to get date in the next format: MM/dd/yyyy

To get the current date you can use:
SELECT date('now');
Note: This is NOT a server date, it's the same time you get if you query the date and time directly from your application because SQLITE runs in-process.
It's mostly useful for putting a current time into a table or for some simple calculations if your language's date processing is very poor.
To do the calculations see the SQLITE Documentation
See the docs for formatting too for example:
SELECT strftime('%Y-%m-%d %H:%M:%S', datetime('now'))

According to the SQLite documentation as of this writing (3/30/2020), in the section titled "The DEFAULT clause", it is recommended that a constant value be used instead of a sub-query.
In my experimentation, I also ran into issues with the SQLite CREATE TABLE statement that was generated during model creation by EF Core 3.0 when using SELECT datetime('now'). The SQLite data provider complained of a syntax error when using a SELECT statement within the CREATE table statement. As such, I would recommend using the CURRENT_TIMESTAMP keyword.

for your concrete case, this is what you need:
strftime('%m/%d/%Y',date('now'))

Related

Unparseable Date in Grails Domain Class from SQLite Database

I have a sqlite db (it is the spiceworks db) and I am mapping the tables to grails domain classes. There is a table in particular that is in a datetime format (yyyy-MM-dd HH:mm:ss). An example of such a date in the db for anyone who wants to verify would be: 2015-06-26 15:32:39
I created the domain class and mapped my properties to the columns. Let grails generate the views so that they are default. When I try to get to the index page I get:
URI
/spiceworks/weeklyReportItem
Class
java.text.ParseException
Message
Unparseable date: "2015-06-26 15:32:39" does not match (\p{Nd}++)\Q-\E(\p{Nd}++)\Q-\E(\p{Nd}++)\Q \E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q:\E(\p{Nd}++)\Q.\E(\p{Nd}++)
I've used MSSQL datetimes in the past and have never ran into this issue. In the database, the data type for the problematic column is datetime. Anyone know what's going on?
EDIT: I only have Read permissions on the db and the spiceworks source code isn't open source.
If you look at that regular expression, you'll see it's looking for a ISO8601 timestamp formatted like YYYY-MM-DD HH:mm:SS.SSS - in other words, it needs a decimal seconds, and you're just providing whole seconds.
An easy fix would be to update every existing value in the relevant column by appending '.000' to it, and update the insertion routines to do the same.
If you refer to the sqlite date time functions, there's a %f format specifier for strftime() that can be used to produce fractional seconds that might be helpful if you're building the timestamp directly in an insert query.
In the database, the data type for the problematic column is datetime
Sqlite3 doesn't have a datetime type. The timestamps you're storing are strings. More information.

Issue with date when migrating databases between SQL Server 2008 and 2012 [duplicate]

I have the following piece of inline SQL that I run from a C# windows service:
UPDATE table_name SET
status_cd = '2',
sdate = CAST('03/28/2011 18:03:40' AS DATETIME),
bat_id = '33acff9b-e2b4-410e-baaf-417656e3c255',
cnt = 1,
attempt_date = CAST('03/28/2011 18:03:40' AS DATETIME)
WHERE id = '1855'
When I run this against a SQL Server database from within the application, I get the following error:
System.Data.SqlClient.SqlException: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated.
But if I take the piece of SQL and run it from SQL Management Studio, it will run without issue.
Any ideas what may be causing this issue?
Ambiguous date formats are interpreted according to the language of the login. This works
set dateformat mdy
select CAST('03/28/2011 18:03:40' AS DATETIME)
This doesn't
set dateformat dmy
select CAST('03/28/2011 18:03:40' AS DATETIME)
If you use parameterised queries with the correct datatype you avoid these issues. You can also use the unambiguous "unseparated" format yyyyMMdd hh:mm:ss
But if i take the piece of sql and run it from sql management studio, it will run without issue.
If you are at liberty to, change the service account to your own login, which would inherit your language/regional perferences.
The real crux of the issue is:
I use the following to convert -> date.Value.ToString("MM/dd/yyyy HH:mm:ss")
Please start using parameterized queries so that you won't encounter these issues in the future. It is also more robust, predictable and best practice.
I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.
You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.
To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').
For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)
It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).
I know that this solution is a little different from the OP's case, but as you may have been redirected here from searching on google the title of this question, as I did, maybe you're facing the same problem I had.
Sometimes you get this error because your date time is not valid, i.e. your date (in string format) points to a day which exceeds the number of days of that month!
e.g.: CONVERT(Datetime, '2015-06-31') caused me this error, while I was converting a statement from MySql (which didn't argue! and makes the error really harder to catch) to SQL Server.
You could use next function to initialize your DateTime variable:
DATETIMEFROMPARTS ( year, month, day, hour, minute, seconds, milliseconds )
JAVA8: Use LocalDateTime.now().toString()
i faced this issue where i was using SQL it is different from MYSQL
the solution was puting in this format:
=date('m-d-y h:m:s');
rather than
=date('y-m-d h:m:s');

Different date types manipulation

I am currently stuck with a database issue where I need to manipulate data using my database inserts. I am currently doing a website with C# ASP.NET on Visual studio 2012 and the database I am using is SQL Management 2008.
Firstly, I currently store my System.Date into a string and store it as a nvarchar datatype in my database. If I would like to perhaps get the latest 10 rows from for example, user= 'x', how should I actually go about doing the SELECT statement to only get the data I specified?
And I currently store information like Date Of Birth using the calander Ajax toolkit so the format the dates are saved in is in month/day/year format. The data is stored into my database as a nvarchar as well. If I want to perhaps calculate the age of user='x' how should I calculate it?
I think Jon's comment about storing the data properly as a datetime is spot on:
Why are you storing it as an nvarchar to start with? It's logically a
date/time, not a string - so store it as a date/time. Get rid of the
string part, and all your formatting problems go away too.
Definitely do that if you can.
If, for some reason, you can't change your database structure, you can use a CAST / CONVERT statement in your ORDER BY clause to get what you want:
SELECT TOP 10 *, CAST(yourDateField AS datetime) AS convertedDate
FROM yourTable
WHERE
user='Some user'
ORDER BY CAST(yourDateField AS datetime) DESC
This assumes that your nvarchar data can be properly converted to a datetime (which it should be if you're using the Ajax Control Toolkit calendar extender).

How to add Timestamp value in SQL Server 2005 by using LINQ

My database table have a Timestamp column named as inTime and i am using LINQ for insert, update data in SQL server. Now i want to add the timestamp value in my database but i don't know how to insert?
spaBL.attendance obj = new spaBL.attendance();
obj.FK_employeeId = 1;
obj.inTime =[what to write here??]
inTime is of timestamp type.
Timestamp as in SQL Server Timestamp data type?
;) If I got a cent every time someone did not read the documentation and thought that is a TIME STAMP I would be more rich than bill gates.
Timestamp data time has NO TIME INFORMATION IN IT. It is a running version number, legacy to Sybase SQL Server where SQL Server from Microsoft originated and a totally borked design.
So, no, you CAN NOT SET THAT FIELD, sorry, and it has no usable value except to see whether it changed (then the row was updated).
The documentation is explicitly clear on that, even if some people think reading is maybe a lost art:
http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx
Is a data type that exposes automatically generated, unique binary
numbers within a database. timestamp is generally used as a mechanism
for version-stamping table rows.
There is no way for you to set it. CHange your LINQ setup to not update this column.
Timestamp values are auto generated by the server on inserts. You should insert rows to the table without supplying a value for the timestamp column. Sql server will then generate the value for the column.
Note the columns of type timestamp does NOT contain values that can be parsed as a DateTime. The idea behind timestamp columns is that they can be used to check if a row has been updated between fetching the row and trying to update the row with new values.
You do not provide values for columns with a Timestamp (Rowversion) data type. SQL Server will provide a value for you automatically (and it won't be a datetime value). Therefore you do not need to be concerned with having Linq To SQL insert a Timestamp value for you. In fact, you cannot do it. SQL Server will do it for you. You can however, retrieve the value of a Timestamp column. I believe the corresponding C# type will be System.Data.Linq.Binary.
How to add Timestamp value in SQL database by using LINQ
hope it helps
You cannot update a timestamp. See here. And indeed, as TomTom indicated, it doesn't contain actual time information.

When to use timestamp in sql 2008?

I read several times to convert the timestamp to any readable format but I am not able to decide when to use timestamp datatype or datetime datatype to keep track of records inserted or updated in database in sql server 2008.
timestamp is deprecated, do not use this type. Its role has been replaced by the rowversion type, which is a synonym for timestamp:
The timestamp syntax is deprecated.
This feature will be removed in a
future version of Microsoft SQL
Server. Avoid using this feature in
new development work, and plan to
modify applications that currently use
this feature.
As a type, timestamp (and rowversion) has absolutely no relation to dates, time or anything chronological:
The rowversion data type is just an
incrementing number and does not
preserve a date or a time.
If you need to track the time when a record was inserted or updated, use DATETIME2, at the desired precission.
Read detailed msdn article here
hope this will help you.

Resources