Picking the first and last date of the previous month

3

I'm using Selenium in Eclipse to automate the sending of commands to a website through JAVA files. On this site, I need to check dates. I did so to test:

element = driver.findElement(By.name("form:dtEmissao_input"));
element.sendKeys("01/04/2016");
element = driver.findElement(By.name("form:emissFim_input"));
element.sendKeys("12/04/2016");

However, I wanted him to always get the first and last day of the previous month. How can I do this? Need to import some library into my JAVA file?

    
asked by anonymous 12.04.2016 / 16:30

2 answers

1

You do not need any external libraries! Here is a possible solution

public static voi main(String[] args){
    Calendar c = Calendar.getInstance();
    Date d = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
    d = c.getTime();

    //subtrai 1 do mês atual para pegar o anterior
    c.add(Calendar.MONTH, -1);

    //seta primeiro dia do mês
    c.set(Calendar.DAY_OF_MONTH, c.getActualMinimum(Calendar.DAY_OF_MONTH));
    d = c.getTime();
    System.out.println("Data do primeiro dia do mes passado: " + sdf.format(d));
    //seta ultimo dia do mês
    c.set(Calendar.DAY_OF_MONTH, c.getActualMaximum(Calendar.DAY_OF_MONTH));
    d = c.getTime();
    System.out.println("Data do ultimo dia do mes passado: " + sdf.format(d));
}
    
12.04.2016 / 17:01
1

Using Java 8

In Java 8 this is trivial because it is part of the API.

LocalDateTime data = LocalDateTime.now();
LocalDateTime ultimoDiaDoMesAnterior = data.minusMonths(1).with(TemporalAdjusters.lastDayOfMonth());
System.out.println(ultimoDiaDoMesAnterior.format(DateTimeFormatter.ofPattern("dd/MM/yyyy")));

Note that LocalDateTime does not consider timezone, so it is safer than using Date or Calendar .

Java

13.04.2016 / 09:38