Problem when substract minutes to a date

Hi,
I have a problem when I try to substract minutes to a date. I tryied the code below in the static/console and it works fine:

var startTimeValue = new Date.now(); 
var currentTime = new Date.now(); 
currentTime.setMilliseconds("0");
currentTime.setSeconds("0");
currentTime.setMinutes("0");
startTimeValue.setMilliseconds("0");
startTimeValue.setSeconds("0");
startTimeValue.setMinutes("0");
var startMinutes = startTimeValue.getMinutes()-10080;
startTimeValue.setMinutes(startMinutes);
var startFilter = startTimeValue.toISOString(), endFilter = currentTime.toISOString();

The logic is to have, if it executes now, for startFilter “2019-05-23T15:00:00.000+02:00” and endFilter “2019-05-30T15:00:00.000+02:00”.

The script works if I execute it on the console, if I insert this piece of code in a CronJob and launch it I receive the error
wrapped DateTimeException: Invalid value for MinuteOfHour (valid values 0 - 59): -10080

Someone can help me to modify the script so that it works in a CronJob script?

Thanks,
Laura

The error occurs on this operation:
var startMinutes = startTimeValue.getMinutes()-10080;

I solved in this way, instead of

var startMinutes = startTimeValue.getMinutes()-minuteToSub;
startTimeValue.setMinutes(startMinutes);

I use

startTimeValue.addMinutes(-10080); var startFilter = TransformHelper.timeZoneUtcToCetCest(startTimeValue.toISOString(), true).toISOString(), endFilter = TransformHelper.timeZoneUtcToCetCest(currentTime.toISOString(), true).toISOString();

Yes, sounds like you want to add/subtract minutes rather than set the minute value.

I also just wanted to note that the functions that mutate the original date (setMinutes, setSeconds, etc.) have been deprecated in favor of the functions that do not mutate the original date but instead return a copy with changes applied.

For example, your code could look like:

var currentTime = new DateTime.now()
  .withMillisOfSecond(0)
  .withSecondOfMinute(0)
  .withMinuteOfHour(0);

// A copy of `currentTime`, adjusted by -10080 minutes
var startTimeValue = currentTime.plusMinutes(-10080);

// and there are even nice APIs to do these operations :) 
var startTimeValue = currentTime.plusWeeks(-1);

Hope this helps!

1 Like

Also if you want to align date to a particular interval you can do the following

Interval.alignDate(DateTime.now(), Interval.MINUTE).toString()
"2019-05-30T08:25:00.000-07:00"
Interval.alignDate(DateTime.now(), Interval.SECOND).toString()
"2019-05-30T08:25:24.000-07:00"
Interval.alignDate(DateTime.now(), Interval.HOUR).toString()
"2019-05-30T08:00:00.000-07:00"
1 Like