I have:
int lineTable = Table.getRowCount();
int columnTable= Table.getColumnCount();
Object[][] arrayTable = new Object[lineTable ][columnTable];
for (int j = 0; j < lineTable ; j++) {
for (int i = 0; i < columnTable; i++) {
arrayTable [j][i] = Table.getValueAt(j, i);
}
}
With this, I have a multidimensional array type Object with all data of the table... Can I convert this array to date(HH:mm)?
PS: The data is already in this format(HH:mm), but I don't know how take this directly in date format...
I did it! Just made these changes:
int lineTable = Table.getRowCount();
int columnTable= Table.getColumnCount();
Date[][] arrayTable = new Date[lineTable ][columnTable];
for (int j = 0; j < lineTable ; j++) {
for (int i = 0; i < columnTable; i++) {
arrayTable [j][i] = (Date)Table.getValueAt(j, i);
}
}
Thanks for all!
You can use the SimpleDateFormat class to parse the String to Date object like this:
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String str = yourArray[x][x] + ":" + yourArray[x][x]
Date date = sdf.parse(str);
Try something like this:
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); //your format here
Date date = df.parse("11-3-1985");
System.out.println("" + date);
}
This will parse a date in the given format. You can also create another DateFormat for formatting the date when you print if if you want a different format example:
public static void main(String[] args) throws ParseException {
DateFormat df = new SimpleDateFormat("MM-dd-yyyy"); //your format here
DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy");
Date date = df.parse("11-3-1985");
System.out.println("" + df1.format(date));
}
This is just an example you can use whatever format you want...if you only want to give hours and seconds do that.
Related
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();
I have a hashmap of the following type
HashMap<String,List<Training>> map=new HashMap<String,List<Training>>();
Input:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
python 10-10-2017 12-11-2017 www viz
Enter Date: 01-10-2017
The attributes/values to be displayed are like this :
Output:
topicName startDate endDate Trainer Venue
css 01-10-2017 11-11-2017 ccc hyd
html 01-10-2017 12-11-2017 www viz
I need to retrieve the details of list from getList().What code do i need to write in this method such that when user enters the date i can display output in the desired way as shown above.
public List<Training> getList(String fromDate) {
}
public static void main(String args[]) throws ParseException{
Map<String,List<Training>> map = new HashMap<String,List<Training>>();
Scanner sc = new Scanner(System.in);
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
//DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
//Date fromDate = dateFormat.parse(sc.next());
//Date toDate = dateFormat.parse(sc.next());
String fromDate = sc.next();
String toDate = sc.next();
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
List<Training> l1=new ArrayList<Training>();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
//System.out.println("list********"+l1);
if(!map.containsKey(fromDate)){
map.put(fromDate,l1);
}else{
map.get(fromDate).add(new Training(topicName,fromDate,toDate,trainer,venue));
}
}
System.out.println("map********"+map);
}
#Override
public String toString() {
return gettopicName() + getfromDate() + gettoDate() + gettrainer() + getvenue() ;
}
Since, fromDate is the key for your Map. Then, you could simply get method which will give you List<Training>.
return map.get(fromDate);
If there are no value for specified key, then it will return null.
Try below code instead of creating Map based on from Date keep a list of training. If user enter date iterate over the training to filter it.
public List<Training> getList(List<Training> trainingList, Date date) {
List<Training> list = new ArrayList<Training>();
for( Training training : trainingList ) {
if( training.getFromDate().getTime() <= date.getTime() &&
date.getTime() <= training.getToDate().getTime() ) {
list.add(training);
}
}
return list;
}
public static void main(String args[]) throws ParseException{
Scanner sc = new Scanner(System.in);
List<Training> l1=new ArrayList<Training>();
System.out.println("Give me a size ");
int n = sc.nextInt();
for (int i = 0; i < n; i++){
String topicName = sc.next();
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date fromDate = dateFormat.parse(sc.next());
Date toDate = dateFormat.parse(sc.next());
System.out.println("fromDate********"+fromDate);
String trainer = sc.next();
String venue = sc.next();
l1.add(new Training(topicName,fromDate,toDate,trainer,venue));
}
System.out.println("map********"+l1);
}
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();
}
}
I am trying to remove data from hashtable for a particular date,the hashtable is of type (String,vector).Initially i am checking if hashtable contains the usrDate if yes then i need to remove all the data frm hashtable only for usrDate and add the new data that is listEvents.But the contains from hashtable for other dates should not be deleted.
listEvents.addElement(eventBean);//new data is here
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
}
//checking if hashtable has given date
if (listUserEvents.containsKey(usrDate)) {
Vector info = (Vector)listUserEvents.get(usrDate);
info.addElement(eventBean);
listUserEvents.put(usrDate,info);
} else {
listUserEvents.put(usrDate,listEvents);
}
i just want to add listEvents to the hashtable for the given date,without affecting the other data in hashtable which has data for some other dates.
private Hashtable getEvents(String usrDate, String timezone) {
try {
listUserEvents = getUserInfo();
listEvents = new Vector();
Calendar calendarLocalEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEvent = calendarLocalEvent.getTimeZone();
System.out.println("Time Zone first-->"
+ timeZoneEvent.getDefault());
if (timezone.equals(timeZoneEvent.getDefault())) {
;
} else {
TimeZone timeZoneChange = TimeZone.getTimeZone(timezone);
System.out.println("Time Zone change-->" +timeZoneChange);
Device.setTimeZone(timeZoneChange);
}
EventList eventList = (EventList) PIM.getInstance().openPIMList(
PIM.EVENT_LIST, PIM.READ_ONLY);
Enumeration events = eventList.items();
while (events.hasMoreElements()) {
System.out.println("in while");
Event event = (Event) events.nextElement();
if (eventList.isSupportedField(Event.START)
&& event.countValues(Event.START) > 0)
{
long start = event.getDate(Event.START, 0);
SimpleDateFormat sdf = new SimpleDateFormat(
"MMM dd,yyyy HH:mm");
SimpleDateFormat sdf_start = new SimpleDateFormat("HH:mm");
SimpleDateFormat sdf_start_min = new SimpleDateFormat("HH");
String dateString = sdf.formatLocal(start);
String timeString = sdf_start.formatLocal(start);
String hour = sdf_start_min.formatLocal(start);
SimpleDateFormat sdf1 = new SimpleDateFormat("MMM dd,yyyy");
String date = sdf1.formatLocal(start);
System.out.println("dates are :" + date +"user" + usrDate);
if (usrDate.equalsIgnoreCase(date)) {
System.out.println("dates are equal:" +date);
EventData eventBean = new EventData();
if (eventList.isSupportedField(Event.END)
&& event.countValues(Event.END) > 0) {
long end = event.getDate(Event.END, 0);
SimpleDateFormat sdform = new SimpleDateFormat(
"MMM dd, yyyy HH:mm");
SimpleDateFormat sdfTime = new SimpleDateFormat(
"HH:mm");
SimpleDateFormat sdfhr = new SimpleDateFormat("HH");
String dateString1 =sdform.formatLocal(end);
String timeString1 =sdfTime.formatLocal(end);
String hr = sdfhr.formatLocal(end);
eventBean.setStartHr(hour);
eventBean.setEndHr(hr);
eventBean.setStartTime(timeString);
eventBean.setEndTime(timeString1);
eventBean.setStartDate(dateString);
eventBean.setEndDate(dateString1);
// Dialog.alert("equal startdate" + dateString);
// Dialog.alert("equal end date"+ dateString1);
}
if (eventList.isSupportedField(Event.LOCATION)
&& event.countValues(Event.LOCATION) > 0) {
String location = event
.getString(Event.LOCATION, 0);
eventBean.setLocation(location);
// Dialog.alert("equal location"+ location);
}
if (eventList.isSupportedField(Event.SUMMARY)
&& event.countValues(Event.SUMMARY) > 0) {
String subject = event.getString(Event.SUMMARY, 0);
eventBean.setSummary(subject);
// Dialog.alert("equal subject" +subject);
}
eventBean.setUserDate(usrDate);
eventBean.setTimeZone(timezone);
listEvents.addElement(eventBean);
System.out.println("the size bf hashis"
+ listEvents.size());
for (int i = 0; i < listEvents.size();i++) {
EventData e = (EventData)listEvents.elementAt(i);
System.out.println("so thesummary is ::"
+ e.getSummary());
}
// for(int i=0;i<listUserEvents.size();i++){
if (listUserEvents.containsKey(usrDate)) {
// listUserEvents.remove(usrDate);
Vector info = (Vector)listUserEvents.get(usrDate);
System.out.println("the size in getEvents is"
+ info.size());
if(info.contains(usrDate)){
System.out.println("in info");
}
info.addElement(eventBean);
System.out.println("vector size info is"
+ info.size());
listUserEvents.put(usrDate,info);
} else {
System.out.println("in else of getevent" +listEvents.size());
listUserEvents.put(usrDate,listEvents);
}
// }
} else {
// Dialog.alert("not equal");
}
}
}
Device.setTimeZone(timeZoneEvent);
Calendar calendarLocalLastEvent = Calendar.getInstance();
// fetches time zone
TimeZone timeZoneEventLast =calendarLocalLastEvent.getTimeZone();
System.out.println("Time Zone last-->"
+ timeZoneEventLast.getDefault());
} catch (PIMException e) {
// //Dialog.alert(e.getMessage());
}
System.out.println("size in hashtable " + listUserEvents.size());
return listUserEvents;
}
It must be something like this
for(int i = 0; i<listUserEvents.size();i++)
{
if (listUserEvents.containsKey(usrDate)){
listUserEvents.remove(usrDate);
}
}
Here is a simple example of how this works:
Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
numbers.put("one", 1);
numbers.put("two", 2);
if (numbers.containsKey("two")) {
numbers.put("two", 222);
}
What are you having difficulty at? Moreover what is the type of your Hashtable key? Is it java.util.Date or something else?
If i have an Array which contains the Strings 07:46:30 pm , 10:45:28 pm , 07:23:39 pm , .......
and I want to convert it into Time. How can i do this?
Here's how to convert an array of Strings in the given format to an array of dates:
public static Date[] toDateArray(final String[] dateStrings)
throws ParseException{
final Date[] arr = new Date[dateStrings.length];
int pos = 0;
final DateFormat df = new SimpleDateFormat("K:mm:ss a");
for(final String input : dateStrings){
arr[pos++] = df.parse(input);
}
return arr;
}
Use the SimpleDateFormat class. Here is an example:
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
for(String str : array){
Date date = formatter.parse(str);
}
Use the SimpleDateFormat class to parse the date.
You need to write your own parser. See this example:
http://www.kodejava.org/examples/101.html
If you want a array or list of time...
String[] arrString = new String[] { "07:46:30 pm", "10:45:28 pm", "07:23:39 pm" }
Time[] arrTime = new Time[strArray.lengh];
or
List<Time> listTime = new ArrayList<Time>();
Array string to array or list time:
//For array
for (int i = 0; i < arrString.length; i++) {
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = formatter.parse(arrString[i]);
//Populate the ARRAY
arrTime[i] = new Time(date.getTime());
}
//For list
for (String str : arrString) {
DateFormat formatter = new SimpleDateFormat("hh:mm:ss a");
Date date = formatter.parse(str);
//Populate the LIST
listTime.add(new Time(date.getTime()));
}