Site icon TestingDocs.com

Write a program to convert date format from one Timezone to another?

Introduction

Before writing a simple program to convert date format, we will look at some Java classes which will be useful for the program. The class Date represents a specific instant in time, with millisecond precision. We can use DateFormat class to format and parse date strings.

DateFormat

DateFormat is an abstract class for date/time formatting sub classes which formats and parses dates or time in a language-independent manner. The date/time formatting subclass, such as SimpleDateFormat, allows for formatting (i.e., date → text), parsing (text → date), and normalization. The date is represented as a Date object or as the milliseconds since January 1, 1970, 00:00:00 GMT. This is the standard base time known as “the epoch”.

SimpleDateFormat is a concrete subclass of DateFormat that allows you to choose any user-defined patterns for date-time formatting.

TimeZone

TimeZone represents a time zone offset, and also figures out daylight savings. Western countries advance the clock reading by one hour ahead during the summer months. In Most cases, you get TimeZone using getDefault which creates a TimeZone based on the time zone where the code is running. For example, for a program running in India , getDefault creates TimeZone object based on Indian Standard Time ( IST )

You can also get TimeZone using getTimeZone along with a time zone ID. For example, the time zone ID for the U.S. Pacific Time zone is “America/Los_Angeles”.

To get U.S. Pacific Time object, we can use:

TimeZone tz = TimeZone.getTimeZone(“America/Los_Angeles”);

or

TimeZone tz = TimeZone.getTimeZone(“PST”);

 

 

 

 

Sample Code

import java.util.*;
import java.text.*;

public class TimeZoneConverterExample{

public static void main(String args[]){

Date date = new Date();
 Scanner in = new Scanner(System.in);
 System.out.println("Enter your TimeZone| Sample CST , IST , GMT etc");
 String inputTimeZone = in.next();
 System.out.println("Enter TimeZone Time & Date to Converted...");
 String outputTimeZone = in.next();

DateFormat inputFormat = new SimpleDateFormat();
 DateFormat outputFormat = new SimpleDateFormat();

TimeZone inputTime = TimeZone.getTimeZone(inputTimeZone);
 TimeZone outputTime = TimeZone.getTimeZone(outputTimeZone);

inputFormat.setTimeZone(inputTime);
 outputFormat.setTimeZone(outputTime);

System.out.println("Time in TimeZone " + inputTimeZone + " is :" + inputFormat.format(date));
 System.out.println("Time in TimeZone " + outputTimeZone + " is :" +outputFormat.format(date));

in.close();
 }
}

 

Exit mobile version