selenium 如何获取上月最后一天[副本]

brgchamk  于 2023-01-13  发布在  其他
关注(0)|答案(2)|浏览(108)
    • 此问题在此处已有答案**:

find first and last date of the last month [duplicate](4个答案)
16小时前关门了。
我正在尝试一些自动机器人在这里,需要得到上个月的最后一天。虽然在第一次运行的机器人在本月的工作罚款,但在下个月的日期,我从这个代码

Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
dateformat2 = new SimpleDateFormat((cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.DAY_OF_MONTH)+"/yyyy");

不正确。下面是我当前机器人类的完整代码。

typeimport java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;



public class Teco_Bot extends Thread{
    WebDriver driver;
    GUI gui;
    String user[]= {"NorthVillage432","VPM1263"};
    String pass[]= {"user123","user123"};
    String accId[]= {"0","1"};
    SimpleDateFormat dateformat1,dateformatDay,dateformat2,dateformat3;
    Statement st;
    ResultSet rs;
    
    public Teco_Bot() {
        dateformat1 = new SimpleDateFormat("yyyy-MM-dd");
        dateformatDay = new SimpleDateFormat("dd");
        
        dateformat3 = new SimpleDateFormat("MM/dd/yyyy");
                Calendar cal = Calendar.getInstance();
            cal.add(Calendar.MONTH, -1);
            cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
            dateformat2 = new SimpleDateFormat((cal.get(Calendar.MONTH)+1)+"/"+cal.get(Calendar.DAY_OF_MONTH)+"/yyyy");
        gui = new GUI();
        
    }
    
    public void run() {
        
        String currentdate="";
        EmailNotification notif1;
        EmailNotification notif2;
        while(true) {
            try {
                Thread.sleep(2000);
            }catch(Exception ee) {ee.printStackTrace();}
            System.out.println("Waiting");
                    
            
            if((dateformatDay.format(new Date()).equalsIgnoreCase("05")||dateformatDay.format(new Date()).equalsIgnoreCase("15"))&&!currentdate.equalsIgnoreCase(dateformat1.format(new Date())))
            {
                 notif1 = new EmailNotification("junrybuenavista@yahoo.com",30,"Teco Bot");
                 notif1.start();
                 notif2 = new EmailNotification("michaelvinocur@htgrp.net",30,"Teco Bot");
                 notif2.start();
                setDataBaseConnection();
                        while(true) {
                            for(int i=0;i<user.length;i++) {
                                setBrowser();
                                gui.textAppend("Processing "+user[i]+"\n");
                                Login(user[i],pass[i]);
                                
                                currentdate = dateformat1.format(new Date());
                                try {
                                    st.execute("DELETE FROM `teco_data`");
                                }catch(Exception ee) {ee.printStackTrace();}
                                    
                                getData();
                                if(driver.findElements(By.xpath("//*[@id=\"selectionForm\"]/div[3]/div[2]/div[2]/ul/li[2]/a")).size() != 0) {
                                    driver.findElement(By.xpath("//*[@id=\"selectionForm\"]/div[3]/div[2]/div[2]/ul/li[2]/a")).click();
                                    System.out.println();   
                                    getData();
                                }
                                
                                
                                
                                driver.get("http://localhost/googleapi/teco-query.php?day="+dateformatDay.format(new Date())+"&acc="+accId[i]+"&date="+dateformat2.format(new Date())+"&date2="+dateformat3.format(new Date()));
                                System.out.println("http://localhost/googleapi/teco-query.php?day="+dateformatDay.format(new Date())+"&acc="+accId[i]+"&date="+dateformat2.format(new Date())+"&date2="+dateformat3.format(new Date()));
                                try {
                                    Thread.sleep(4000);
                                }catch(Exception ee) {ee.printStackTrace();}
                                driver.quit();
                                try {
                                    Thread.sleep(2000);
                                }catch(Exception ee) {ee.printStackTrace();}
                                gui.textAppend("Processing complete\n\n");
                                                                
                            }
                            try {
                                st.close();
                                rs.close();
                            }catch(Exception ee) {ee.printStackTrace();}
                            break;
                        }
                        notif1.setIsRunning(true);
                        notif2.setIsRunning(true);
                    }                                   
        }
    }
    public void getData() {
        try {
                
                WebElement table = driver.findElement(By.xpath("//*[@id=\"selectionForm\"]/div[2]/table"));
                List<WebElement> acc = table.findElements(By.xpath(".//tr/td[2]"));
                List<WebElement> add = table.findElements(By.xpath(".//tr/td[3]"));
                List<WebElement> amount_due = table.findElements(By.xpath(".//tr/td[4]"));
                List<WebElement> due_date = table.findElements(By.xpath(".//tr/td[5]"));
                
                for(int i=0;i<acc.size();i++) {             
                    System.out.print(acc.get(i).getText()+" ");
                    System.out.print(add.get(i).getText()+" ");
                    System.out.print(amount_due.get(i).getText()+" ");
                    System.out.println(due_date.get(i).getText()+" ");
                    st.execute("INSERT INTO teco_data (acc, address, amount_due, due_date)\r\n"
                            + "VALUES ('"+acc.get(i).getText()+"', '"+add.get(i).getText()+"', '"+amount_due.get(i).getText()+"', '"+due_date.get(i).getText()+"');");
                }
        }catch(Exception ee) {ee.printStackTrace();}        
    }
    public void setDataBaseConnection() {
        while(true) {
            System.out.println("Database connecting");
            gui.textAppend("Database connecting\n");
            try{  
                Thread.sleep(1500);
                Class.forName("com.mysql.jdbc.Driver");  
                Connection con=DriverManager.getConnection(  
                "jdbc:mysql://localhost:3306/teco_db","root","");   
                 st=con.createStatement();
                 break;
                
               }catch(Exception e){}
        }
    }
    public void setBrowser() {      
        System.setProperty("webdriver.chrome.driver", "C:\\Jars\\chromedriver.exe");        
        HashMap<String,Object> chromePrefs = new HashMap<String, Object>();
        chromePrefs.put("plugins.always_open_pdf_externally", true);
        chromePrefs.put("download.default_directory", "C:"+File.separator+"Square_download");
        chromePrefs.put("excludeSwitches", "enable-popup-blocking");    
        ChromeOptions options = new ChromeOptions();
        options.setExperimentalOption("prefs", chromePrefs);
        
        driver = new ChromeDriver(options);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);    
    }
    public void Login(String user,String pass) {

        gui.textAppend("Starting Login\n");
        driver.get("https://account.tecoenergy.com/");
        try {
            Thread.sleep(2000);
        }catch(Exception ee) {ee.printStackTrace();}
        driver.findElement(By.id("UserName")).sendKeys(user);
        driver.findElement(By.id("Credentials_Password")).sendKeys(pass);
        driver.findElement(By.id("login-submit")).click();
        gui.textAppend("Login complete\n");
        try {
            Thread.sleep(4000);
        }catch(Exception ee) {ee.printStackTrace();}
        
    }
    
    class GUI  
    {   JTextArea area;
    
         GUI(){  
                 area=new JTextArea();
                 area.setEditable(false);
                
                 
                 JScrollPane scrollableTextArea = new JScrollPane(area);
                   scrollableTextArea.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {  
                        public void adjustmentValueChanged(AdjustmentEvent e) {  
                            e.getAdjustable().setValue(e.getAdjustable().getMaximum());  
                        }
                    });
                 JFrame frame=new JFrame("Teco bot Running");
                 frame.add(scrollableTextArea);
                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                 frame.setSize(500,300);
                 frame.setLocationRelativeTo(null);
                 frame.setVisible(true);
         }
         public void textAppend(String stringIn) {
             area.append(stringIn);
         }
         public void textClear() {
             area.setText("");
         }
    }
}

