Selenium Calendar: Months and Dates Selections: What i'm doing wrong - java

i'm trying to select Months and Dates from a calendar (www.booking.com) for practice purposes but i can not get it to select the month, if the month is into left panel. Probably i'm missing something. Can anyone give me a hint? or make an assist, it would be much appreciated. Thanks in advance.
My Code:
public void calendar() throws InterruptedException {
String selectDate = "6/11/2020";
Date d = new Date(selectDate);
SimpleDateFormat years = new SimpleDateFormat("yyyy");
SimpleDateFormat months = new SimpleDateFormat("MMMM");
SimpleDateFormat days = new SimpleDateFormat("d");
String year = years.format(d);
String month = months.format(d);
String day = days.format(d);
String gap = " ";
String search = month + gap + year;
while (!driver.findElement(By.xpath("//div[#class='xp-calendar']/div/div/div/div/*[contains(#class,'bui-calendar__month')]")).getText().equalsIgnoreCase(search)) {
Thread.sleep(1000);
driver.findElement(By.xpath("//div[#class='xp-calendar']/div/div/div[2]")).click();
}
int coutDays = driver.findElements(By.xpath("//div[#class='xp-calendar']/div/div/div/div/table/tbody/tr/td")).size();
for (int i = 0; i < coutDays; i++) {
String searchingDay = driver.findElements(By.xpath("//div[#class='xp-calendar']/div/div/div/div/table/tbody/tr/td")).get(i).getText();
if (searchingDay.equalsIgnoreCase(day)) {
Thread.sleep(1000);
driver.findElements(By.xpath("//div[#class='xp-calendar']/div/div/div/div/table/tbody/tr/td")).get(i).click();
break;
}
}

you can use the css to select the calendar date.
driver.findElement(By.cssSelector("td[data-date='2019-03-21']")).click();
Make sure you pass the date in "YYYY-MM-DD" format.
Here is the code if you want to try in your console first.
document.querySelector('td[data-date="2019-03-21"]').click()
You don't have to open the date picker, just navigate to the page and run the above.

Correct Code:
String date = "10-June 2020";
String splitter[]= date.split("-");
String checkInMonth_Year = splitter[1];
String checkInDay = splitter[0];
List<WebElement> a = driver.findElements(By.xpath("//div[#class='bui-calendar']/div/div/div/div"));
for (int i=0; i<a.size(); i++)
{
System.out.println(a.get(i).getText());
if (a.get(i).getText().equals(checkInMonth_Year))
{
List<WebElement> days = driver.findElements(By.xpath("//div[#class='bui-calendar']/div/div/div["+(i+1)+"]/table/tbody/tr/td[#class='bui-calendar__date']"));
for (WebElement d:days)
{
if (d.getText().equals(checkInDay))
{
d.click();
return;
}
}
}
}
pauseFor1Sec();
driver.findElement(By.xpath("//div[contains(#class,'bui-calendar__control bui-calendar__control--next')]")).click();
calendar();

Related

Change date format from m/dd/yy to yyyy/MM/dd in Java

I have this Date in a String with a 2 digit year.
I need to convert in another format. I tried with SampleDateFormat but it didn't work.
The SampleDateFormat is giving wrong format i.2 date with UTC and timestamp
I want in yyyy/MM/dd only.
Is there any other way to do this?
String receiveDate = "7/20/21";
DateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
try {
rdate = sdf.parse(receiveDate);
} catch (ParseException e) {
e.printStackTrace();
}
String recievedt = rdate.toString();
String dateParts[] = recievedt.split("/");
// Getting day, month, and year from receive date
String month = dateParts[0];
String day = dateParts[1];
String year = dateParts[2];
int iday = Integer.parseInt(day);
int imonth = Integer.parseInt(month);
int iyear = Integer.parseInt(year);
LocalDate date4 = LocalDate.of(iyear, imonth, iday).plusDays(2*dueoffset);
If you can use the java.time API I would suggest something along the lines of the following:
String input = "7/20/21";
LocalDate receivedDate = LocalDate.parse(input, DateTimeFormatter.ofPattern("M/dd/yy"));
String formatted = receivedDate.format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
// or if you actually need the date components
int year = receivedDate.getYear();
...
How is String receiveDate="7/20/21"; a valid date?
String dateStr = "07/10/21";
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date)); // 2007/10/21
This, however, requires that you have date with leading zeros for year, month and date. If that is not the case, please sanitize your date string.
public static String sanitizeDateStr(String dateStr) {
String dateStrArr[] = dateStr.split("/");
String yearStr = String.format("%02d", Integer.parseInt(dateStrArr[0]));
String monthStr = String.format("%02d", Integer.parseInt(dateStrArr[1]));
String dayStr = String.format("%02d", Integer.parseInt(dateStrArr[2]));
return String.format("%s/%s/%s", yearStr, monthStr, dayStr);
}
public static void main (String[] args) throws Exception {
String dateStr = sanitizeDateStr("7/10/21");
SimpleDateFormat receivedFormat = new SimpleDateFormat("yy/MM/dd");
SimpleDateFormat finalFormat = new SimpleDateFormat("yyyy/MM/dd");
Date date = receivedFormat.parse(dateStr);
System.out.println(finalFormat.format(date));
}

