This sounds a painfully simple question but I'm having the hardest time finding how I can grab all the entries that were updated today.
def today = new Date()
def q = "from UserMapping as u where u.updateTime like :today"
def updated = UserMapping.findAll(q, [today: today])
java.lang.String cannot be cast to java.util.Date. Stacktrace follows:
I've tried about 10 other ways but I can't figure it out.
I solved it using:
def today = new Date().clearTime()
def updated = UserMapping.findAllByUpdateTimeGreaterThanEquals(today)
If anyone has a more elegant method, please post it.
Related
I have following mapping defined
def e_environments = [["demo1#mystuff.com":"file1"], ["demo2#mystuff.com":"file1"], ["insurance1#mystuff.com":"file2"], ["insurance2#mystuff.com":"file2"]]
Is there a way to replace URL's with same file name from a variable value. For example
def demo_env = ["demo1#mystuff.com","demo2#mystuff.com"]
def insurance_env= ["insurance1#mystuff.com","insurance2#mystuff.com"]
def def e_environments = [[${demo_env}:"file1"], [${insurance_env}:"file2"]]
I hope you must have made some efforts from your side before asking here.
Here is something for you to work upon,
def e_environments = [ "demo1#mystuff.com":"file1", "demo2#mystuff.com":"file1" , "insurance1#mystuff.com":"file2" ,"insurance2#mystuff.com":"file2" ]
def temp = []
e_environments.keySet().each{
temp.add(e_environments[it])
}
temp.unique().each{ val ->
println e_environments.findAll{it.value==val}
}
Got all keys from Map
Created a unique list of it
And a little bit of groovy magic for you to fix and figure it out.
I have a selection field and this function for list items in field by dynamically.
def get_years(self):
year_list = []
year = date.today().year+1
lastyear = date.today().year - 20
for i in range(int(lastyear),int(year)):
year_list.append((i, str(i)))
return year_list
this is the field,
year = fields.Selection(get_years, string='Yıl', default=get_current_year, restore="True")
and when I save the form, this field becomes unknown. I found what is the problem but I don't know the solution. Problem is compute function, when i write items like [(1997,1997),(2016,2016),(2017,2017)] it is working but i don't want to write hard code. How can i solve this problem? Thank you.
I found the solution, i don't need to create a new method and can use like;
year = fields.Selection([(num, str(num)) for num in range(1900, (datetime.now().year)+1 )],string='Year', default=datetime.now().year)
Thanks.
I'm struggling a little creating a timestamp in a format that I want using a scripted pipeline in Jenkins. Here's my code from the pipeline:
def cal = Calendar.instance
def dateFormat = 'YYYYMMDD-hhmmss'
def timeZone = TimeZone.getTimeZone('CST')
def timeStamp = cal.time.format(dateFormat,timeZone)
println "Timestamp is: ${timeStamp}"
env.BUILD_TIMESTAMP = timeStamp
When I run via Jenkins, I get the following:
org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: unclassified field java.util.GregorianCalendar time
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.unclassifiedField(SandboxInterceptor.java:387)
at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:371)
I've seen mention of similar issues with different fields online, but the workaround of adding it to scriptapproval.xml (and restarting Jenkins) doesn't seem to be working.
Anyone have a method of generating a timestamp in a format similar to what I'm trying to do?
I figured out a way around it. I was accessing the field time directly. If I change the call from cal.time to cal.getTime() Jenkins behaves a lot better. I consolidated it into a one-liner, but the functionality's the same:
def timeStamp = Calendar.getInstance().getTime().format('YYYYMMdd-hhmmss',TimeZone.getTimeZone('CST'))
Thanks to those that had a look.
Or use Date() formatted with SimpleDateFormat():
import java.text.SimpleDateFormat
def dateFormat = new SimpleDateFormat("yyyyMMddHHmmss")
def date = new Date()
def timestamp = dateFormat.format(date)
Lets say, i have a "Book" class with field "availableOn"(as shown below).
class Book {
String availableOn;
}
The fields holds values
"All days" or
String representation of a date. For example "13/06/2012"
How can i get all Books that are available within next two days? The below code would throw an exception ("java.util.Date cannot be cast to java.lang.String")
def books = c.list(){
between('availableOn', new Date(), new Date() + 2)
}
PS : Am working on a legacy DB, and so am not suppose to change the schema :(
I think there are 2 problems which the between statement will have:
availableOn cannot be converted to a Date for comparison when its value is All days
Even when availableOn has a date value in it, it is not converted to a Date for the comparison
I'd try something along the lines of this:
def now = new Date()
def books = Book.findAllByAvailableNotEqual("All days").findAll { book ->
Date.parse('dd/MM/yyyy', book.availableOn) > now && Date.parse('dd/MM/yyyy', book.availableOn) < now+2
}
Clearly, this can be done in a nicer way (adding some methods to the domain class for example), but this should illustrate my idea...
I don't have a criteria based solution, but you can try something like this:
Book.executeQuery(
"select book from Book book where book.availableOn = :availableOn or to_date(book.availableOn, :format) between (:startDate, :endDate) ",
[availableOn:"All days", format: "dd/MM/yyyy", startDate: startDate, endDate:endDate])
The problem with my solution is that this query becomes DB dependent. to_date is an Oracle function. You may want to alter this to fit your database
You can use format on a date to get desired string format of it.
new Date().format('dd/MM/yyyy')
And your criteria would get modified to
def books = c.list(){
def todayDateStr = new Date().format('dd/MM/yyyy')
def twoDaysAfterTodayDateStr = (new Date()+2).format('dd/MM/yyyy')
or{
between('availableOn', todayDateStr, twoDaysAfterTodayDateStr)
eq 'availableOn', 'All Days'
}
}
Test if the str comparison works, otherwise other ways has to be used. Sending from phone, excuse my typos.
UPDATE
The above would fail in peculiar cases when dates are like "01/01/2013" and "07/11/2011".
Alternatively, you can use sqlRestriction but in that case it gets tightly coupled with the underlying database. Something like this can be done if Oracle db is used:
def books = c.list(){
def todayDateStr = new Date().format('dd/MM/yyyy')
def twoDaysAfterTodayDateStr = (new Date()+2).format('dd/MM/yyyy')
or{
sqlRestriction "to_date(available_on, 'DD/MM/YYYY') between to_date(todayDateStr, 'DD/MM/YYYY') and to_date(twoDaysAfterTodayDateStr, 'DD/MM/YYYY')"
eq 'availableOn', 'All Days'
}
}
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