Manipulation of date in Groovy language - groovy

I have this script in Groovy:
currentDate = new Date().format( 'yyyyMMdd' )
I want to be able to manipulate the date in order to 'play' with the dates of it..
for example if I have this:20150701 I want to subtract days, weeks or months for example if I subtract one day it will be 20150630.
How can I do it without using TimeCategory?
thanks!

Without TimeCategory, you can only add or subtract days. If you want to add/subtract other fields, TimeCategory is a good way to go.
If your annoyance with TimeCategory is the with syntax, one alternative would be to use mixins (although they are generally considered deprecated since traits have been added to Groovy):
[Date, Integer].each { it.mixin(groovy.time.TimeCategory) }
def lastMonth = new Date() - 1.months

OK I have the answer to it, I tried this and it worked:
currentDate = new Date()
def yesterday = currentDate - 1
currentDate = yesterday.format("yyyyMMdd")

Related

Nodejs change time at date type after getting from Mongodb

I wanted to change time at date type which returning from mongodb with custom time like below
"2021-05-26T00:00:00.000Z"
to
"2021-05-26T10:20:00.000Z"
I wanted to change time from a variable at the date, so my technique was split this date with "T" then get time part and change it with custom time
let splitedTime = timev[0].validFrom.toString().split()[0];
let customTime = "10:20:00.000Z";
let finalTime = splitedTime + customTime;
but this split not working this giving me date like this "Wed May 26 2021 06:00:00 GM". Can you please help me for this?
Working with Date
Whilst I understand your logic of converting it to a string and then using string methods to convert it to your desired output, I believe a simpler approach is to use the Date object
function dateAdd(original, hours, minutes) {
const date = new Date(original);
date.setHours(original.getHours() + hours);
date.setMinutes(original.getMinutes() + minutes);
return date.toISOString();
}
When original = "2021-05-26T00:00:00.000Z" then the return value is "2021-05-26T10:20:00.000Z".
If you want a fixed time:
const date = new Date('2021-05-26T00:00:00.000Z');
date.setUTCHours(10);
date.setUTCMinutes(20);
date.setUTCSeconds(0);
date.setUTCMilliseconds(0);
// a cleaner approach:
date.setUTCHours(10, 20, 0); // hoursValue, minutesValue, secondsValue
console.log(date.toISOString());
Which produces the following:
"2021-05-26T10:20:00.000Z"
Another Solution
Your actual problem is being caused by the fact you call toString which returns a date string in the format of "Tue Aug 19 1975 23:15:30 GMT+0200 (CEST)" so when you're splitting by "T", that's way down at the end. toISOString will return the correct format.
Explanation
As you can see above, we avoid using string methods and use the methods that exist on Date. This approach is safer as you avoid issues with the difference between toISOString and toString. You may also find moment useful if you're using dynamic methods of changing dates regularly.
Note
In all honesty, I'm not entirely sure I understand the why behind what you're doing, so if I'm wrong please correct me so I can update my answer to be more relevant for you.
Learn More
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

how to compare dates using relational Operators in dart?

I'm working on a problem which requires to compare the date with other if the selected date is less than given then print Hello.
The date is present In String Format like given in Examaple
Ex:
if('2020-1-13'<'2021-1-5')
{
print(hello);
}
You should try this it should work
````
var date1 = DateTime.parse('2020-01-13').millisecondsSinceEpoch.toInt();
var date2 = DateTime.parse('2021-01-15').millisecondsSinceEpoch.toInt();
if(date1 < date2){
print('true');
}else{
print('false');
}
````
Instead of doing that just use the date's isBefore or isAfter operator
It would look something like the following:
final now = DateTime.now();
final yesterday = DateTime.now().subtract(Duration(days: 1));
print(now.isAfter(yesterday)); //true
Since your dates are in STring format, it you would have to use the DateTime.parse() method to construct your date objects, and then use the operators talked about above
package:basics provides DateTime extensions that can easily compare DateTime objects.
(Disclosure: I contributed those particular extensions.)

Why does new Date(year,month,day) not return an equivialent Date?

one day I fiddled with vanilla NodeJS using the node command line tool. (I am using node v13.11.0)
I tried to create a new Date at the 01.01.1970. I used the usual new Date(year, month, day) constructor.
As simple as it sounds, I entered new Date(1970, 1, 1) and found out, that it does not return 1970-01-01T00:00:00.0000Z. Instead, it returns 1970-01-31T12:00:00.000Z.
Has anyone an Idea, why this constructor does not return the equivalent date?
The constructor does more or less what you think:
x = new Date(1970,1,1)
1970-01-31T14:00:00.000Z
> x.getMonth()
1
> x.getDate()
1
> x.getHours()
0
(Note that months count from zero, so you requested the 1st of February).
But if you display the whole date as a string, it's showing the time in UTC, which might not be what you expect.

Subtract days or years from new java.text.SimpleDateFormat

Application: SoapUI XML Resquest
I could swear this worked at one time where I use the below:
${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )}
To Subtract or Add I would add enclose the -# or +# like so:
${=${=(new java.text.SimpleDateFormat("yyyy-MM-dd")).format( new Date() )}-1
The result of the -1 is showing up as 1982
QUESTIONS:
Why is it taking away the -MM-dd part?
Why is it subtracting 23 years for -1
GOAL:
To be able to subtract from sysdate and the request show in yyyy-MM-dd format
i.e. if I want someone to be 65 years old - i want to subtract from sysdate to get that.
Again this is a SoapUI tag I'm populating the expression in.
You have the brackets misplaced! Let me break it down for you:
def yesterday = new Date() - 1
def sdf = new java.text.SimpleDateFormat("yyyy-MM-dd")
def yesterdayFormatted = sdf.format(yesterday)
If you want it in a SoapUI property one liner:
${=new java.text.SimpleDateFormat("yyyy-MM-dd").format(new Date() - 1)}
Note that you can achieve the exact same thing with (slightly more compact):
${=String.format('%tF', new Date() - 1)}
Docs for the formatter.

Getting last day of current month

In Groovy, how can I find the last day of the current month?
Thanks for your sage advice and better wisdom.
Yeah, as you commented, Calendar.FIELD is probably your best friend (though groovy's TimeCategory also has neat tricks).
Here's how i made for the last day of the current month:
Calendar.with {
println instance.getActualMaximum( DATE )
}
I didn't understood what you meant by "break out the current weekday if I'm looping through a month". Perhaps getting the weekday for each month?
Calendar.with {
(JANUARY..DECEMBER).each { month ->
def cal = instance
cal[MONTH] = month
println cal[DAY_OF_WEEK]
}
}

Resources