sharic19
sharic19

Reputation: 1139

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

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.

Upvotes: 0

Views: 1315

Answers (3)

Ed OConnor-Giles
Ed OConnor-Giles

Reputation: 716

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.

Upvotes: 0

Jim Garrison
Jim Garrison

Reputation: 86754

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.

Upvotes: 1

vicky
vicky

Reputation: 940

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.

Upvotes: 3

Related Questions