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.
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 add a day to my date:
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate);
However, this keeps returning an obscure object {_i: "2017-12-20T21:06:21+00:00", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array(7), …}
fiddle:
http://jsfiddle.net/rLjQx/4982/
Does anyone know what I might be doing wrong?
You are logging a moment object. As the Internal Properties guide states:
To print out the value of a Moment, use .format(), .toString() or .toISOString().
let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
Please note that you can get the current date using moment() (no need to use new Date()) or moment.utc().
I will go with this one, simple works for me and I don't think you need other function to only add day in moment.
var yourPreviousDate = new Date();
var yourExpectedDate = moment(yourPreviousDate).add(1, 'd')._d;
The add method modifies the moment object. So when you log it, you're not getting an obscure object, you're getting the moment object you're working with. Are you expecting a formatted date? Then use format or some other method.
I agree with other answers just providing shortcut and different ways
You can do the format at the same time
moment().add(1,'d').format('YYYY-MM-DD');
or you can just format any date or date object
moment(result.StartDate).format('YYYY-MM-DD');
def cleantz( time : String ) : String = {
var sign_builder= new StringBuilder ++= time
println(sign_builder)
var clean_sign = ""
if (sign_builder.charAt(23).toString == "-"){
clean_sign= sign_builder.replace(23,24,"-").toString()
}else{
clean_sign = sign_builder.replace(23,24,"+").toString()
}
var time_builder= new StringBuilder ++= clean_sign
if (time_builder.charAt(26).toString == ":"){
val cleanz = time_builder.deleteCharAt(26)
cleanz.toString()
}else{
time_builder.toString()
}
}
val start = ISO8601Format.parse(cleantz(01/01/2017 6:54 PM))
I get this error:
java.lang.StringIndexOutOfBoundsException: String index out of range: 23
java.time
For the sake of completeness I should like to contribute the modern answer. It’s quite simple and straightforward.
I am sorry that I can neither write Scala code nor test it on my computer. I have to trust you to translate from Java.
private static DateTimeFormatter inputFormatter
= DateTimeFormatter.ofPattern("MM/dd/yyyy h:mm a", Locale.US);
public static String cleantz(String time) {
return LocalDateTime.parse(time, inputFormatter)
.atOffset(ZoneOffset.ofHours(1))
.toString();
}
Now cleantz("01/01/2017 6:54 PM") returns 2017-01-01T18:54+01:00, which is in ISO 8601 format. I would immediately suppose that you’re set. If for some reason you want or need the seconds too, replace .toString(); with:
.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME);
Now the result is 2017-01-01T18:54:00+01:00. In both cases the milliseconds would have been printed if there were any.
Since AM and PM are hardly used in other languages than English, I suggest you give an English-speaking locale to DateTimeFormatter.ofPattern() (in my example I used Locale.US). Failing to provide a locale will cause the code to fail on many computers with non-English language settings.
Why java.time?
SimpleDateFormat and friends are long outdated and notoriously troublesome. I cannot count the questions asked on Stack Overflow because SimpleDateFormat behaved differently from what every sane programmer would have expected, or offered no help to debug the simple errors we all make from time to time.
Joda-Time was good for a long time. Today the Joda-Time homepage says:
Note that Joda-Time is considered to be a largely “finished” project.
No major enhancements are planned. If using Java SE 8, please migrate
to java.time (JSR-310).
java.time is the modern Java date & time API built using the experience from Joda-Time and under the same lead developer, Stephen Colebourne. It is built into Java 8 and later, and a backport exists for Java 6 and 7, so you can use the same classes there too.
Assuming that your input string is 01/01/2017 6:54 PM: it has 18 characters. When you call charAt(23), it tries to get the character at position 23, which doesn't exist: the string has positions from zero (the first 0) to 17 (the M). If you try to get a position greater than that, it throws a StringIndexOutOfBoundsException.
But you don't need to do all this string manipulation. If you have a string that represents a date in some format, and want to convert it to another format, all you need is:
parse the original string to a date
format this date to another format
So you need 2 different Joda formatter's (one for each step). But there's one additional detail.
The input has a date (01/01/2017) and a time (6:54 PM), and the output has a date (2017-01-01), a time (18:54:00.000) and the UTC offset (+0100). So you'll have an additional step:
parse the original string to a date
add the +0100 offset to the parsed date
format this date to another format
With Joda-Time, this can be achieved with the following code:
import org.joda.time.DateTimeZone
import org.joda.time.LocalDateTime
import org.joda.time.format.DateTimeFormat
import org.joda.time.format.ISODateTimeFormat
val fmt = DateTimeFormat.forPattern("dd/MM/yyyy h:mm a")
// parse the date
val localDate = LocalDateTime.parse("01/01/2017 6:54 PM", fmt)
// add the +01:00 offset
val dt = localDate.toDateTime(DateTimeZone.forOffsetHours(1))
// format to ISO8601
print(ISODateTimeFormat.dateTime().print(dt))
The output will be:
2017-01-01T18:54:00.000+01:00
Note that the offset is printed as +01:00. If you want exactly +0100 (without the :), you'll need to create another formatter:
val formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
println(formatter.print(dt))
The output will be:
2017-01-01T18:54:00.000+0100
This is the code I used to achieve the same result. The error occurred because I was trying to parse the wrong date format.
val inputForm = new SimpleDateFormat("MM/dd/yyyy h:mm a")
val outputForm = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
val dateFormat1 = start_iso
val dateFormat2 = stop_iso
val start = outputForm.format(inputForm.parse(start_iso))
val stop = outputForm.format(inputForm.parse(stop_iso))
println(start)
println(stop)
I have to copy the data from one collection to another collection based on a date. Here date is calculated as yesterday date dynamically and working properly.
If i pass the dynamic date value as /$yesterday/ to mongo find method, Its getting failed.
Assume data_timestamp format is 2013-08-20 17:04:40.633 and trying to get the result by like query.
Sample JS Code:
db=db.getSiblingDB('masterdb')
$today = new Date();
$yesterday = new Date($today);
$yesterday.setDate($today.getDate() - 1);
var $dd = $yesterday.getDate();
var $mm = $yesterday.getMonth()+1;
var $yyyy = $yesterday.getFullYear();
if($dd<10){$dd='0'+dd} if($mm<10){$mm='0'+$mm} $yesterday = $yyyy+'-'+$mm+'-'+$dd;
db.mastercollection.find( { "data_timestamp": /$yesterday/ } ).forEach( function(x){db.newcollection.insert(x)} );
Is any other way to pass dynamic value without using '$' symbol?
Please share your valuable comments
Thanks in advance...
Ramesh Kasi
The way you're doing your query now, I'm pretty sure that /$yesterday/ is being interpreted as a regular expression matching strings starting with "yesterday". A better approach would be to use the $regex operator so that you can pass in a javascript variable that holds the regular expression you hope to match.
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.