Showing posts with label Convert Date/Time for given Timezone - java. Show all posts
Showing posts with label Convert Date/Time for given Timezone - java. Show all posts

How to convert DateTime to different Timezone's

Convert the given date, time to a different timezone along with 12-hour clock format. Lets see simple java example to convert the given string to Date and with local/Default(IST) time to 2 different timezone along with 12-hour clock format (AM/PM).

Convert Date/Time for given Timezone - java



import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class DateTime {

 public static void main(String[] args) {
  
  String sDate1="25-03-2018 13:34:56";  
  SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
  
  // Converting string to Date() with specified date format.
  Date date = null;
  try {
   date = sdf.parse(sDate1);
  } catch (ParseException e) { 
   e.printStackTrace();
   // If any format error pick current datetime
   date = new Date();
  } 
  sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss a");
  Calendar calendar = Calendar.getInstance();
  calendar.setTime(date);
  
  System.out.println("Default IST Time      : "+sdf.format(calendar.getTime()));    
  
  
  // Changing TimeZone to America/New_York
  sdf.setTimeZone(TimeZone.getTimeZone("America/New_York"));
  System.out.println("America/New_York Time : "+sdf.format(calendar.getTime()));    

  
  // Changing TimeZone to Australia/Sydney
  sdf.setTimeZone(TimeZone.getTimeZone("Australia/Sydney"));
  System.out.println("Australia/Sydney Time : "+sdf.format(calendar.getTime()));
  
 }
}


OUTPUT:


Default IST Time      : 25-Mar-2018 01:34:56 PM
America/New_York Time : 25-Mar-2018 04:04:56 AM
Australia/Sydney Time : 25-Mar-2018 07:04:56 PM