Grails databinding date format - grails

I have a problem within a grails 2.3 application, when it comes to data binding and correct date formats.
I use a datepicker (jQuery ui) that provides a <input type="hidden" /> that holds the selected date in ISO_8601 format. It will post a value like this: 2015-08-14 to the controller. The form itself and the post result is correct.
I use this simplified model:
class Thing {
DateTime lastUpdated
static constraints = {
lastUpdated nullable: true
}
}
when I try to create an entity, I will face this error message:
Invalid format: "2015-08-14" is malformed at "15-08-14"
A first research lead me to this change in the Config.groovy:
jodatime.format.html5 = true
(Link 3 in the list below)
Appying this leads to change. Now the error message is:
Invalid format: "2015-08-14" is too short (flip table)
Another try was to change the databinding.dateFormats to this (also in the Config.groovy):
grails.databinding.dateFormats = [ "yyyy-MM-dd HH:mm:ss.S","yyyy-MM-dd'T'hh:mm:ss'Z'", "yyyy-MM-dd"]
Which has no effect what so ever.
For my understanding a given date format should automatically be marshaled in a dateTime object. What configuration did I miss?
Here are relative question, that sadly did not help me:
bind date to command object in Grails
GORM default Date format when sending date to Grails
Grails unable to unmarshall date/time from JSON back into joda DateTime

You should add next line in config.groovy
jodatime { format.org.joda.time.DateTime = "yyyy-MM-dd" }
But if you don't need time in this field, it's better to use LocalDate instead of DateTime here.
class Thing {
LocalDate lastUpdated;
...
jodatime {
format.org.joda.time.DateTime = "yyyy-MM-dd HH:mm:ss"
format.org.joda.time.LocalDate = "yyyy-MM-dd"
}
So you will use DateTime where you need date with time and LocalDate where date is enough

Related

Groovy joda-time convert time

In my domain I have
Time startTime
Time endTime
In my controller I need to covert the time from the view which is in a format of HH:MM to the acceptable format to submit to the domain. I have installed the plugin Joda-Time but I've come a bit stuck.
def startTime = params.startTime
def fmt_in = DateTimeFormat.forPattern("HH:mm:ss")
def fmt_out = ISODateTimeFormat.dateTime()
println fmt_out.print(fmt_in.parseDateTime(startTime))
sorry, newbie to groovy grails
After parsing for DateTime, you need to transform it to the desired type. For date and time without considering timezone I suggest you to use LocalDateTime and LocalTime.
def formatter = DateTimeFormat.forPattern("HH:mm:ss")
LocalTime time = formatter.parseLocalDateTime(params.startTime).toLocalTime()

set data type when exporting to excel

I'm using Grails 1.3.4 with the export 0.9.5 plug in.
I have a formatter that I use that sets the date format to 'YYYY-MM-DD' when exporting to excel. But this doesn't change the data type. The date is exported to Excel as a string/general data type.
def dateFormat = { domain, value ->
if(value instanceof Date){
return new java.text.SimpleDateFormat("yyyy-MM-dd").format(value)
}
return value
}
Map formatters = [ecd:dateFormat, completed:dateFormat, dateCreated:dateFormat, approvedDate:dateFormat, dpaECD:dateFormat]
exportService.export(params.format, response.outputStream,exportList, jobService.parseColNames(columns), labels, formatters, null)
Is there a way to export data and set the datatype of a column in excel so the user doesn't have to manually set the cell/column formatting to 'Date' every time after exporting?
Are you sure you want to use that plugin? It didn't work so well to me.
I've been using the JXL plugin for Grails for a while and it works perfectly.
It even has an option to write the Excel file to the response, so that the user can directly download the file using my REST service.
The link is: http://grails.org/plugin/jxl
Here is an example of how simple it is to create workbooks:
new ExcelBuilder().workbook('/path/to/test.xls') {
sheet('SheetName') {
cell(0,0,'Current Date')
cell(0,1,new Date())
}
}
Note that the cell() method has 3 parameters: column, row and value. This third parameter can be a number, string or date, and it formats it perfectly.
You can find more information here.

Grails intercept form submit to modify params

Why do I need this:
I am working in a project which allows user to choose date in Nepali Bikram Sambat Date format (which is incompatible with Java and SQL's "DATE"). I did it by modifying org.codehaus.groovy.grails.plugins.web.taglib.FormTagLib class's datePicker tagLibrary. And modifying the scaffolding template list.gsp.
My problem :
When user chooses Nepali date from browser and submits the form, I want to read the [day, month, year] and convert it into Java Date object and save into database. (The date will be converted back to Nepali Bikram Sambat when it will be displayed into view).
I tried to print the params in the controller but all the params are already mapped/wrapped into corresponding objects - along with my Nepali Date. So I get sysout of Java's Date from code below :
println params.date
I am wondering how can I intercept the form submit request and modify the date params into English date. I see one solution - using JavaScript ( and rewrite my conversion code into JavaScript) before form submit to convert the params. And just wanted to confirm is there a easy way - like interceptor/filter etc.
Well, assuming you are using input fields with the standard grails datepicker, you should have in your params map the fields being passed, just with a different name. Write a "println params" in your action receiving the request and look for the names of the fields of the datepicker. It was supposed to bring you something like (name of the datepicker field, say * + _year, for year, * + _month for month and so on).
You can create a CustomEditorRegistrar that changes the format from your date before it's wrapped into objects. Like this:
public class CustomDateEditorRegister implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry registry) {
String dateFormat = 'dd/MM/yyyy'
registry.registerCustomEditor(Date, new CustomDateEditor(new SimpleDateFormat(dateFormat), true))
}
}
And your Date editor could be something like:
class CustomSimpleDateEditor extends CustomDateEditor {
public CustomSimpleDateEditor(SimpleDateFormat formatter, boolean allowEmpty) {
super(formatter, allowEmpty);
}
public String getAsText() {
Date date = (Date)getValue();
try {
String dateText = new SimpleDateFormat("dd/MM/yyyy").parse(date);
return dateText;
}
catch(Exception e) {
e.printStackTrace();
return "";
}
}
}
Your params.date will be converted before it's passed to objects and saved to the db. Anyway, here's a good link explaining it.
Hope it helps!