如果有人能帮我,我很感激。
我必须在上个月的最后一天得到正确的结果,即使当前月份将更改为下个月对我的机器人自动化。

nbysray5

nbysray51#

您可以使用java.time ...获取该日期。
这个想法很简单:

  • 确定 * 今天 *
  • 减去一个月
  • 休这个月的最后一天

这里有一个方法:

public static LocalDate lastDayOfLastMonth() {
    /*
     * get "today", 
     * subtract a month and 
     * take the last day of the resulting month
     */
    return LocalDate.now()
                    .minusMonths(1)
                    .with(TemporalAdjusters.lastDayOfMonth());
}

您可以在main中使用此方法,并根据需要设置日期格式。
示例:

public static void main(String[] args) {
    // use the method to get the date
    LocalDate lastDayOfLastMonth = lastDayOfLastMonth();
    // define some formatters
    DateTimeFormatter dtf = DateTimeFormatter.ofPattern("MM/dd/uuuu");
    DateTimeFormatter anotherDtf = DateTimeFormatter.ofPattern(
                                        "EEEE, MMM dd uuuu", 
                                        Locale.ENGLISH
                                   );
    // print without a formatter (implicit use of toString())
    System.out.println(lastDayOfLastMonth);
    // print with different formatters
    System.out.println(lastDayOfLastMonth.format(dtf));
    System.out.println(lastDayOfLastMonth.format(anotherDtf));
}

输出:

2022-12-31
12/31/2022
Saturday, Dec 31 2022

(于2023年1月12日执行)

nwlqm0z1

nwlqm0z12#

下面是使用相同类的另一种方法:

LocalDate today = LocalDate.now();
    LocalDate firstDayOfMonth = LocalDate.of(today.getYear(), today.getMonth(), 1);
    LocalDate lastDayOfLastMonth = firstDayOfMonth.minusDays(1);

    System.out.println(lastDayOfLastMonth); // prints on 2023-01-12: "2022-12-31"

作为私有方法:

private LocalDate getLastDayOfLastMonth()
{
    LocalDate today = LocalDate.now();
    LocalDate firstDayOfMonth = LocalDate.of(today.getYear(), today.getMonth(), 1);
    LocalDate lastDayOfLastMonth = firstDayOfMonth.minusDays(1);
    return lastDayOfLastMonth;
}

相关问题