【问题标题】:How to split a date from String by using Selenium?如何使用 Selenium 从字符串中拆分日期?
【发布时间】:2019-03-17 10:15:19
【问题描述】:

在下面的字符串中,我想通过与总字符串分开来将日期保存在单独的变量中。

    String text="The client start date is 13/10/2018";
    String[] effectiveDateText=text.split(" ");

    for(int i=0;i<effectiveDateText.length;i++){
        String effectiveDate=effectiveDateText.length-1;
    }

我收到一条编译器错误消息

类型不匹配:无法从 int 转换为 String

将日期放入单独变量的正确方法是什么?

【问题讨论】:

  • string singleDate = effectiveDateText[(effectiveDateText.length)-1] 是你需要的。
  • 感谢编辑。你的问题现在很清楚,我已经投票支持重新开放。
  • 如果这是用于 Selenium 测试,为什么不另辟蹊径呢?如果您想检查日期是否为13/10/2018,请连接前面的文本并检查您从 Selenium 获得的文本是否匹配。 "The client start date is " + expectedDate。或者可以测试text.endsWith("13/10/2018")
  • Ayush Goel 想说:Selenium 不用于拆分字符串。阅读 Java 或您正在使用的任何编程语言中的字符串操作。

标签: java selenium date split


【解决方案1】:

经过大量修改,现在可以了,

用这个简单,

string SingleDate = effectiveDateText[(effectiveDateText.length)-1]

别忘了 EffectiveDateText 是一个字符串数组,你需要 '.[ int ]' 就可以了。
如果您不确定放置日期的位置,我仍然建议您使用正则表达式,

String regex = "(\\d{2}-\\d{2}-\\d{4})";
Matcher m = Pattern.compile(regex).matcher(text);
if (m.find()) {
    Date date = new SimpleDateFormat("dd-MM-yyyy").parse(m.group(1));
}

根据您的客户开始日期和您的拆分代码方法, 看来你正在以错误的角色进行分裂, 你得到了需要拆分的日期数,

你应该在'/'处分割而不是在''处分割

尝试使用,

String FullDate = driver.findElement(By.xpath(xpath)).getText(); // FullDate = 13/10/2018
String[] effectiveDateText=FullDate.split("/");
String Day = effectiveDateText[0]; // Day = 13    
List<Date> dList = new List<>();

我只是好奇为什么你使用 for 循环你可以使用 forEach 代替, FullDate 变量中是否存在更多日期。
(比如 FullDate = "13/10/2018 13/10/2018 13/10/2018 13/10/2018" 对了)

for(String effectiveDate : effectiveDateText){
   // effectiveDate contains date of your like
   effectiveDate = effectiveDate.Trim();
   Date date1 = new SimpleDateFormat("dd/MM/yyyy").parse(effectiveDate);
   dList.add(date1);
}

我希望这回答了你的问题
您将获得 List dList 中的所有日期;

【讨论】:

  • 嗨..在这个问题中,我想将整个日期从字符串值中拆分出来,而不仅仅是天
  • 在“FullDate”变量中得到了什么请在您的问题中提供,或者您的 html 元素结构需要更多帮助和澄清您的问题。
  • 嗨,Ahish,对不起,不清楚......你能检查一下吗
  • 好吧,我的意思是这个命令 driver.findElement(By.xpath(xpath)).getText() 给你一堆用“”分隔的日期,即我想要的“空格”,实际的 TEXT此命令返回给您。
  • string singleDate = effectiveDateText[(effectiveDateText.length)-1] 是你需要的。
【解决方案2】:

根据 text 客户端开始日期是 13/10/2018date 存储在单独的变量中,您可以使用 split() 方法,可以使用以下解决方案:

  • 代码块:

    public class Split_in_Java  
    {
        public static void main(String[] args) 
        {
            String text="The client start date is 13/10/2018";
            String[] parts = text.split(" ");
            System.out.println(parts[parts.length-1]);
        }
    }
    
  • 控制台输出:

    13/10/2018
    

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-15
    • 2018-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多