How change joda--time default DateTime format in Grails

I am using Grails 2.0.3 (groovy 1.8.6) with joda-time:1.3.1 and joda-time-templates plugins.
Everything works perfectly but I would like to change displayed format for date and time.
How can I do that? Every domain is scaffolded so I do not have access to any view to render it manually.
My domain
import org.joda.time.*
import org.joda.time.contrib.hibernate.*
class Game {
Team host
Team guest
String location
DateTime date
static mapping = {
date type: PersistentDateTimeTZ, {
column name: "date_timestamp"
column name: "date_zone"
}
}
}
rendered date
Date 5/24/12 5:53 PM
I would like to get it as
Date 5 may 2012 17:53 PM
Is there any way to translate name of month
define this in config.groovy
jodatime { format.org.joda.time.DateTime = "dd MMM YYYY HH:mm a" }
and that should take care of it.

Saving and Querying a Date in GORM Grails

I have a database table TableA, which has a column 'theDate' for which the datatype in the database is DATE.
When I save a java.util.Date to 'theDate' through GORM it appears to save just the date value when I look at the data in the table by just executing select * from TableA.
However, when I run a query such as:
select * from TableA where theDate = :myDate
No results are found, but if I run something like;
select * from TableA where theDate <= :myDate
I do get results.
So it's like the Time is relevant.
My question is how do I save a Date and query for a Date ignoring the Time completely and just matching on an exact Date only?
Thanks.
note: I have also tried using sql.Date and util.Calendar but to no success.
clearTime()
You can use clearTime() before saving and before comparing to zero out the time fields:
// zero the time when saving
new MyDomain(theDate: new Date().clearTime()).save()
// zero the target time before comparing
def now = new Date().clearTime()
MyDomain.findAll('SELECT * FROM MyDomain WHERE theDate = :myDate', [myDate: now])
joda-time plugin
An alternative would be to install the joda-time plugin and use the LocalDate type (which only holds date information, no times) instead of Date. For what it's worth, I don't think I've worked on a project with dates without using the Joda plugin. It's completely worth it.
If you have date saved without clearing you could retrieve it using range, as Jordan H. wrote but in more simple way.
def getResults(Date date) {
def from = date.clearTime()
def to = from + 1
def results = MyDomain.findAll("from MyDomain where dateCreated between :start and :stop" ,[start:from,stop:to])
}
Your question may be a duplicate. See Convert datetime in to date. But if anyone has more recent information, that would be great.
If that doesn't help, you can hack it the way I might, with a BETWEEN restriction, e.g.
def today = new Date()
def ymdFmt = new java.text.SimpleDateFormat("yyyy-MM-dd")
def dateYmd = ymdFmt.format(today)
def dateTimeFormat = new java.text.SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
def startDate = dateTimeFormat.parse("${dateYmd} 00:00:00");
def endDate = dateTimeFormat.parse("${dateYmd} 23:59:59");
MyDomain.findAll("from MyDomain where dateCreated between ? and ?", [startDate, endDate])
It's definitely not pretty, but it may get you where you're going.
I figured it out.
I used DateGroovyMethods.clearTime to clear the time value before saving.
You can use the DB type date not datetime , in the filed type

Resources