Set default joda time duration/period format in Grails - grails

When using joda time with Grails you can set the default LocalDate format as they have done here. I want to do the same thing with Duration and Period so I don't have to type something like
durationFormatter.print(exampleObject.myDuration)
every time I want to display a duration or period. I want a call to the toString() method of a Duration / Period object and have it print in the desired format.
I have tried to implement PeriodFormatter in my config file much like they did here, but to no avail. Here is what I have so far in my config file:
jodatime {
format.org.joda.time.LocalDate = "yyyy-MM-dd"
format.org.joda.time.PeriodFormatter = { new format.org.joda.time.PeriodFormatterBuilder()
.appendMonths()
.appendSuffix( " month", " months" )
.appendWeeks()
.appendSuffix( " week", " weeks" )
.appendDays()
.appendSuffix( " day", " days" )
.appendHours()
.appendSuffix( " hour", " hours" )
.toFormatter();
}
}

class
ISOPeriodFormat
field
cStandard
this is default period formatter. This field is private static and haven't setter. But you can change this value using java-reflection API
final Field f = ISOPeriodFormat.class.getDeclaredField("cStandard");
f.setAccessible(true);
f.set(null, yourPeriodFormatter);

Related

Convert month (date) into full month (string)

I have a date field (adate10) called Period with values like 07/02/2018.
I need to convert this into a string like "July 2, 2018."
I can use the code below to produce a string, Period_String, that says "JUL 2, 2018." I can't figure out how to format the month as the full month, e.g., "July." Is the only option to create an if/then statement that says 'if 1 then "January", if 2, then "February"', etc.? Was hoping there was a built in format but can't find it.
* extract each date element, then format.
compute mo = xdate.month(Period).
compute da = xdate.mday(Period).
compute yr = xdate.year(Period).
formats mo (month) da yr (F4.0).
execute.
* concatentate date elements as strings.
string Period_String (a30).
compute Period_String = concat(ltrim(string(mo,month)), " ", ltrim(string(da,F4)), ", ", ltrim(string(yr,F4))).
execute.
see the revised month format (month9 instead of month):
compute Period_String = concat(ltrim(string(mo,month9)), " ", ltrim(string(da,F4)), ", ", ltrim(string(yr,F4))).
EDIT:
using #mirirai's one-liner suggestion + getting only first letter in capitals:
string Period_String(a20).
COMPUTE Period_String = CONCAT(
RTRIM(char.substr(STRING(period,MONTH9),1,1)),
RTRIM(lower(char.substr(STRING(period,MONTH9),2)))," ",
LTRIM(STRING(XDATE.MDAY(Period),F2)), ", ",
LTRIM(STRING(XDATE.YEAR(period),F4))
).

Subtract date in grails filter (le) in filter grails gorm [duplicate]

Is there a way in Groovy to get the duration between two Date objects? The duration format I'm looking for would be something like: 2 days, 10 hours, 30 minutes...
Thanks
TimeCategory has some methods for getting a duration. You could use it like
use(groovy.time.TimeCategory) {
def duration = date1 - date2
print "Days: ${duration.days}, Hours: ${duration.hours}, etc."
}
The use()-Syntax is weird to me.
so I prefer it like this:
def duration = groovy.time.TimeCategory.minus(
new Date(),
new Date(session.creationTime)
);
def values = [
"seconds: " + duration.seconds,
"min: " + duration.minutes,
"hours: " + duration.hours,
"days: " + duration.days,
"ago: " + duration.ago,
];

How to write a script which concatenates namedValues?

I have a google sheet populated by a google form input with 1 column that has a start date, the 2nd has the start time (the time is a text input from a drop down menu in a time format (but it is text) - 09:00 - 09:30 - 10:00 ..etc) I'm trying to join the date and time input to create a calendar event with the end date the same day as the start day and end time 30 minutes after. Any help would be appreciated!
I have searched and found that the text string for time can be converted by removing the ' sign infront of the text time input by using:-
var withoutQuote = e.values[1].substring(1);
My current script for createEvent:-
var options = { description: namedValues.Description[0],
location: namedValues.Location[0],
guests:"info#domain.com"};
var cEvent = CalendarApp.getCalendarsByName("TEST")[0].createEvent(
namedValues.Name[0],
new Date(namedValues.Starts),
new Date(namedValues.Ends),
options)
}
I would like to create new date based on input date (namedValues.Starts) + concatenate start time (namedValues.Stime) and new date based on (namedValues.Starts) + concatenate start time (namedValues.Stime) + 30 minutes
Any help would be appreciated!
Ok, I was able to get the concatenates namedValues part right herewith edit code:-
function createEvent_ (namedValues) {
var options = { description: namedValues.Description[0],
location: namedValues.Location[0],
guests:"johan#inprint.co.za"};
var cEvent = CalendarApp.getCalendarsByName("TEST")[0].createEvent(
namedValues.Name[0],
new Date(namedValues.Starts + " " + namedValues.Stime),
new Date(namedValues.Ends + " " + namedValues.Etime),
options)
}
What I need now is the second part - I would like to create a new end date/time - based on new Date(namedValues.Starts + " " + namedValues.Stime) + 30 minutes

