I am writing an automated test in Java using Selenium2/WebDriver. I need to validate a birthday in the future is not allowed. To get tomorrow's date, I am using:
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
I am having trouble printing that to a text field, since .sendKeys requires characters. Any help is appreciated. I'm also unsure if that is the best way to get tomorrow's date.
Your code is basically right. Use a Calendar
to produce Date
objects:
Calendar calendar = Calendar.getInstance();
Date today = calendar.getTime();
calendar.add(Calendar.DAY_OF_YEAR, 1);
Date tomorrow = calendar.getTime();
Use SimpleDateFormat
to format the Date
as a String
:
DateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy");
String todayAsString = dateFormat.format(today);
String tomorrowAsString = dateFormat.format(tomorrow);
System.out.println(todayAsString);
System.out.println(tomorrowAsString);
Prints:
09-Aug-2012
10-Aug-2012
You can use Selenium to send those String
objects to the date control (if it accepts keyed input, of course). You'll need to adjust the date pattern "dd-MMM-yyyy"
to match the format expected by the input control on the page, eg perhaps it's ( "MM/dd/YY"
)?
First, don't you mean to add before defining the date? Then, you could do a
today.toString()
to assign via sendkeys, but IMO you should look first at the format the widget accepts (eg european vs US) and format your date accordingly (eg using something like this ).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.