I'm building a criteria to get all yesterday's created records for a certain domain class. Something like
def c = A.createCriteria().list {
eq(<some operation on dateCreated>, <some operation on 'now'>)
}
Thanks in advance
How about
Date today = new Date().clearTime()
Date yesterday = today - 1
def c = A.createCriteria().list {
ge(yesterday)
lt(today)
}
See example criteria here: http://www.grails.org/doc/1.3.7/ref/Domain%20Classes/withCriteria.html
def now = new Date()
between('dateCreated', now-1, now)
will get you everything created within 24h of now. Just use standard Java date manipulation to set your now to midnight.
Related
I'm trying to set the scheduled time when creating an assignment using the Google Classroom API. However, I'm confused about which date format is needed. By the error messages, it seems to accept a string which holds a timestamp and a timezone or Z at the end. Among others, I've tried using System.currentTimeMillis() + "Z", as well as googleDate.getValue() + "Z", googleDate.getValue() since Google Date format seems to be the way to go based on this doc but none of them seem to work.
Any ideas perhaps?
Thank you.
String timezone = timestamp + offset + "";
System.currentTimeMillis()
com.google.api.client.util.DateTime googleDate =
new com.google.api.client.util.DateTime(new java.util.Date());
// Date javaDate = new Date(googleDate.getValue());
CourseWork courseWork = new CourseWork()
.setCourseId(course.getId())
.setTitle("title PUBLISHED 2")
.setDescription("desc")
.setScheduledTime(googleDate.getValue() + "Z")
.setMaxPoints(100.0)
.setDueDate(date)
.setDueTime(timeOfDay)
.setWorkType("ASSIGNMENT")
.setState("PUBLISHED")
;
This is what I get when I manually add a timestamp and turn it into a string.
And this using the Google date instead.
And this with the new Java 8 apis
java.time
I recommend that you use java.time, the modern Java date and time API, for your date and time work. The following code gives the same result as the code from your answer.
LocalDate localDate = LocalDate.now().plusDays(7);
String s = localDate.atStartOfDay(ZoneId.systemDefault())
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
System.out.println(s);
Output in my time zone today:
2021-10-20T00:00:00+02:00
Compared to your own answer you have fewer conversions, and you are freed from writing your own format pattern string since the formatter we need is built in.
This worked:
LocalDate localDate = LocalDate.now().plusDays(7);
java.util.Date date1 = java.util.Date.from(localDate.atStartOfDay()
.atZone(ZoneId.systemDefault())
.toInstant());
String s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX").format(date1);
It seems the imports were using the Google Date class instead of java.util.date.
I am trying to get only the records that was created in the last 5 minutes. I found code that uses between("date", now-1, now)but that doesn't work in my case because the 1 there represents a day and that would mean I would have to write now-0.00347 or now-(5/1440) coz that's what 5 minutes are. The problem with that is that the minus method can apparently not be applied to any datatype except integer. So if anyone knows any better way to get the records created in the last 5 minutes please let me know, I would really appreciate it. Here's what I got:
def activeUsers = User.withCriteria{
def now = new Date()
between("date", now-(5/1440), now
}
Use time categories to make date manipulation easier in Groovy. Such as this:
import groovy.time.*
import org.codehaus.groovy.runtime.TimeCategory
def now = new Date()
def beforeNow = now
use (TimeCategory) {
beforeNow = now - 5.minutes
}
def activeUsers = User.withCriteria{
def now = new Date()
between("date", beforeNow, now)
}
I wanted to perform some benchmarks on some methods of my program so I wrote this little snippet
object ExecutionTime {
private val format = new java.text.SimpleDateFormat("hh:mm:ss")
private var timeList = scala.collection.mutable.MutableList[String]()
def startTimer() : Long = {
val start = System.currentTimeMillis()
start
}
def getExecutionTime(start : Long) {
val executionTime = System.currentTimeMillis() - start
timeList.+=(format.format(new Date(executionTime)))
}
def printResults() {
timeList.mkString(" /n ")
}
}
To test this, I ran this little piece of code :
object Test {
val begin = ExecutionTime.startTimer()
waitFor2Seconds()
ExecutionTime.getExecutionTime(begin)
ExecutionTime.printResults()
}
However, when I run this I am getting a strange output :
01:00:02 // Should be 00:00:02
The result I have is the one that I expect, but with 1 extra hour.
Anyone have an idea on this?
You are constructing a Date object using the time delta between clock measurements. Therefore the SimpleDateFormat is translating the Date to local time when constructing the String.
From the documentation (emphasis mine):
SimpleDateFormat is a concrete class for formatting and parsing dates
in a locale-sensitive manner.
Your constructed Date is epoch + 2 seconds, so your local time must be (epoch + 1 hour + 2 seconds); and that is what the formatter is printing.
To have SimpleDateFormat print without the 1 hour addition you need to set the locale to be GMT and change your hour format to be "HH":
private val format = new java.text.SimpleDateFormat("HH:mm:ss")
format.setTimeZone(java.util.TimeZone.getTimeZone("GMT"))
As another suggestion, look into the Joda time library (here's a scala wrapper). This library can be used to easily subtract and add periods of time and convert to time formats on the fly. I much prefer it to the SimpleDateFormat class.
I have a string which is:
"may 2013"
This refers to the second of May. I am trying to get all instances of PostOrder where the date is the second of May.
What I have tried so far:
def t = new Date(new Integer(sp[1]), new Integer(month), 01)
def results = PostOrder.createCriteria().list() {
ilike('dateCreated', t )
}
Please note I have split the string so sp[1] is 2013 and I have parsed the May so the month variable is not 05.
The above attempt does not work.
The only way I know will work is grabbing all objects and doing a for each on them. parsing the dateCreated to a string then doing a .contains(). But this will get very slow and messy.
First point. According to the documentation, ilike() is a case-insensitive 'like' expression - see SQL LIKE Operator. So, it cannot accept a date. What you need is just eq().
def t = new Date(new Integer(sp[1]), new Integer(month), 1)
def results = PostOrder.createCriteria().list() {
eq('dateCreated', t)
}
Another point. The constructor Date() accepts the year minus 1900 as the first argument. So, you probably need to subtract 1900 from new Integer(sp[1]).
Also, that constructor is deprecated; I would suggest to use GregorianCalendar(new Integer(sp[1]), new Integer(month), 1).time.
well the code I posted below all works perfectly except for a small detail. When I input today date in the field dateEntered, the later rejects it, it validates if the date entered is before todays date, validate if the date falls on a weekends, but it also show an error message when it is todays date. Actually the user should be able to enter Today or after date.
Anyone can tell me where am wrong, already tried every possible ways but still not working even the ( ==) or (===) or (<=) ..nothing
if (event.value!="")
{
var e = util.scand("ddd, dd.mmm.yy", event.value);
var a = (e.getTime()) < (new Date().getTime());
if (a) {
app.alert("The Date cannot be before Today's Date", 1);
event.rc = null;
}
if (e.getDay()==6 || e.getDay()==0) {
app.alert("Cannot take permission on a Weekend!", 2);
event.rc=null;
}
}
I found the solution to my problem, I had to set the hour to 0. Thank to the one who updated this on stackoverflow and sorry forget to retain your name.
if (event.value!="")
{
var e = util.scand("ddd, dd.mmm.yy", event.value);
var b=new Date();
b.setHours(0,0,0,0);
if (e<b) {
app.alert("ERROR: Date cannot be before"+" "+ new Date(b), 5);
event.rc = null;
}
if (e.getDay()==6 || e.getDay()==0) {
app.alert("ALERT: The date you entered ("+event.value+") falls on a WEEKEND!", 3);
event.rc=null;
}
}
This codes also contains a condition of removing one weekend from the dates since the number of leaves allowed to take ranges from 1 to 7 thus only one weekend is remove.