Java get int numbers from DateFormat and have user Input

In my code I want to have the individual numbers from date format so I can use them as int values:
public static final String DATE_FORMAT = "dd.MM.yyyy";
public int age()
{
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
// How to convert to int?
int currentnDay = ?;
int currentMonth = ?;
int currentYear = ?;
}
also I would like some user input to define day,month and year in one go, if that's even possible:
private Date dateOfPublication;
public void input()
{
Scanner scn = new Scanner( System.in );
System.out.print( "Please enter dateOfPublication: " );
// How to setup input for this?
}
I hope you can help me out, previously I did it all seperatly but the code was quite big and I think it would be prettier if I could do it like that..
update: okay I'm doing the input like this now:
System.out.print( "Please enter dateOfPublication, use format of x.x.xxxx: " );
userInputDate = scn.next();
String[] ary = userInputDate.split("\\.");
publicationDay = Integer.parseInt(ary[0]);
publicationMonth = Integer.parseInt(ary[1]);
publicationYear = Integer.parseInt(ary[2]);
thanks for your help!
Take a look at Java 8's new Time API (or JodaTime or Calendar if you're really stuck)
LocalDate ld = LocalDate.parse("16.10.2015", DateTimeFormatter.ofPattern(DATE_FORMAT));
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue());
System.out.println(ld.getYear());
Which outputs
2015-10-16
16
10
2015
Now, you could simply ask the user to input a date in a given format and try and parse the result, if the parsing fails, you could reprompt them
For example...
Scanner input = new Scanner(System.in);
LocalDate ld = null;
do {
System.out.print("Please enter date in " + DATE_FORMAT + " format: ");
String value = input.nextLine();
try {
ld = LocalDate.parse(value, DateTimeFormatter.ofPattern(DATE_FORMAT));
} catch (Exception e) {
System.err.println(value + " is not a valid date for the format of " + DATE_FORMAT);
}
} while (ld == null);
System.out.println(ld);
System.out.println(ld.getDayOfMonth());
System.out.println(ld.getMonth().getValue()); // Is probably 0 indexed
System.out.println(ld.getYear());
You can use:
dateFormat.format(today).split("\\.");
For your code:
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
Date date = new Date();
String[] dateArr = dateFormat.format(today).split("\\.");
int currentnDay = Integer.parseInt(dateArr[0]);
int currentMonth = Integer.parseInt(dateArr[1]);
int currentYear = Integer.parseInt(dateArr[2]);
IdeOne Example
First, you have to parse the input string
The Calendar data type is more flexible for date-time handling. This is an example that shows some Date/Calendar operations.
Date date;
Calendar c;
// Get the current date
c = Calendar.getInstance();
System.out.println("Current Calendar:" + c.getTime().toString());
int currentnDay = c.get(Calendar.DATE);
int currentMonth = c.get(Calendar.MONTH);
int currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Current Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
String DATE_FORMAT = "dd.MM.yyyy";
DateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
date = dateFormat.parse("11.10.1981");
System.out.println("Modified Date:" + date.toString());
// reset Calendar
c = Calendar.getInstance();
// set date to the calendar
c.setTimeInMillis(date.getTime());
currentnDay = c.get(Calendar.DATE);
currentMonth = c.get(Calendar.MONTH);
currentYear = c.get(Calendar.YEAR);
System.out.println(String.format("Modified Values: %d/%d/%d",
currentnDay, currentMonth, currentYear));
This is the output of the example.
Current Calendar:Thu Oct 15 20:22:59 EDT 2015
Current Values: 15/9/2015
Modified Date:Sun Oct 11 00:00:00 EDT 1981
Modified Values: 11/9/1981

