Make sure to subscribe to our newsletter and be the first to know the news.
Make sure to subscribe to our newsletter and be the first to know the news.
When you work with project which have involvement of more than one countries you need to work on the date and time and timezone of other countries.
This blog post we are going to learn how to convert you timezone to another countries or states timezone
The code below will help you to fetch all the available TimeZone
import java.util.*;
class GetTimeZones
{
public static void main(String[] args)
{
String[] ids=TimeZone.getAvailableIDs();
for(String id:ids)
{
System.out.println(id);
}
}
}
In this code we will convert our local date and time to TimeZone of Africa/Johannesburg
import java.util.*;
import java.text.*;
class ConvertTimeZone
{
public static void main(String[] args)
{
String format="dd-M-yyyy hh:mm:ss a";
SimpleDateFormat dateFormat=new SimpleDateFormat(format);
Date dt=new Date();
String defaultTZ=TimeZone.getDefault().getID();
System.out.println(defaultTZ);
Calendar cal=new GregorianCalendar();
cal.setTime(dt);
System.out.println("Date:"+dateFormat.format(cal.getTime()));
System.out.println("TimeZOne:"+cal.getTimeZone().getID());
System.out.println("Timezone Name:"+cal.getTimeZone().getDisplayName());
TimeZone jnbTZ=TimeZone.getTimeZone("Africa/Johannesburg");
SimpleDateFormat jnbFormat=new SimpleDateFormat(format);
jnbFormat.setTimeZone(jnbTZ);
cal.setTimeZone(jnbTZ);
System.out.println("After Conversion");
System.out.println("Date:"+jnbFormat.format(cal.getTime()));
System.out.println("TimeZOne:"+cal.getTimeZone().getID());
System.out.println("Timezone Name:"+cal.getTimeZone().getDisplayName());
}
}
You can checkout the execution of the code in the video below