This question already has answers here:
Java Date - Insert into database
(10 answers)
Closed 6 years ago.
How can I best store a String with format yyyy-MM-dd (without time declaration) in SQL database (postgres)?
I later want to use that String always as Date type. I also want to execute query against the database to give me records that are before or after that Date.
Should I store it as a String or as a Date type in DB?
If I store it as a Date, in database I see yyyy-MM-dd HH:mm:ss. How could I prevent the time declaration?
If you do not want to store a time component, then use the DATE data type. It does not have a time or a time zone component, so is useful for dates of birth, dates of employment start/end, and other data for which the time is not relevant.
http://www.postgresql.org/docs/9.3/static/datatype-datetime.html
The display format is a matter for the application -- just use the correct data type. YYYY-MM-DD is documented as the best format for suplying dates, though.
Always recommended one is Date with time-stamp. If you don't need then while storing store it as 00:00:00.(Use Sql Date for date without time-stamp.)
Use business logical in order to truncate the time and the format you required. Service layer you can play with date and in most of DB its better to store Date with timestamp.
Related
This question already has answers here:
How to get date datatype from sql database to java?
(2 answers)
Closed 7 years ago.
I have a DateTime which I received as JSON via a REST Servce of the Couchbase's Sync Gateway:
"2015-05-20T13:32:25.9999478-07:00"
I do not have the access to the Sync Gateway's configs.
I did no find any documentation about the default format of Sync Gateway's dateTime format.
I do not understand what the .9999478-07:00" means.
Is there a way to guess that somehow?
That is the ISO standard notation for date time
YYYY-MM-DD,
then a 'T' for time, HH:MI:SS.S* (fractional seconds),
+/- time zone (there are half our zones!)
Time and also time zone optional.
Look in the wikipedia or javadoc.
When no time zone the date time representation can be sorted alphabetical to be naturally ordered.
Is it possible to save date values in the database of this format dd/MM/yy in Grails? I know I can customized the format in the views but I need the values to be returned as json and also return the values of dates in json in that format. Any suggestion will be appreciated.
Try this on your presentation layer, don't save time in that format in database. use following code to format the time according to your need.
Date date = new Date( );
SimpleDateFormat simpleFormat = new SimpleDateFormat ("dd/MM/yy");
System.out.println("Date: " + simpleFormat .format(date));
But if you want to save the data in this format in databse, then remember it returns a string and you will have to save the date in String format in database. Which I wouldn't recommend because of many reason.
You should not store the date as a formatted string because you lose the ability to do many things with that field, such as sort it or compare it. Always use the database's native date format for storage. If you want to change the format there are many places to do it, including the presentation layer (as others have suggested) and the database query layer. Format the date in the query if you want to do minimal processing in Java/Javascript.
Agreed with others you should not save in the database in String format. To format a Date using Groovy you can use the String.format() method.
String.format('%tY-%<tm-%<td', new Date())
See the Groovy dates documentation for further examples.
I have a JSON file which has 40k documents, each document contains a date field. I need to query within Java with dates to retrieve data, so I stored the date in numberLong format.
Date dt = new Date();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
dt = format.parse(nextLine[j]);
document.put(ColumnNameAsKey[j], dt.getTime());
where the above code is done in for loop in an API to store data to mongo.
But after entering all those data, and then when I queried numberlong changes automatically for the same date, so that I am unable to retrieve all data for the required date. My query to retrieve is
querygraph.put("Complaint Date (MM/DD/YYYY)", new
BasicDBObject("$gte",startdate.getTime()).append("$lte",EndDate.getTime()));
for eg : if the date 08/01/2012 contains large number of document, the correct numberlong for the date 08/01/2012 is replaced in the date field in mongo. this will continue, but aftr some number of documents, the numberlong keep on changing.. ie if NumberLong is 134353300000 for the date 08/01/2012, then after 6 or more document the numberlong will be different from the former one.. causing unable to retrieve exact data for the date 08/01/2012..
What makes the difference here?
I think see your problem, because you store the millisecond precision of time you are actually getting problems with the long ints representing parts of a day making it impossible to query past, say, midnight.
This is because MongoDB querying does not take this sort of contextual querying into account.
First off a hint, don't store as number longs, store as the $date BSON type using only the lines:
Date dt = new Date();
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
You will get more functionality from using the specified BSON date type and the querying ability is the same across the board.
You have the right idea about querying your records:
querygraph.put("Complaint Date (MM/DD/YYYY)", new
BasicDBObject("$gte",startdate.getTime()).append("$lte",EndDate.getTime()));
But I got a feeling you are doing something wrong. When you create the start date and the end date you are actually looking for the 00:00:00 time of the start date and the 23:59:59 time of the end date. This is due to your getTime() function, UNIX timestamp does not return partial times as such it will just return the default which is effectively now().
One way around that could make your life easier is to standardise times on this field so that you specify a time of 00:00:00 for all dates allowing you pick out ranges correctly.
I have a database which is going to have UMT timestamps in standard sql format. How can I pull that data and set a java date object with it?
As far as I know mysql is yyyy-mm-dd hh:mm:ss As for java, the date / time stuff has always eluded me.
If anyone knows of a good library for this I am open to suggestions.
Why don't directly read it as Date
Date date = resultSet.getTimestamp("date_field");
Timestamp timestamp = resultSet.getTimestamp("date_time_field");
See
ResultSet.getTimeStamp()
A Timestamp is a subclass of a Date, which means it is usable everywhere where a Date is. The only difference is, Timestamp is more precise (due to the SQL specification) than Date is.
Just use:
Timestamp t = resultSet.getTimestamp("columnname");
Date d = t;
That having said, there are some benefits of converting the JDBC returned timestamp into a proper Date value, omitting nanoseconds. When you compare a Timestamp and a Date in some remote part of your app, the Timestamp and the Date won't be equal, even though they seem to be "rougly" the same time value. So if this could cause problem, create a new Date instance using only the .getTime() value returned by Timestamp)
More on this in my blog: Timestamp and Date equality when using Hibernate
(even though the blog entry is about Hibernate, it applies to your case as well)
I have created a database with a String column which contains dates in String format (dd/mm/yyyy). I want to fetch the data from that table which is between two given dates, but when I tried with the below query, I found that it doesn't make any difference what month and year I have selected; it compares the "dd" field only from "dd/mm/yy".
The below query will display all the data which is between day 14 to 25 from every month and year. I want data between the given date, month, and year.
Select * from RunningLog
where CAST(RunDate AS DATETIME) between CAST('14/04/2011' AS DATETIME) and
CAST('25/04/2011' AS DATETIME)
Please see my answer here about how dates are (or are not) stored in sqlite3. Sqlite doesn't have a date field, so its actually stored as a string. Trying to sort / filter on this will prove to be difficult. Instead use an int field, and store the time in milliseconds.
I prefer INTEGER / Unix time storage, then use the built in date and time functions to format when pulling from DB.
Example:
long millis = Calendar.getTimeInMillis();
Store millis in the database as an integer. Then, refer to the first link on how to use the date and time functions in sqlite3.
Sqlite3 documentation does not say it can cast a datetime: http://www.sqlite.org/lang_expr.html (refer to Cast expressions numeral). Why don't you do that from Java? I mean, how are you storing the dates in the database? I highly recommend saving a long (Unix time); that way you can easily get a couple of long numbers that represent an exact date and time and use them to query your table.
Recomendation: Use Datetime fields in the database and JodaTime as a Time library.
Is quite easy to parse the datetime into a DateTime object and then you have many useful methods to compare and work with dates.
Also, your SQL queries will be better.
You can compute the number of seconds between two dates. Here is an example:
SELECT strftime('%s','now') - strftime('%s','2004-01-01 02:34:56');
Based on the sign of the difference you can say if one date is before another. In your case you have to do two comparisons, so you have to verify the sign of two differences. Here you can find other examples, maybe they give you other ideas (http://www.sqlite.org/cvstrac/wiki?p=DateAndTimeFunctions).