Pages

Monday 25 March 2013

Selenium : Get Date and Time of a specific timezone

Have we come across such a situation where we need to fetch Server date and time which is located in US/Canada/Russia/French etc. and do some activities with that in Selenium.

If yes, you are just in the right place as we are going to discuss something similar which will help us fetch date and time particular to a specific timezone. We will use 2 built-in java classes in order to satisfy our need :-

  1. Date - It represents a specific instant in time, with millisecond precision.
  2. SimpleDateFormat - It's a concrete class for formatting and parsing dates in a locale-sensitive manner.


Code snippet to use :-


// Locale date and time
Date date = new Date();  
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd-yyyy hh:mm a");
        
// Get US/Eastern time
formatter.setTimeZone(TimeZone.getTimeZone("US/Eastern")); 
// Prints the date in the US timezone  
System.out.println("US/Eastern date & time : " +formatter.format(date));  
        

// Set the formatter to use a different timezone  
formatter.setTimeZone(TimeZone.getTimeZone("IST"));  
// Prints the date in the IST timezone  
System.out.println("India date & time : " +formatter.format(date));


How to get all available Time-zones?


// To get all available Time-zones
String[] allTimeZones = TimeZone.getAvailableIDs();   
for (int i = 0; i < allTimeZones.length; i++) 
{  
    System.out.println(allTimeZones[i]); 
}

Hope it helps!! :D

No comments:

Post a Comment