Java Date and Time interview questions




In this tutorial we will see about using Java Date and Time-stamp interview questions as,
1. Getting current local Date and Time
2. Converting current local Date and Time to GMT Date and Time
3. Convert String to Date and Time
4. Convert Date and Time to String
5. Adding N days with current Date and Time
6. Subtracting N days with current Date and Time
7. Change Date and Time format
8. Calculate difference between 2 Date
9. Compare 2 Dates

Lets start with simple examples for all above question on Java Date and Time. In all examples we will be using
SimpleDateFormat()
parse()
format()



1. Getting current local Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        System.out.println("Current Date & Time : "+date);
    }
}

OUTPUT:

Current Date & Time : Sun Mar 17 01:17:30 IST 2013



2. Converting current local Date and Time to GMT Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        Date date = new Date();
        DateFormat gmtFor = new SimpleDateFormat();
        TimeZone gmtTime = TimeZone.getTimeZone("GMT");
          
        gmtFor.setTimeZone(gmtTime);
        System.out.println("Current Date & Time : "+date.toString());
        System.out.println("GMT Time & Date     : " + gmtFor.format(date));
    }
}

OUTPUT:


Current Date & Time : Sun Mar 17 01:29:09 IST 2013
GMT Date & Time     : 3/16/13 7:59 PM



3. Convert String to Date and Time

public class MyDateTimeTest {
    public static void main(String[] args) {
        String myDateTime = "2013-03-17 12:45:56";
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date convertedDateTime = df.parse(myDateTime);
            System.out.println("DATE : "+df.format(convertedDateTime));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

OUTPUT:
DATE : 2013-03-17 12:45:56




4. Convert Date and Time to String

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date convertedDateTime = new Date();
        String dateInString = df.format(convertedDateTime);
        System.out.println("DATE : "+dateInString);
    }
}

OUTPUT:

DATE : 2013-03-17 02:03:09



5. Adding N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Adding 10 days with current Date
            System.out.println("CURRENT DATE              : "+df.format(currentDateTime));
            System.out.println("DATE AFTER ADDING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE              : 2013-03-17 02:17:24
DATE AFTER ADDING 10 DAYS : 2013-03-27 02:17:24



6. Subtracting N days with current Date and Time 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date currentDateTime = new Date();
        Date newDate = null;
        try {
            newDate = df.parse(df.format(currentDateTime));
            newDate = addNDays(newDate, 10); // Subtracting 10 days with current Date
            System.out.println("CURRENT DATE                   : "+df.format(currentDateTime));
            System.out.println("DATE AFTER SUBTRACTING 10 DAYS : "+df.format(newDate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    
    public static Date addNDays(Date date, int days) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.add(Calendar.DATE, days*-1); 
        return cal.getTime();
    }
}

OUTPUT:

CURRENT DATE                   : 2013-03-17 02:20:12
DATE AFTER SUBTRACTING 10 DAYS : 2013-03-07 02:20:12



7. Change Date and Time format 

public class MyDateTimeTest {
    public static void main(String[] args) {
        DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        DateFormat df2 = new SimpleDateFormat("dd/MMM/yyyy HH:mm:ss aa");
    
        Date currentDateTime = new Date();
        System.out.println("CURRENT DATE      : "+df1.format(currentDateTime));
        System.out.println("NEW FORMATED DATE : "+df2.format(currentDateTime));        
    }
}

OUTPUT:

CURRENT DATE      : 2013-03-17 02:25:59
NEW FORMATED DATE : 17/Mar/2013 02:25:59 AM



8. Calculate difference between 2 Date 

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        long diff = date1.getTime() - date2.getTime();
        
        System.out.println("DATE DIFF : "+(diff/ (1000 * 60 * 60)) +" hours");
    }
}

OUTPUT:

DATE-1 : 2013-03-17 02:38:54
DATE-2 : 2013-03-15 02:38:45
DATE DIFF : 48 hours



9. Compare 2 Dates

public class MyDateTimeTest {
    public static void main(String[] args) throws ParseException {
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String otherDate = "2013-03-15 02:38:45";
        
        Date date1 = new Date();
        Date date2 = df.parse(otherDate);
        
        System.out.println("DATE-1 : "+df.format(date1));
        System.out.println("DATE-2 : "+df.format(date2));    
        
        if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is after Date-2");
            }else if(date1.compareTo(date2) > 0){
                System.out.println("Date-1 is before Date-2");
            }else if(date1.compareTo(date2) == 0){
                System.out.println("Date-1 is equal to Date-2");
            }
        }