Android check days between two day-times

Hello everyone i try to check between days two daytimes
i have for example 12/10/2014 and 12/15/2015 datetimes.I wrote some code witch can to check different days between there two daytimes
this is a my source
public String getDateDiffString(Date dateOne, Date dateTwo) {
long timeOne = dateOne.getTime();
long timeTwo = dateTwo.getTime();
long oneDay = 1000 * 60 * 60 * 24;
long delta = (timeTwo - timeOne) / oneDay;
if (delta > 0) {
return String.valueOf(delta);
} else {
delta *= -1;
return String.valueOf(delta);
}
}
this code working perfect but i want to increase days for example 12/10/2014, 12/11,2014.....12/20/2014 between first and second daytimes.i i also wrote code but result is between first date and second days -1(between 12/19/2014)
this is a my source
SimpleDateFormat df = new SimpleDateFormat("MM/dd/yyyy");
Date _d;
try {
SimpleDateFormat new_df = new SimpleDateFormat("d MMM");
_d = df.parse(timeInfo.getTimeformat().get(0));
Date _d1 = df.parse(timeInfo.getEndTimeFormat().get(0));
String datetimeis = getDateDiffString(_d1, _d);
int differentdays = Integer.parseInt(datetimeis);
Log.e("Different is ", "" + differentdays);
for (int k = 0; k < differentdays; k++) {
String datetimeformat = dateFormatter(timeInfo.getStartTimePeriod().get(0));
Date datetime = new_df.parse(datetimeformat);
Calendar cal = Calendar.getInstance();
cal.setTime(datetime);
cal.add(Calendar.DATE, k);
datetime = cal.getTime();
String ttime = new_df.format(datetime);
ApishaDaysAdapter.add(ttime);
ApishaHollsAdapter.add(timeInfo.getHole());
String start_time = timeInfo.getTime();
start_time = start_time.replace(",", "\n");
ApishaTimesAdapter.add(start_time);
timeInfo.setStartTimePeriod(ttime);
System.out.println(ttime);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
how i can solve my problem?if anyone knows solution please help me
i want to increase days [12 -20] and not [12-19)

How to automate selection of a particular date from calendar in selenium using java

I have a case in which I have to pick 3 days back date from the calendar.How to automate this case using selenium.I am using java with selenium for automation..
1) Assumption is that you can write the date in the input field and calendar is only the icon. You can have helper method something like this
public String threeDaysBefore(){
String threeDaysBefore = "";
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, -3);
Date before = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd.MM.yyyy HH:mm");
threeDaysBefore = formatter.format(before);
return threeDaysBefore;
}
And later in the code
WebElement calendarManualInput = driver.findElement...// find the manual input field
calendarManualInput.sendKeys(threeDaysBefore());
2) If you can only click the calendar, It would be little more tricky. You still need the String, but little different:
public String threeDaysBefore(){
String threeDaysBefore = "";
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DAY_OF_YEAR, -3);
Date before = cal.getTime();
SimpleDateFormat formatter = new SimpleDateFormat("dd");
threeDaysBefore = formatter.format(before);
return threeDaysBefore;
}
But the above has little catch. If the date is 1.4. then it will return you "29" which could be interpreted as 29.4. which you dont want to happen. So later in the code you will probably have to do this
//this will click three days before
Date today = new Date();
Date minusThree = new Date();
Calendar now = Calendar.getInstance();
now.setTime(today);
Calendar before = Calendar.getInstance();
before.setTime(minusThree);
before.add(Calendar.DAY_OF_YEAR, -3);
int monthNow = now.get(Calendar.MONTH);
int monthBefore = before.get(Calendar.MONTH);
if (monthBefore < monthNow){
// click previous month in the calendar tooltip on page
}
WebElement dateToSelect = driver.findElement(By.xpath("//span[text()='"+threeDaysBefore()+"']"));
dateToSelect.click();
here i show you my orignal code for automating jqueryui calender from its official site "https://jqueryui.com/resources/demos/datepicker/default.html".
copy paste the code and see it working like charm :)
vote up if you like it :) regards Avadh Goyal
public class calendarHanding {
static int targetDay = 4, targetMonth = 6, targetYear = 1993;
static int currenttDate = 0, currenttMonth = 0, currenttYear = 0;
static int jumMonthBy = 0;
static boolean increment = true;
public static void getCurrentDayMonth() {
Calendar cal = Calendar.getInstance();
currenttDate = cal.get(Calendar.DAY_OF_MONTH);
currenttMonth = cal.get(Calendar.MONTH) + 1;
currenttYear = cal.get(Calendar.YEAR);
}
public static void getTargetDayMonthYear(String dateString) {
int firstIndex = dateString.indexOf("/");
int lastIndex = dateString.lastIndexOf("/");
String day = dateString.substring(0, firstIndex);
targetDay = Integer.parseInt(day);
String month = dateString.substring(firstIndex + 1, lastIndex);
targetMonth = Integer.parseInt(month);
String year = dateString.substring(lastIndex + 1, dateString.length());
targetYear = Integer.parseInt(year);
}
public static void calculateToHowManyMonthToJump() {
if ((targetMonth - currenttMonth) > 0) {
jumMonthBy = targetMonth - currenttMonth;
} else {
jumMonthBy = currenttMonth - targetMonth;
increment = false;
}
}
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
String dateToSet = "16/12/2016";
getCurrentDayMonth();
System.out.println(currenttDate);
System.out.println(currenttMonth);
System.out.println(currenttYear);
getTargetDayMonthYear(dateToSet);
System.out.println(targetDay);
System.out.println(targetMonth);
System.out.println(targetYear);
calculateToHowManyMonthToJump();
System.out.println(jumMonthBy);
System.out.println(increment);
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ashutosh.dobhal\\Desktop\\Software\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.navigate().to(
"https://jqueryui.com/resources/demos/datepicker/default.html");
driver.manage().window().maximize();
Thread.sleep(3000);
driver.findElement(By.xpath("//*[#id='datepicker']")).click();
for (int i = 0; i < jumMonthBy; i++) {
if (increment) {
driver.findElement(
By.xpath("//*[#id='ui-datepicker-div']/div/a[2]/span"))
.click();
} else {
driver.findElement(
By.xpath("//*[#id='ui-datepicker-div']/div/a[1]/span"))
.click();
}
Thread.sleep(1000);
}
driver.findElement(By.linkText(Integer.toString(targetDay))).click();
}
}

