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..

No comments: