-1
**DATE FROM:** 
def format=new java.text.SimpleDateFormat("yyyyMMdd")
def cal=Calendar.getInstance()
cal.get(Calendar.YEAR);
cal.set(Calendar.MONTH, 0); 
cal.set(Calendar.DAY_OF_MONTH, 31);
[format.format(cal.getTime())]

**DATE TO:**
def format=new java.text.SimpleDateFormat("yyyyMMdd")
def cal=Calendar.getInstance()
cal.add(Calendar.DAY_OF_MONTH,-cal.get(Calendar.DAY_OF_MONTH))
[format.format(cal.getTime())]

when year changes (2020 - 2021) - it confuses January of previous year with January of this year
I have to correct so that in January (December reporting) it extracts data for period 31.01 - 31.12. of previous year.

The job was wrong because it extracted data from 31.01.2021 to 31.12.2020

// retrieve details of the current date
def cal = Calendar.instance;
def currentYear = cal.get(Calendar.YEAR);
def currentMonth = cal.get(Calendar.MONTH);
 

// set the instance to the start of the previous month
if ( currentMonth == 0 ) {
cal.set(currentYear-1, 11, 1);
} else {
cal.set(currentYear, (currentMonth-1), 1);
}
 
// extract the date, and format to a string
Date previousMonthStart = cal.time;
String previousMonthStartFormatted = previousMonthStart.format('yyyy-MM-dd');
bad_coder
  • 11,289
  • 20
  • 44
  • 72
disaster
  • 7
  • 4
  • _"Please correct the job so that in January (December reporting) it extracts data for period 31.01 - 31.12. of previous year."_ - it sounds like you copy-pasted JIRA ticket here. What have you tried so far to fix this problem? – Szymon Stepniak Mar 10 '21 at 09:24
  • i have tried to write IF statement for checking the year, but does not work. Do you have some suggestions? The problem is only when year is changing. So once per year, but want to solve it. – disaster Mar 10 '21 at 10:24
  • What are you actually trying to accomplish? Two dates obviously but what two dates? Start and end of last month based on current date? If you explain the goal we might be able to help you better. Also what version of java are you on? This is relevant as the date time api:s have changed in java 8 and later and provide new tools for solving these kinds of problems. – Matias Bjarland Mar 10 '21 at 10:47
  • at the end of each month there is a job which is triggered automatically and it runs perfect. There was an error when year changed from 2020 to 2021 (so the same problem will be the next year also) because the job automatically took DATE FROM: 01.31.2021 - DATE TO: 31.12.2021. And it should be DATE FROM: 31.01.2020. Probably beacause i have cal.get(Calendar.YEAR); – disaster Mar 10 '21 at 10:55
  • And now im writing something like this: – disaster Mar 10 '21 at 10:55
  • def format=new java.text.SimpleDateFormat("yyyyMMdd") def cal=Calendar.getInstance() def currentYear = cal.get(Calendar.YEAR); def currentMonth = cal.get(Calendar.MONTH); cal.get(Calendar.YEAR); cal.set(Calendar.MONTH, 0); cal.set(Calendar.DAY_OF_MONTH, 31); if ( currentMonth == 2 ) { cal.set(currentYear-1, 11, 1); } else { println "Hello,"; } [format.format(cal.getTime())] – disaster Mar 10 '21 at 10:55
  • So what you want is the last day of the previous month and the last day of the current month as your dates? – Matias Bjarland Mar 10 '21 at 10:57
  • I recommend you don’t use `SimpleDateFormat` and `Date`. Those classes are poorly designed and long outdated, the former in particular notoriously troublesome. Instead use `LocalDate` and `DateTimeFormatter`, both from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). – Ole V.V. Mar 10 '21 at 12:23
  • 2
    Please don't make more work for other people by vandalizing your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the [CC BY-SA 4.0 license](//creativecommons.org/licenses/by-sa/4.0/), for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed. Thus, any vandalism will be reverted. If you want to know more about deleting a post please see: [How does deleting work?](//meta.stackexchange.com/q/5221) – Sabito stands with Ukraine Mar 10 '21 at 14:19

1 Answers1

2

If all you are looking for is the start of the previous year as in your title then the following code:

import java.time.*

def startOfPreviousYear = LocalDate.now()
                                   .withDayOfMonth(1)
                                   .withMonth(1)
                                   .minusYears(1)

println startOfPreviousYear

def againStartingFromJanuary = LocalDate.of(2021, 1, 15)
                                        .withDayOfMonth(1)
                                        .withMonth(1)
                                        .minusYears(1)

println againStartingFromJanuary

demonstrates one way to accomplish this. When run, this prints (with now being today's date of 2021.Mar.10):

─➤ groovy solution.groovy
2020-01-01
2020-01-01

updated after comments

You can get the end of previous and current months with something like this:

import java.time.* 

def endOfPreviousMonth = LocalDate.now()
                                  .withDayOfMonth(1)
                                  .minusDays(1)

def endOfCurrentMonth  = LocalDate.now()
                                  .withDayOfMonth(1)
                                  .plusMonths(1)
                                  .minusDays(1)

println "end of last month:    ${endOfPreviousMonth}"
println "end of current month: ${endOfCurrentMonth}"

which with current date prints:

end of last month:    2021-02-28
end of current month: 2021-03-31

or if we are in january:

def endOfPreviousMonth = LocalDate.of(2021, 1, 15)
                                  .withDayOfMonth(1)
                                  .minusDays(1)

def endOfCurrentMonth  = LocalDate.of(2021, 1, 15)
                                  .withDayOfMonth(1)
                                  .plusMonths(1)
                                  .minusDays(1)

println "end of last month:    ${endOfPreviousMonth}"
println "end of current month: ${endOfCurrentMonth}"

which prints:

─➤ groovy solution.groovy
end of last month:    2020-12-31
end of current month: 2021-01-31

In general you should try to, when possible, stay away from using manual date arithmetic when dealing with dates if your target is based on the current date (as in, previous month, next month, three months ago, etc). Use the api:s handed to you by java. The date classes take care of rolling years, rolling months, rolling days, leap years, etc, all that stuff that you really do not want to spend time solving yourself.

Matias Bjarland
  • 4,124
  • 1
  • 13
  • 21
  • this is good but the year is fix. at the end of each month there is a job which is triggered automatically and it runs perfect. There was an error when year changed from 2020 to 2021 (so the same problem will be the next year also) because the job automatically took DATE FROM: 01.31.2021 - DATE TO: 31.12.2021. And it should be DATE FROM: 31.01.2020. Probably because i have cal.get(Calendar.YEAR); All i want .. when will be 2022 year, the job should execute from 31.01.2021 to 31.12.2021 and not 31.01.2021 to 31.12.2022 – disaster Mar 10 '21 at 11:26