OUTPUT:
DATE-1 : 2013-03-17 02:42:37
DATE-2 : 2013-03-15 02:38:45
Date-1 is after Date-2






Java 7 - try-with-resources

In earlier tutorials we have seen couple of Java 7 features like Underscore in numeric literals, Switch Case with non-primitive data-type and Exception handling with multi-catch.

In this tutorial we will see about try-with-resources is a one of the fine feature added in Java 7.
 

For example if we need to allocate a resource for file handling or database connectivity then we need to explicitly close the resource which we have opened in our try block. In those cases it will be tedious to handle lot of resource management manually. In some of the cases we will have try with finally block where we will check for the resource closing. No matter whether the to resource has allocated or not finally block will be executed automatically for all time. Below is the simple example from earlier Java 7 as how we used to handle resources by using file handling.
 



public class MyOldFileHandling {
    public static void main(String[] arg){
        FileInputStream fstream = null;
        DataInputStream istream = null;
        BufferedReader breader = null;
        try {            
            fstream = new FileInputStream("test.txt");
            istream = new DataInputStream(fstream);
            breader = new BufferedReader(new InputStreamReader(istream));
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally{
            try{
                /* 
                 * Explicitly all resources need to be closed in 
                 * earlier java versions 
                */

                if(fstream != null)fstream.close();
                if(istream != null)istream.close();
                if(breader != null)breader.close();
            }catch(IOException ioe){
                ioe.printStackTrace();;
            }
        }
    }
}



In above program we can see explicitly programmers need to handle resource closing under finally block, whether resource has or not finally block will be executed compulsory. 

But in Java 7 onwards try-catch-resource feature introduced and programmer need not to worry about resource management once when we add resource in try statement as like bellow.
 



try(FileInputStreamfstream = new FileInputStream("test.txt")) {
.
.
}



Above statement will have same functionality of FileInputStream of our above program. Where as here resource closing close() method will be automatically called once try block completed. Even we can multiple resource under single try block as like below.
 



try(FileInputStreamfstream = new FileInputStream("test.txt");
    DataInputStream istream = new DataInputStream(fstream);
    BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {
.
.
}

Below example will show same above program will be handled using try-with-resource using Java 7.
 



public class MyNewFileHandling {
        public static void main(String[] arg){
        
        try (FileInputStream fstream = new FileInputStream("test.txt");            
             DataInputStream istream = new DataInputStream(fstream);
             BufferedReader breader = new BufferedReader(new InputStreamReader(istream))) {            
            
            String line;
            while ((line = breader.readLine()) != null) {
                System.out.println (line);
            }            
        } catch (IOException ex) {
            ex.printStackTrace();
        } 
    }
}




 

Drawing image border using Java Code





In our last tutorial we have seen how to re-size image using Java code. In this tutorial we will see how to draw a border in the image using Java code.



import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageBorder {

    public static void main(String[] args) {
        new ImageBorder().createBorderImage("e:\\tree.jpg", "e:\\tree_border.jpg");
    }
    
    public void createBorderImage(String oriImgUrl, String saveLocFilePath){
        try {
            int borderColor = 0x99FF0000; //Red color
            BufferedImage image = ImageIO.read(new File(oriImgUrl));
            for(int i=0;i < image.setRGB(0, i, borderColor);
                image.setRGB(image.getWidth()-1, i, borderColor);
            }
            for(int i=0;i < image.setRGB(i, 0, borderColor);
                image.setRGB(i, image.getHeight()-1, borderColor);
            }
            ImageIO.write(image, "png"new File(saveLocFilePath));
            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}






Image resizing using Java code




We will see how to re-size image using Java program. Below program will explains you about resizing image using Java code. Method resizeMyImage() will take necessary parameters like re-size image name, original image and resize image sizes (width and height).



import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;

public class ImageResize {
    public static void main(String[] args) {
        // resize_image_name, original_image, resize_image_sizes 
        new ImageResize().resizeMyImage("e:\\rat_resized.jpg", "e:\\rat.jpg", "200", "93");
    }
    
    private void resizeMyImage(String resizeImg, String filePath, String w, String h){
        if(new File(filePath).exists()){
            imageResize(filePath, Integer.parseInt(w) , Integer.parseInt(h), resizeImg);
            System.out.println("Resize completed....");
        }else{
            System.out.println("Original file not exist....");
        }        
    }
    
    public void imageResize(String oriImgUrl, int width, int heigth, String saveLocFilePath){
        try {            
            File f = new File(oriImgUrl);
            BufferedImage image = ImageIO.read(f);
            BufferedImage resizeImage = resize(image, width, heigth);
            ImageIO.write(resizeImage, "jpg"new File(saveLocFilePath));            
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    
    private static BufferedImage resize(BufferedImage image, int width, int height) {
        BufferedImage resizedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(image, 0, 0, width, height, null);
        g.dispose();
        return resizedImage;
    }
}






 

Sending SMS through JAVA code

 
In this tutorial we will see about sending SMS through Java code in India. For this first we need to chose some SMS gateway for sending SMS across India and other countries. I have chose www.SMSZone.in for this and will see small example for sending SMS.

Steps to get subscribed:
  • 1. For subscribing we need to provide registered Mobile no. and company / personal details. 
  • 2. Once subscribed need to decide whether we are going to use SMS for promotional or non-promotional activities. 
  • 3. Based on that we need decide our tariff plan and SMS template formats. 
  • 4. Next we need to chose the SenderId for SMS, like JDISCO (only 6 letters are allowed)
  • 5. Next you chose any language for sending SMS like Java, .NET, PHP etc.,


Lets see small Java code for sending SMS by using above SMS gateway.



public class SendSMS {
  
  // SMS Gateway API
  static String SMSApi = "http://www.smszone.in/sendsms.asp?page=SendSmsBulk&username=91XXXX12XXXX&password=XXXX&number=<PHONE>&message=<MSG>&SenderId=JDISCO";
  
  //List of mobile numbers to send SMS
  static String phoneNos = "91XXXX54XXXX, 91XXXX56XXXX";
  
  // SMS text
  static String smsText = "Hi All, Welcome to JavaDiscover";
    
  public static void main(String[] args) {
    try{
      String url = SMSApi.replace("<PHONE>", phoneNos).replace("<MSG>", smsText).replaceAll(" ""%20");
      String smsApiResponse = sendMySMS(url);
      System.out.println(smsApiResponse);
    }catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  public static String sendMySMS(String url){
    StringBuilder output = new StringBuilder();
    try{
      URL hp = new URL(url);
      System.out.println(url);
      URLConnection hpCon = hp.openConnection()
      BufferedReader in = new BufferedReader(new InputStreamReader(hpCon.getInputStream()));
      String inputLine;
      while ((inputLine = in.readLine()) != null)
        output.append(inputLine);
      in.close();
    }catch (Exception e) {
      e.printStackTrace();
    }
    return output.toString();
  }
}




Change you Username, password, phone number and Senderid accordingly. 





Using Java TreeMap

 
Today we will see about one of the important interface in Java called Map interface. Map interface and derived classes are in java.util.Map package and Map uses simple data structure that contains Key and Value. Always key must be unique Object and its uses Hashing to identify the correct Key and corresponding Value in the Sequential array (Used to call as bucket). 

Under Map interface lot of derived classes and lets see TreeMap in this tutorial.

TreeMap:
       TreeMap is an important class which implements the Map interface. As same as HashMap TreeMap also uses the Key/ Value to store the data in a sorted order. TreeMap can be created in 2 ways as natural sorted order or custom sorted order by using Comparator. Below we will see small examples for all these types.


Example: TreeMap using natural sort.


public class TreeMapTest {
 public static void main(String[] args) {
  TreeMap<String, String> map = new TreeMap<String, String>();
  map.put("4", "Delhi");
  map.put("3", "Mumbai");
  map.put("5", "Chennai");
  map.put("1", "Culcutta");
  map.put("2", "Bangalore");
  
  // Sorted TreeMap
  System.out.println("Sorted TreeMap values....");
  for (Map.Entry<String, String> entry : map.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting size TreeMap
  System.out.println("\nSize of TreeMap :: "+map.size());
  
  // Contains Key in TreeMap
  System.out.println("\nKey Contains (15) : "+map.containsKey("15"));
  System.out.println("Key Contains (4) : "+map.containsKey("4"));
    
  // Contains Value in TreeMap
  System.out.println("\nValue Contains (Delhi) : "+map.containsValue("Delhi"));
  System.out.println("Value Contains (Ney York) : "+map.containsValue("New York"));
    
  // Getting Reversing TreeMap
  NavigableMap<String, String> revMap = map.descendingMap();
  System.out.println("\nReverse TreeMap values....");
  for (Map.Entry<String, String> entry : revMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Get sub portion of map to subMap
  SortedMap<String, String> subMap = map.subMap("2","4");
  System.out.println("\nSub portion TreeMap values....");
  for (Map.Entry<String, String> entry : subMap.entrySet()) {
   System.out.println("KEY : "+entry.getKey() +" - VALUE : "+entry.getValue());
  }
  
  // Getting first Key and Entry in TreeMap
  System.out.println("\nFirst Key in TreeMap : "+map.firstKey());
  System.out.println("First Entry in TreeMap : "+map.firstEntry());
  
  // Getting last Key and Entry in TreeMap
  System.out.println("\nLast Key in TreeMap : "+map.lastKey());
  System.out.println("Last Entry in TreeMap : "+map.lastEntry());
  
  // Removing data from TreeMap
  map.remove("3");
  System.out.println("\nTreeMap size after removing 1 element : "+map.size());
  
  // Checking TreeMap is empty or not
  System.out.println("\nTreeMap empty or not : "+map.isEmpty());
  
  // Clearing complete TreeMap
  map.clear();
  System.out.println("\nTreeMap size after clearing all values : "+map.size());
  System.out.println("TreeMap empty or not : "+map.isEmpty());
  
 }
}



OUTPUT:


Sorted TreeMap values....
KEY : 1 - VALUE : Culcutta
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai
KEY : 4 - VALUE : Delhi
KEY : 5 - VALUE : Chennai

Size of TreeMap :: 5

Key Contains (15) : false
Key Contains (4) : true

Value Contains (Delhi) : true
Value Contains (Ney York) : false

Reverse TreeMap values....
KEY : 5 - VALUE : Chennai
KEY : 4 - VALUE : Delhi
KEY : 3 - VALUE : Mumbai
KEY : 2 - VALUE : Bangalore
KEY : 1 - VALUE : Culcutta

Sub portion TreeMap values....
KEY : 2 - VALUE : Bangalore
KEY : 3 - VALUE : Mumbai

First Key in TreeMap : 1
First Entry in TreeMap : 1=Culcutta

Last Key in TreeMap : 5
Last Entry in TreeMap : 5=Chennai

TreeMap size after removing 1 element : 4

TreeMap empty or not : false

TreeMap size after clearing all values : 0
TreeMap empty or not : true



In above example we can see automatically TreeMap sorted and also other methods in TreeMap class.

Next we will see simple example using custom sorting using Comparator.

Example: TreeMap using custom sort - Comparator.




public class TreeMapUsingCustomComparator {
 
 public static void main(String a[]){
  TreeMap<Worker,String> map = new TreeMap<Worker, String>(new MyNameComp());
  map.put(new Worker("david",5000), "david");
  map.put(new Worker("joy",2000), "joy");
  map.put(new Worker("abel",7000), "abel");
  map.put(new Worker("ruby",9000), "ruby");
  
  for (Map.Entry<Worker, String> entry : map.entrySet()) {
   System.out.println("KEY : "+ entry.getKey() +" \t VALUE : "+entry.getValue());
  }
 }
}




public class Worker{
    
    private String name;
    private int salary;
    
    public Worker(String name, int salary){
        this.name = name;
        this.salary = salary;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getSalary() {
        return salary;
    }
    public void setSalary(int salary) {
        this.salary = salary;
    }
    public String toString(){
        return "("+this.name+":"+this.salary+")";
    }
}




public class MyNameComp implements Comparator<Worker>{
    public int compare(Worker obj1, Worker obj2) {
        return obj1.getName().compareTo(obj2.getName());
    }
}



OUTPUT: 


KEY : (abel:7000)   VALUE : abel
KEY : (david:5000)   VALUE : david
KEY : (joy:2000)   VALUE : joy
KEY : (ruby:9000)   VALUE : ruby