Save date in database in this format dd/MM/yy - java

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.

Related

How to create a new Date object without the year parameter in Java?

I am trying to use new SimpleDateFormat to parse a string in the format dd-MM. Basically, I want to create a date object out of the string and persist in the database.
When I checked the database entry I see that it appends 1970 to the year column. I believe it is the default value of the year provided when it is empty. Is there a way to prevent the year value. I do not want to store information about the year.
My code -
String dateOfBirth = "14-Feb";
dbObject.save(new SimpleDateFormat("dd-MMM").parse(dateOfBirth));
For the sake of simplicity, assume dbObject.save() the method expects a date object to be provided. I do not want to create a date of value - 14-Feb-1970, instead it should be just 14-Feb.
I would strongly suggest you use the java.time.MonthDay class to store your dates. If your database doesn't support storing that, you can just store it as a string, and parse it when you get it out of the database.
Here is how you would parse your date:
MonthDay md = MonthDay.parse("14-Feb", DateTimeFormatter.ofPattern("dd-MMM").withLocale(Locale.US));
You can then store the string returned by .toString into the database (it will be something like --02-14), and the next time you parse it, you don't need a date time formatter:
MonthDay md = MonthDay.parse("--02-14");

Set date format dd/mm/yyyy in SQL table

I want to save the dates in my database in the dd/mm/yyyy format, because I want to import the table that contains them in a JTable (Java SE) and I want to display them in this format. Is it possible to directly save the date on my database in this format or I must do it in another way? My DB is write in SQL and I use MySQL.
Date are dates. It doesn't exists a format for dates.
What you can obtain is a string with a particular format from the date.
Note that the format probably is not dd/mm/yyyy but dd/MM/yyyy because mm is for minutes, not for months.
So basically you have two possibilities:
Save dates as Date and retrieve them as string with the requested format
Convert dates to strings and save them as formatted strings (VARCHAR for example)
To convert a Date to a String in MySql you can use the function DATE_FORMAT
If you like to convert them in java you can use a SimpleDateFormat
There is no possibility to save the date in the specified format but yes you can set the type of that field as String (in MySql varchar) and you can save whatever you want.
You can't do it,
or else you have to use VARCHAR or CHAR, but thats not recommended.
save the date in DATE datatype with format yyyy-mm-dd.
don't mess with it.
When you fetch the records, use DATE_FORMAT function to convert it into your format. (if you use MySQL)
like
SELECT DATE_FORMAT(CURDATE(), '%d-%m-%Y');
in your case
SELECT DATE_FORMAT(< your_date_field >, '%d-%m-%Y');
Use DATE_FORMAT function to change the format of a date in MySQL.
SELECT DATE_FORMAT(CURDATE(),'%d/%m/%Y')
SELECT DATE_FORMAT(column_name,'%d/%m/%Y') # FROM tablename
Refer to documentation for more details.

Store date as yyyy-MM-dd in database without time? [duplicate]

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.

Converting String date to SQL Date

I have a string date in the format DD/MM/YY (16/07/13)
How do I convert this string date to SQL Date format (maintaining the same DD/MM/YY format)
for storing in my Oracle DB.. ??
Use a SimpleDateFormat:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy");
String stringWithDate = "16/07/13";
Date theDate = sdf.parse(stringWithDate);
//store theDate variable in your database...
Note that SimpleDateFormat#parse throws ParseException.
UPDATE: Using Java 8 and LocalDate
LocalDate localDate = LocalDate.from(
DateTimeFormatter.ofPattern("dd/MM/yy")
.parse(fecha));
If you need to pass this to java.sql time objects, you can see this answer on How to get a java.time object from a java.sql.Timestamp without a JDBC 4.2 driver?
I don't know Java and I'm not super familiar with Oracle, but this may help.
In MS SQL Server I've seen all kinds of bad stuff happen when people try to post stuff using specific date formats. Windows date settings can vary so problems are almost guaranteed. From that point of view your
(maintaining the same DD/MM/YY format)
rings alarm bells
I'm yet to have issues as I usually fall back on handling dates in a "standardised" way.
'yyyymmdd'
select CAST('19900506' AS DATETIME)
is very predictable, so if you want predictable you need the oracle equivalent
it also works for date + time
'yyyymmdd hh:mi:ss.mmm'
select CAST('19900506 01:01:01.000' AS DATETIME)
Oracle/PLSQL will have similar functions that work in an controllable way. Use these functions to save values correctly then your data can be reliably output in whatever format you specify at the time of retrieval

What is the efficient way to store date in mongodb.?

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.

Categories

Resources