Skip to main content

Handling Dates in Java

Date is one of the Important Variable type in Java, Generally we use following actions with Dates while Automating the application

1) Read and Write date in Different Format

When we read date from browser, it is String type Variable. which is not suitable for perform date like operation. so that we need to convert the string to Date We can convert the string to date using SimpleDateFormat Below is different patterns used

LetterDescriptionExamples
yYear2013
MMonth in yearJuly, 07, 7
dDay in month1-31
EDay name in weekFriday, Sunday
aAm/pm markerAM, PM
HHour in day0-23
hHour in am/pm1-12
mMinute in hour0-60
sSecond in minute0-60
Note: If ‘M’ is 3 or more, then the month is interpreted as text, else number
Example 1:

 SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
 String dateString = "07-Jun-2013";
  try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
 } 
  catch (ParseException e) {
  e.printStackTrace();
 }
Output:
Fri Jun 07 00:00:00 MYT 2013
07-Jun-2013

in above case we have String dateString in format dd-MMM-yyyy, so to convert the String to Date in given format we have Created Object formatter of Class SimpleDateFormat.

This class provides various methods but for now out of that parse and format are important for us

  • parse Method takes String in argument and returns Date Object 
  • format Method takes Date in argument and returns formatted String
Example 2:

 
 SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
 SimpleDateFormat parser = new SimpleDateFormat("dd/MMM/yyyy");
 String dateString = "31-10-2013";
  try {
    Date date = formatter.parse(dateInString);
    System.out.println(parser.format(date));
 } 
  catch (ParseException e) {
  e.printStackTrace();
 }
Output:
31/Oct/2013

In Example 2, we are converting the format of the given Date String by using separate SimpleDateFormat for parsing and formatting.


2) Compare Dates


To compare dates we use Date.compareTo(), this is the classic method to compare dates in Java. the method returns the results as follows.
  • Return value is 0 if both dates are equal.
  • Return value is greater than 0 , if Date is after the date argument.
  • Return value is less than 0, if Date is before the date argument.
 
try{
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
  Date date1 = sdf.parse("2009-12-31");
  Date date2 = sdf.parse("2010-01-31");
  System.out.println(sdf.format(date1));
  System.out.println(sdf.format(date2));
  if(date1.compareTo(date2)>0){
    System.out.println("Date1 is after Date2");
  }else if(date1.compareTo(date2)<0){
    System.out.println("Date1 is before Date2");
  }else if(date1.compareTo(date2)==0){
    System.out.println("Date1 is equal to Date2");
  }else{
    System.out.println("How to get here?");
  }
  }catch(ParseException ex){
 ex.printStackTrace();
}

3) Find Difference between two dates


The best way to get difference between two dates is to get difference in milliseconds and convert them in to required format(days, hours, min, seconds)
  • 1000 milliseconds = 1 second
  • 60 seconds = 1 minute
  • 60 minutes = 1 hour
  • 24 hours = 1 day
I have tried explained in below example.

String dateStart = "01/14/2012 09:29:58";
String dateStop = "01/15/2012 10:31:48";
 
  //HH converts hour in 24 hours format (0-23), day calculation
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
 
Date d1 = null;
Date d2 = null;
 
try {
  d1 = format.parse(dateStart);
  d2 = format.parse(dateStop);
 
   //in milliseconds
  long diff = d2.getTime() - d1.getTime();
 
  long diffSeconds = diff / 1000 % 60;
  long diffMinutes = diff / (60 * 1000) % 60;
  long diffHours = diff / (60 * 60 * 1000) % 24;
  long diffDays = diff / (24 * 60 * 60 * 1000);
 
  System.out.print(diffDays + " days, ");
  System.out.print(diffHours + " hours, ");
  System.out.print(diffMinutes + " minutes, ");
  System.out.print(diffSeconds + " seconds.");
 
}
catch (Exception e)
{
  e.printStackTrace();
}

hope this will help you some where....

Keep Automating..
Post a Comment

Popular posts from this blog

Alternate Way for sendKeys

One of my friend called me yesterday, he had an interview on Selenium WebDriver and got confused on 1 Question.

What is an alternative for sendKeys Method in WebDriver? I also got stammered on this and thought in mind
Why the hell do we need this? There are below possible reason that I could find, When we need any alternative to sendKeys.
When the Text element is disabled or locked, sendKeys can not set the value in text field.
(in my opinion, this is not the correct way of Automation, because the element is locked or disabled by intend to not allow any text insertion)When we want to write huge text as input... that time the way WebDriver work, by sending Series of characters from String one by one, and Which is Very time consuming. so to minimize that time we can use this alternate method So now we have above two problems with sendKeys ......
Solution!!! The best alternative I found is JavaScript
Way 1 to Execute Script WebDriver driver = new FirefoxDriver(); driver…

Selecting Date on JQuery Datepicker

Hello Friends,

In this post we will see how to select specific date in JQuery Datepicker.

Its very easy to enter date as text by .sendKeys() method, but mostly when application uses JQuery Datepicker, it disables typing on the text-box. the text-box sets to read only.

While automating such screens we need to write logic which can interact with Datepicker and selects desired date.

Consider below example of Datepicker.


Html code for above example is


To automate this, we first break apart a problem.
Decide which date we want to set Read the current date from datepicker Calculate difference between both dates in Months(difference will positive in case of set date is in future respective to current date & will negative when set date is in past respective to current date of datepicker) Set loop depends on month difference and navigate the datepicker to specific month Select the Day. 
Lets implement the above logic.
Note: we have used Joda Date Time Library for calculate date and time …

XPATH Basics....

XPATH Basics...
XPath is a text syntax for locating parts of HTML document XPath contains a library of standard functions which helps to locate the WebElement XPath is a W3C recommendation
XPath uses path expressions to select WebElement or sets of WebElements in Web page. These expressions look very much like the expressions you see when you work with a traditional computer file system. like c:\MyFolder\another_folder\myFile.txt
XPATH terminologies Nodes While using Selenium WebDriver, we come across following three types of nodes
elementattributetext Look at below HTML code sample
Link to GoogleLink to YahooLink to FaceBook here div, a are element nodes (element is the basically type of WebElement). Attribute nodes for div element is class and its value is myLink"a" element has text nodes as Link to Google, Link to Yahoo, Link to FaceBook Relationship of Nodes There are various relations available in XPATH but as a selenium user we must have knowledge of below relations…