You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中如何从日期时间列表提取当日日期并移除时间戳?

提取Web表格中当日日期并移除时间戳的解决方案

需求分析

你需要从Web表格指定列中,筛选出日期为当日的记录,同时移除每个条目中的时间戳部分,最终得到仅包含当日日期的列表。

现有代码问题

当前代码仅简单获取列元素文本并加入列表,未实现日期筛选和时间戳移除逻辑,还存在无用空循环和未合理利用的变量(string2)。

修改后的实现代码

以下是基于Java Selenium的完整解决方案,采用Java 8+的DateTimeFormatter处理日期(兼容性更强):

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

// 定义日期格式,与列表中的日期格式匹配(dd/MM/yyyy)
DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern("dd/MM/yyyy");
// 获取当日日期的字符串形式
String todayDate = LocalDate.now().format(dateFormatter);

List<WebElement> colValues = driver.findElements(By.xpath("//table[@class='v-table-table']//tbody//tr//td[17]"));
List<String> filteredDates = new ArrayList<>();

for(WebElement e : colValues) {
    String dateTimeStr = e.getText().trim();
    // 分割日期与时间部分,提取前半段日期
    String datePart = dateTimeStr.split(" ")[0];
    // 校验是否为当日日期,符合则加入结果列表
    if(datePart.equals(todayDate)) {
        filteredDates.add(datePart);
    }
}

// 输出最终结果
System.out.println("筛选后的当日日期列表:" + filteredDates);

针对你的示例数据的预期结果

假设当日日期为08/09/2022,运行代码后得到的列表为:

[08/09/2022, 08/09/2022, 08/09/2022, 08/09/2022, 08/09/2022, 08/09/2022, 08/09/2022]

补充说明

  • 若你的日期格式不是dd/MM/yyyy,只需调整DateTimeFormatter的格式字符串(比如MM/dd/yyyy对应月/日/年格式)
  • 代码用split(" ")分割日期和时间,适用于两者以空格分隔的场景,若分隔符不同可替换为对应字符
  • 加入trim()是为了处理文本中可能存在的首尾空格

内容的提问来源于stack exchange,提问作者Pooja

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:03:20