Set custom publish date, but publish now if it's empty

I am trying to make a custom publish date, because the user wants to use that as the publishing date and for sorting. The date will also be displayed on the page.
Here is what I want:
The user can input a date
The date can be empty (meaning it will be published now)
It has to use that date for sorting
The date has to be set to UTC time, so it's equal for everyone in the world
I am desperate and I cannot figure out how to do this.
Here is what I have tried so far: I found a neat little plugin, which displays the user's current UTC time next to the input field, so the person knows their UTC time. I modified that to always enter the current date in the input field:
var timer = setInterval(function () {
var date = $(".custom-date").val();
if (date === "") {
$(".custom-date").focus();
$(".custom-date").click();
$(".custom-date").trigger("click");
//the date has now been set on the input field
} else if (date !== "") {
var newDate = new Date(date);
var stringDate = newDate.getFullYear() + "-" + ('0' + (newDate.getMonth() + 1)).slice(-2) + "-" + ('0' + (newDate.getDate() - 1)).slice(-2) + " " + ('0' + (newDate.getHours() - offset)).slice(-2) + ":" + ('0' + newDate.getMinutes()).slice(-2) + ":" + ('0' + newDate.getSeconds()).slice(-2);
$(".custom-date").val(stringDate);
angular.element(".custom-date").scope().$apply(function () {
angular.element(".custom-date").scope().datetimePickerValue = stringDate;
});
clearInterval(timer);
}
}, 1000);
Yes, this looks like a lot... and no, it does not work. I do the focus/click/trigger on the element, because that will automatically set the time to be the user's local time. I then turn that into UTC time (offset is the UTC time offset). Then I apply the date to the element's scope and the value gets updated both in $scope and in the view (I can actually see it).
However, when I hit save and publish, the date gets reset (it's empty in the database). It's only when I physically click on the input field and select a new date it will actually update it. I like this method, as I am in 100% control of it, so is it possible? It would seem like setting the new date on the scope doesn't trigger the actual "new date has been selected".
Alternatively I have my Razor code here:
//selection is all my elements/nodes
selection.OrderByDescending(x => x.GetProperty("publishDate") != null).ThenByDescending(x => x.GetPropertyValue("publishDate")).Where(x => x.GetPropertyValue<DateTime>("publishDate") < DateTime.UtcNow);
So apparently before the Angular event is triggered, I need to, at least, call these:
$(".custom-date").trigger("click");
$(".custom-date").change();
So I did that right after I set my new date and now it works.

Grails - illegal arguments for java.sql.Date

I'm trying to create an sql.Date by creating a Calendar object on the current date. This is driving me crazy, if i hardcode the date as a string every thing is fine:
def dat = java.sql.Date.valueOf("2011-01-31");
But, if I create the same string in code I'm getting an illegal argument error.
def currentDay = {
def today = Calendar.getInstance();
def dateYear = today.get(Calendar.YEAR);
def dateMonth = today.get(Calendar.MONTH) + 1;
def dateDay =today.get(Calendar.DATE);
def todayDate = (dateYear + "-" + dateMonth + "-" + dateDay);
def todayDateString = todayDate.toString();
def todayDate2 = java.sql.Date.valueOf(todayDateString);
[ today : todayDate2 ]
}
Running this is yielding this stacktrace:
java.lang.IllegalArgumentException
at java.sql.Date.valueOf(Date.java:138)
at java_sql_Date$valueOf.call(Unknown Source)
at samma.TapesController$_closure7.doCall(TapesController.groovy:178)
at samma.TapesController$_closure7.doCall(TapesController.groovy)
at java.lang.Thread.run(Thread.java:619)
I know I'm doing something completely stupid, but I cannot figure out what, nor what a workaround could be.
Thanks
Donald.
Replace all the code above with
def currentDay = {
def todayDate = new java.sql.Date(new Date().time)
todayDate.clearTime()
[today: todayDate]
}
Why are you converting to a string at all? Just make sure your Calendar has the field values that you want, and then call
new java.sql.Date(calendar.getTime().getTime());
Alternatively, given that you just need the millis to be right, I would try to use Joda Time if at all possible - it'll be easier than manipulating a calendar, IMO. You can convert from a Joda Time instant (or whatever) to a long value very easily.
java.sql.Date.valueOf(String date) throws an IllegalArgumentException if the date given is not in the JDBC date escape format (yyyy-mm-dd). The date you are providing has the format yyyy-m-dd, (only one digit month for 1-9) therefore it is invalid.
As a workaround, use SimpleDateFormat to get a two digit month or directly work with dates without intermediate String conversion like Jon Skeet suggests.

Resources