How do I call a non-static method from another class in a non-static method? (java)

import java.util.*;
import java.io.*;
public String recToString (boolean format) {
Date date = new Date();
File inputFile = new File ("records.txt");
Scanner sc = new Scanner(inputFile);
if (format == true){
format = Date1.usFormat();
format = Date1.usFormat();
} else {
format = Date1.euFormat();
}
}
I plan to call the usFormat and euFormat.
import java.util.*;
import java.io.*;
class Date1 {
String month = "";
String day = "";
String year = "";
public Date1 (String date) {
StringTokenizer st = new StringTokenizer(date, "/");
month = st.nextToken();
day = st.nextToken();
year = st.nextToken();
} //end constructor
public String usFormat () {
String date = month + "/" + day + "/" + year;
return date;
} //end usFormat
public String euFormat () {
String date = day + "/" + month + "/" + year;
return date;
} //end euFormat
} //end class
Try to ignore any other mistakes please. But if it screws up this and I have to change it to get it, please do tell :)
Thanks.
You need to construct a Date1 object and call the methods on that. You need to do something like
...
String dateString = ...
Date1 date1 = new Date1(dateString);
if (format){
format = date1.usFormat();
} else {
format = date1.euFormat();
}
In this case i'd typically do the following
format = new Date1(date.toString()).usFormat();
format = new Date1(date.toString()).usFormat();
Not sure why you are not making them static though.
You're calling:
Date1.usFormat();
like usFormat is a static method. But, as you already said, it's not. You need to create an instance of Date1 by doing:
Date1 myDate1 = new Date1("01/01/2001");
After that you can call either format method with the myDate1 object like:
format = myDate1.usFormat();

Categories