简体   繁体   English

用于将应用程序的日期和时间与系统进行比较的 Java 代码

[英]Java code to compare date and time of an application with the system

I am into automation testing, selenium and java.我喜欢自动化测试、硒和 Java。 I have been asked this question in an interview that suppose we have an application which displays date and time.我在一次采访中被问到这个问题,假设我们有一个显示日期和时间的应用程序。 How can we fetch that and compare with the system date and time to ensure that the application is showing the correct date and time.我们如何获取并与系统日期和时间进行比较,以确保应用程序显示正确的日期和时间。

First you have to get the date from webpage using getText() and then fetch the current date and time from the system using Date Class in java.首先,您必须使用 getText() 从网页获取日期,然后使用 java 中的 Date Class 从系统中获取当前日期和时间。 Then compare both the strings.然后比较两个字符串。

Define a tolerance (say, a couple of seconds) and the expected time zone.定义一个容差(比如几秒)和预期的时区。 Parse the date and time from the web app into an appropriate type from java.time, the modern Java date and time API using a DateTimeFormatter .将 Web 应用程序中的日期和时间从 java.time 解析为适当的类型,java.time 是使用DateTimeFormatter的现代 Java 日期和时间 API。 Use the now method from the same class to get current time (for example, LocalDateTime.now(ZoneId.of("America/Sitka")) ).使用同一个类中的now方法来获取当前时间(例如, LocalDateTime.now(ZoneId.of("America/Sitka")) )。 And and subtract your tolerance and use the isBefore and/or isAfter to determine whether the parsed date and time falls within the allowed.并减去您的容忍度并使用isBefore和/或isAfter来确定解析的日期和时间是否在允许范围内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM