The following sample XML shows how to set up a single Quartz job with multiple cron triggers in a jobs.xml configuration file. The scheduled job is called SampleJob and it has two triggers Trigger1 and Trigger2. The job has its own parameter and each trigger has its own parameter. Trigger1 runs every day at 9:00 and Trigger2 runs every day at 10:00. This works for sure with Quartz version 1.8.3.
<?xml version='1.0' encoding='utf-8'?>
<job-scheduling-data xmlns="http://www.quartz-scheduler.org/xml/JobSchedulingData"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.quartz-scheduler.org/xml/JobSchedulingData http://www.quartz-scheduler.org/xml/job_scheduling_data_1_8.xsd"
version="1.8">
<schedule>
<job>
<name>SampleJob</name>
<group>DEFAULT</group>
<job-class>com.xyz.SampleJob</job-class>
<job-data-map>
<entry>
<key>Param1</key>
<value>HOT</value>
</entry>
</job-data-map>
</job>
<trigger>
<cron>
<name>Trigger1</name>
<group>DEFAULT</group>
<job-name>SampleJob</job-name>
<job-group>DEFAULT</job-group>
<job-data-map>
<entry>
<key>Param2</key>
<value>Y</value>
</entry>
</job-data-map>
<cron-expression>0 0 9 * * ?</cron-expression>
</cron>
</trigger>
<trigger>
<cron>
<name>Trigger2</name>
<group>DEFAULT</group>
<job-name>SampleJob</job-name>
<job-group>DEFAULT</job-group>
<job-data-map>
<entry>
<key>Param2</key>
<value>N</value>
</entry>
</job-data-map>
<cron-expression>0 0 10 * * ?</cron-expression>
</cron>
</trigger>
</schedule>
</job-scheduling-data>
Piece of Cake!!!
Saturday, August 21, 2010
Friday, August 20, 2010
Place an Inline Link to an Amazon Product with Your Associates ID
In addition to using the Amazon widgets, links, and banners directly available in your Amazon Associates account to place Amazon advertisements on your website or blog, you can also create your own inline links with a simple trick. Keep reading to see how...
Step 0: Figure out your Amazon associates ID (tracking ID). Log into your associates account, and in the upper-left corner of the webpage you should see your Tracking ID. Mine is obscuclari-20, which I will use below. You will need to use YOUR tracking ID.
Step 1: Get the URL of the webpage on Amazon.com that you want to link to. For example, here's a link to some fish food:
http://www.amazon.com/Tetra-BettaMin-Flakes-0-81-Ounces/dp/B00025K10M/ref=sr_1_11?ie=UTF8&s=pet-supplies&qid=1282284515&sr=1-11
Step 2: Add your Amazon associates ID (tracking ID) to the link. This is so that Amazon knows that someone arrived at Amazon.com from your website. All you have to do is add &tag=obscuclari-20 to the end of the link in step 1, where obscuclari-20 is replaced by YOUR Tracking ID. The link in Step 1 should then look like this:
http://www.amazon.com/Tetra-BettaMin-Flakes-0-81-Ounces/dp/B00025K10M/ref=sr_1_11?ie=UTF8&s=pet-supplies&qid=1282284515&sr=1-11&tag=obscuclari-20
Step 3: Test it! Add your inline link to your website, click it and verify that your Tracker ID properly appears in the URL in the browser's address bar. Here's the inline link I just created: Click me!
I have another working example here, where I've added my own inline links to some harddrive hardware, and it's been working out for me for well over a year.
Piece of Cake!!!
See also: How to Add an Amazon Widget to Your Blog to Make Some Extra Cash
Step 0: Figure out your Amazon associates ID (tracking ID). Log into your associates account, and in the upper-left corner of the webpage you should see your Tracking ID. Mine is obscuclari-20, which I will use below. You will need to use YOUR tracking ID.
Step 1: Get the URL of the webpage on Amazon.com that you want to link to. For example, here's a link to some fish food:
http://www.amazon.com/Tetra-BettaMin-Flakes-0-81-Ounces/dp/B00025K10M/ref=sr_1_11?ie=UTF8&s=pet-supplies&qid=1282284515&sr=1-11
Step 2: Add your Amazon associates ID (tracking ID) to the link. This is so that Amazon knows that someone arrived at Amazon.com from your website. All you have to do is add &tag=obscuclari-20 to the end of the link in step 1, where obscuclari-20 is replaced by YOUR Tracking ID. The link in Step 1 should then look like this:
http://www.amazon.com/Tetra-BettaMin-Flakes-0-81-Ounces/dp/B00025K10M/ref=sr_1_11?ie=UTF8&s=pet-supplies&qid=1282284515&sr=1-11&tag=obscuclari-20
Step 3: Test it! Add your inline link to your website, click it and verify that your Tracker ID properly appears in the URL in the browser's address bar. Here's the inline link I just created: Click me!
I have another working example here, where I've added my own inline links to some harddrive hardware, and it's been working out for me for well over a year.
Piece of Cake!!!
See also: How to Add an Amazon Widget to Your Blog to Make Some Extra Cash
Sunday, August 15, 2010
Java Ant - Build .War file with Auto-Incrementing Build Number
To auto-increment a build number while building a .war file with ANT, we can create a .properties file using the propertyfile ant task in combination with the buildnumber ant task. The buildnumber task creates a build.version file and increments the build number contained within during each build. The following task in my Ant build file creates a properties file with auto-incrementing build information along with the person who built the .war file and a timestamp. The ${major.minor.version} variable comes out of a build.properties file I use for the build.
<target name="buildinfo">  
<buildnumber />
<propertyfile file="${build.dir}/build-info.properties"
comment="This file is automatically generated - DO NOT EDIT">
<entry key="Built-By" value="${user.name}"/>
<entry key="Build-Version" value="${major.minor.version}-b${build.number}"/>
</propertyfile>
</target>
Here is the contents of the build-info.properties file:
See also:
Hello World Java Web Application in Eclipse (Part 3)
<target name="buildinfo">  
<buildnumber />
<propertyfile file="${build.dir}/build-info.properties"
comment="This file is automatically generated - DO NOT EDIT">
<entry key="Built-By" value="${user.name}"/>
<entry key="Build-Version" value="${major.minor.version}-b${build.number}"/>
</propertyfile>
</target>
Here is the contents of the build-info.properties file:
#This file is automatically generated - DO NOT EDIT #Sun Aug 15 17:04:03 CEST 2010 Build-Version=0.1-b15 Built-By=tim
See also:
Hello World Java Web Application in Eclipse (Part 3)
Java Ant - Build Jar with Auto-Incrementing Build Number
To auto-increment a build number while building a Jar file with Ant, we can use the "manifest" Ant task with the "buildnumber" task. The buildnumber task creates a build.version file and increments the build number contained within during each build. The build number along with other information can be integrated right into the MANIFEST.MF file (or anywhere else for that matter). Here is the Ant code I use to auto-increment the build number during a Jar file build:
<target name="manifest">
<echo>Creating manifest</echo>
<mkdir dir="${build.dir}/META-INF"/>
<buildnumber file="build.version"/>
<tstamp>
<format property="timestamp" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build.dir}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Build-Version" value="0.4-b${build.number}"/>
<attribute name="Build-Date" value="${timestamp}"/>
</manifest>
</target>
Here is the contents of the MANIFEST.MF file:
See also:
Hello World Java Web Application in Eclipse (Part 3)
<target name="manifest">
<echo>Creating manifest</echo>
<mkdir dir="${build.dir}/META-INF"/>
<buildnumber file="build.version"/>
<tstamp>
<format property="timestamp" pattern="yyyy-MM-dd HH:mm:ss" />
</tstamp>
<manifest file="${build.dir}/META-INF/MANIFEST.MF">
<attribute name="Built-By" value="${user.name}"/>
<attribute name="Build-Version" value="0.4-b${build.number}"/>
<attribute name="Build-Date" value="${timestamp}"/>
</manifest>
</target>
Here is the contents of the MANIFEST.MF file:
Manifest-Version: 1.0 Ant-Version: Apache Ant 1.7.1 Created-By: 1.5.0_24-149 (Apple Inc.) Built-By: tim Build-Version: 0.4-b2 Build-Date: 2010-08-15 16:13:49
See also:
Hello World Java Web Application in Eclipse (Part 3)
Sunday, August 8, 2010
Error Occured While Converting Date Log4j Slf4j Quartz Tomcat Java
Today I spent way too many hours fixing a bug I ran across while getting Quartz integrated into a Java Webapp running on Tomcat with integrated log4j. The Quartz api uses slf4j logging and Quartz was throwing null pointer exceptions when starting up relating to logging. Below is the solution in my particular case. I hope this helps someone else!
log4j:ERROR Error occured while converting date.
java.lang.NullPointerException
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:488)
at java.lang.StringBuffer.append(StringBuffer.java:302)
at org.apache.log4j.helpers.ISO8601DateFormat.format(ISO8601DateFormat.java:132)
at java.text.DateFormat.format(DateFormat.java:314)
at org.apache.log4j.helpers.PatternParser$DatePatternConverter.convert(PatternParser.java:444)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:64)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:503)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:301)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:159)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:230)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:65)
at org.apache.log4j.Category.callAppenders(Category.java:203)
at org.apache.log4j.Category.forcedLog(Category.java:388)
at org.apache.log4j.Category.log(Category.java:853)
at org.slf4j.impl.Log4jLoggerAdapter.debug(Log4jLoggerAdapter.java:204)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:595)
[] DEBUG org.quartz.simpl.SimpleThreadPool WorkerThread is shut down.
The solution is to replace "ISO8601" in the following log4j.xml file with "yyyy-MM-dd HH:mm:ss.SSS". AHHHHRRRRRRRR!
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{ISO8601}] %-5p %c %m %n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN"/>
<param name="LevelMax" value="FATAL"/>
</filter>
</appender>
log4j:ERROR Error occured while converting date.
java.lang.NullPointerException
at java.lang.AbstractStringBuilder.append(AbstractStringBuilder.java:488)
at java.lang.StringBuffer.append(StringBuffer.java:302)
at org.apache.log4j.helpers.ISO8601DateFormat.format(ISO8601DateFormat.java:132)
at java.text.DateFormat.format(DateFormat.java:314)
at org.apache.log4j.helpers.PatternParser$DatePatternConverter.convert(PatternParser.java:444)
at org.apache.log4j.helpers.PatternConverter.format(PatternConverter.java:64)
at org.apache.log4j.PatternLayout.format(PatternLayout.java:503)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:301)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:159)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:230)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:65)
at org.apache.log4j.Category.callAppenders(Category.java:203)
at org.apache.log4j.Category.forcedLog(Category.java:388)
at org.apache.log4j.Category.log(Category.java:853)
at org.slf4j.impl.Log4jLoggerAdapter.debug(Log4jLoggerAdapter.java:204)
at org.quartz.simpl.SimpleThreadPool$WorkerThread.run(SimpleThreadPool.java:595)
[] DEBUG org.quartz.simpl.SimpleThreadPool WorkerThread is shut down.
The solution is to replace "ISO8601" in the following log4j.xml file with "yyyy-MM-dd HH:mm:ss.SSS". AHHHHRRRRRRRR!
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{ISO8601}] %-5p %c %m %n" />
</layout>
<filter class="org.apache.log4j.varia.LevelRangeFilter">
<param name="LevelMin" value="WARN"/>
<param name="LevelMax" value="FATAL"/>
</filter>
</appender>
Tuesday, August 3, 2010
Get Previous Business Day Date Object in Java
To get a java.util.Date object representing the previous business day,
we can use the java.util.Calendar class. First, create a Calendar
object and set it's time with a Data object. Next, check what day of
the week it is and decrement it accordingly to the previous weekday.
Finally, create a new Date object with the Calendar's getTime()
method.
Here is the output of the example code:
we can use the java.util.Calendar class. First, create a Calendar
object and set it's time with a Data object. Next, check what day of
the week it is and decrement it accordingly to the previous weekday.
Finally, create a new Date object with the Calendar's getTime()
method.
Get Previous Business Day Date Object in Java - Example Code
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; //Java 1.4+ Compatible // // The following example code demonstrates how to determine // the next business day given a Date object. public class GetPreviousBusinessDay { public static void main(String[] args) { Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == Calendar.MONDAY) { calendar.add(Calendar.DATE, -3); } else if (dayOfWeek == Calendar.SUNDAY) { calendar.add(Calendar.DATE, -2); } else { calendar.add(Calendar.DATE, -1); } Date previousBusinessDay = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("EEEE"); System.out.println("Today : " + sdf.format(today)); System.out.println("Previous business day: " + sdf.format(previousBusinessDay)); } }
Here is the output of the example code:
Today : Tuesday Previous business day: Monday
Get Next Business Day Date Object in Java
To get a java.util.Date object representing the next business day, we
can use the java.util.Calendar class. First, create a Calendar object
and set it's time with a Data object. Next, check what day of the week
it is and increment it accordingly to the next weekday. Finally,
create a new Date object with the Calendar's getTime() method.
Here is the output of the example code:
can use the java.util.Calendar class. First, create a Calendar object
and set it's time with a Data object. Next, check what day of the week
it is and increment it accordingly to the next weekday. Finally,
create a new Date object with the Calendar's getTime() method.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; // Java 1.4+ Compatible // // The following example code demonstrates how to determine // the next business day given a Date object. public class GetNextBusinessDay { public static void main(String[] args) { Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK); if (dayOfWeek == Calendar.FRIDAY) { calendar.add(Calendar.DATE, 3); } else if (dayOfWeek == Calendar.SATURDAY) { calendar.add(Calendar.DATE, 2); } else { calendar.add(Calendar.DATE, 1); } Date nextBusinessDay = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("EEEE"); System.out.println("Today : " + sdf.format(today)); System.out.println("Next business day: " + sdf.format(nextBusinessDay)); } }
Here is the output of the example code:
Today : Tuesday Next business day: Wednesday
Get Last Day of Month Date Object in Java
To get a java.util.Date object representing the last day of the month,
we can use the java.util.Calendar class. First, create a Calendar
object and set it's time with a Data object. Next, add one month, set
the day of month to 1, and subtract one day. Finally, create a new
Date object with the Calendar's getTime() method.
Here is the output of the example code:
we can use the java.util.Calendar class. First, create a Calendar
object and set it's time with a Data object. Next, add one month, set
the day of month to 1, and subtract one day. Finally, create a new
Date object with the Calendar's getTime() method.
import java.text.DateFormat; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; //Java 1.4+ Compatible // // The following example code demonstrates how to get // a Date object representing the last day of the month // relative to a given Date object. public class GetLastDayOfMonth { public static void main(String[] args) { Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.add(Calendar.MONTH, 1); calendar.set(Calendar.DAY_OF_MONTH, 1); calendar.add(Calendar.DATE, -1); Date firstDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Today : " + sdf.format(today)); System.out.println("Last Day of Month: " + sdf.format(firstDayOfMonth)); } }
Here is the output of the example code:
Today : 2010-08-03 Last Day of Month: 2010-08-31
Get First Day of Month Date Object in Java
To get a java.util.Date object representing the first day of the
month, we can use the java.util.Calendar class. First, create a
Calendar object and set it's time with a Data object. Next, set the
Calendar's 'day of month' to 1. Finally, create a new Date object with
the Calendar's getTime() method.
Here is the output of the example code:
month, we can use the java.util.Calendar class. First, create a
Calendar object and set it's time with a Data object. Next, set the
Calendar's 'day of month' to 1. Finally, create a new Date object with
the Calendar's getTime() method.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; // Java 1.4+ Compatible // // The following example code demonstrates how to get // a Date object representing the first day of the month // relative to a given Date object. public class GetFirstDayOfMonth { public static void main(String[] args) { Date today = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(today); calendar.set(Calendar.DAY_OF_MONTH, 1); Date firstDayOfMonth = calendar.getTime(); DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("Today : " + sdf.format(today)); System.out.println("First Day of Month: " + sdf.format(firstDayOfMonth)); } }
Here is the output of the example code:
Today : 2010-08-03 First Day of Month: 2010-08-01
Monday, August 2, 2010
Get All Timezones Available in the TimeZone Class in Java
To get all the timezones available in the java.util.TimeZone class in Java, we use the static method TimeZone.getAvailableIDs(). The following example code also sorts them alphabetically and prints them out to the console.
import java.util.Arrays; import java.util.TimeZone; //Java 1.4+ Compatible // // The following example code demonstrates how to display // all available timezones provided by the java.util.TimeZone // class. public class GetAvailableTimezones { public static void main(String[] args) { String[] allTimeZones = TimeZone.getAvailableIDs(); Arrays.sort(allTimeZones); for (int i = 0; i < allTimeZones.length; i++) { System.out.println(allTimeZones[i]); } } }Here is the output of the example code:
ACT AET AGT ART AST Africa/Abidjan Africa/Accra Africa/Addis_Ababa Africa/Algiers Africa/Asmara Africa/Asmera Africa/Bamako Africa/Bangui Africa/Banjul Africa/Bissau Africa/Blantyre Africa/Brazzaville Africa/Bujumbura Africa/Cairo Africa/Casablanca Africa/Ceuta Africa/Conakry Africa/Dakar Africa/Dar_es_Salaam Africa/Djibouti Africa/Douala Africa/El_Aaiun Africa/Freetown Africa/Gaborone Africa/Harare Africa/Johannesburg Africa/Kampala Africa/Khartoum Africa/Kigali Africa/Kinshasa Africa/Lagos Africa/Libreville Africa/Lome Africa/Luanda Africa/Lubumbashi Africa/Lusaka Africa/Malabo Africa/Maputo Africa/Maseru Africa/Mbabane Africa/Mogadishu Africa/Monrovia Africa/Nairobi Africa/Ndjamena Africa/Niamey Africa/Nouakchott Africa/Ouagadougou Africa/Porto-Novo Africa/Sao_Tome Africa/Timbuktu Africa/Tripoli Africa/Tunis Africa/Windhoek America/Adak America/Anchorage America/Anguilla America/Antigua America/Araguaina America/Argentina/Buenos_Aires America/Argentina/Catamarca America/Argentina/ComodRivadavia America/Argentina/Cordoba America/Argentina/Jujuy America/Argentina/La_Rioja America/Argentina/Mendoza America/Argentina/Rio_Gallegos America/Argentina/Salta America/Argentina/San_Juan America/Argentina/San_Luis America/Argentina/Tucuman America/Argentina/Ushuaia America/Aruba America/Asuncion America/Atikokan America/Atka America/Bahia America/Barbados America/Belem America/Belize America/Blanc-Sablon America/Boa_Vista America/Bogota America/Boise America/Buenos_Aires America/Cambridge_Bay America/Campo_Grande America/Cancun America/Caracas America/Catamarca America/Cayenne America/Cayman America/Chicago America/Chihuahua America/Coral_Harbour America/Cordoba America/Costa_Rica America/Cuiaba America/Curacao America/Danmarkshavn America/Dawson America/Dawson_Creek America/Denver America/Detroit America/Dominica America/Edmonton America/Eirunepe America/El_Salvador America/Ensenada America/Fort_Wayne America/Fortaleza America/Glace_Bay America/Godthab America/Goose_Bay America/Grand_Turk America/Grenada America/Guadeloupe America/Guatemala America/Guayaquil America/Guyana America/Halifax America/Havana America/Hermosillo America/Indiana/Indianapolis America/Indiana/Knox America/Indiana/Marengo America/Indiana/Petersburg America/Indiana/Tell_City America/Indiana/Vevay America/Indiana/Vincennes America/Indiana/Winamac America/Indianapolis America/Inuvik America/Iqaluit America/Jamaica America/Jujuy America/Juneau America/Kentucky/Louisville America/Kentucky/Monticello America/Knox_IN America/La_Paz America/Lima America/Los_Angeles America/Louisville America/Maceio America/Managua America/Manaus America/Marigot America/Martinique America/Matamoros America/Mazatlan America/Mendoza America/Menominee America/Merida America/Mexico_City America/Miquelon America/Moncton America/Monterrey America/Montevideo America/Montreal America/Montserrat America/Nassau America/New_York America/Nipigon America/Nome America/Noronha America/North_Dakota/Center America/North_Dakota/New_Salem America/Ojinaga America/Panama America/Pangnirtung America/Paramaribo America/Phoenix America/Port-au-Prince America/Port_of_Spain America/Porto_Acre America/Porto_Velho America/Puerto_Rico America/Rainy_River America/Rankin_Inlet America/Recife America/Regina America/Resolute America/Rio_Branco America/Rosario America/Santa_Isabel America/Santarem America/Santiago America/Santo_Domingo America/Sao_Paulo America/Scoresbysund America/Shiprock America/St_Barthelemy America/St_Johns America/St_Kitts America/St_Lucia America/St_Thomas America/St_Vincent America/Swift_Current America/Tegucigalpa America/Thule America/Thunder_Bay America/Tijuana America/Toronto America/Tortola America/Vancouver America/Virgin America/Whitehorse America/Winnipeg America/Yakutat America/Yellowknife Antarctica/Casey Antarctica/Davis Antarctica/DumontDUrville Antarctica/Mawson Antarctica/McMurdo Antarctica/Palmer Antarctica/Rothera Antarctica/South_Pole Antarctica/Syowa Antarctica/Vostok Arctic/Longyearbyen Asia/Aden Asia/Almaty Asia/Amman Asia/Anadyr Asia/Aqtau Asia/Aqtobe Asia/Ashgabat Asia/Ashkhabad Asia/Baghdad Asia/Bahrain Asia/Baku Asia/Bangkok Asia/Beirut Asia/Bishkek Asia/Brunei Asia/Calcutta Asia/Choibalsan Asia/Chongqing Asia/Chungking Asia/Colombo Asia/Dacca Asia/Damascus Asia/Dhaka Asia/Dili Asia/Dubai Asia/Dushanbe Asia/Gaza Asia/Harbin Asia/Ho_Chi_Minh Asia/Hong_Kong Asia/Hovd Asia/Irkutsk Asia/Istanbul Asia/Jakarta Asia/Jayapura Asia/Jerusalem Asia/Kabul Asia/Kamchatka Asia/Karachi Asia/Kashgar Asia/Kathmandu Asia/Katmandu Asia/Kolkata Asia/Krasnoyarsk Asia/Kuala_Lumpur Asia/Kuching Asia/Kuwait Asia/Macao Asia/Macau Asia/Magadan Asia/Makassar Asia/Manila Asia/Muscat Asia/Nicosia Asia/Novokuznetsk Asia/Novosibirsk Asia/Omsk Asia/Oral Asia/Phnom_Penh Asia/Pontianak Asia/Pyongyang Asia/Qatar Asia/Qyzylorda Asia/Rangoon Asia/Riyadh Asia/Riyadh87 Asia/Riyadh88 Asia/Riyadh89 Asia/Saigon Asia/Sakhalin Asia/Samarkand Asia/Seoul Asia/Shanghai Asia/Singapore Asia/Taipei Asia/Tashkent Asia/Tbilisi Asia/Tehran Asia/Tel_Aviv Asia/Thimbu Asia/Thimphu Asia/Tokyo Asia/Ujung_Pandang Asia/Ulaanbaatar Asia/Ulan_Bator Asia/Urumqi Asia/Vientiane Asia/Vladivostok Asia/Yakutsk Asia/Yekaterinburg Asia/Yerevan Atlantic/Azores Atlantic/Bermuda Atlantic/Canary Atlantic/Cape_Verde Atlantic/Faeroe Atlantic/Faroe Atlantic/Jan_Mayen Atlantic/Madeira Atlantic/Reykjavik Atlantic/South_Georgia Atlantic/St_Helena Atlantic/Stanley Australia/ACT Australia/Adelaide Australia/Brisbane Australia/Broken_Hill Australia/Canberra Australia/Currie Australia/Darwin Australia/Eucla Australia/Hobart Australia/LHI Australia/Lindeman Australia/Lord_Howe Australia/Melbourne Australia/NSW Australia/North Australia/Perth Australia/Queensland Australia/South Australia/Sydney Australia/Tasmania Australia/Victoria Australia/West Australia/Yancowinna BET BST Brazil/Acre Brazil/DeNoronha Brazil/East Brazil/West CAT CET CNT CST CST6CDT CTT Canada/Atlantic Canada/Central Canada/East-Saskatchewan Canada/Eastern Canada/Mountain Canada/Newfoundland Canada/Pacific Canada/Saskatchewan Canada/Yukon Chile/Continental Chile/EasterIsland Cuba EAT ECT EET EST EST5EDT Egypt Eire Etc/GMT Etc/GMT+0 Etc/GMT+1 Etc/GMT+10 Etc/GMT+11 Etc/GMT+12 Etc/GMT+2 Etc/GMT+3 Etc/GMT+4 Etc/GMT+5 Etc/GMT+6 Etc/GMT+7 Etc/GMT+8 Etc/GMT+9 Etc/GMT-0 Etc/GMT-1 Etc/GMT-10 Etc/GMT-11 Etc/GMT-12 Etc/GMT-13 Etc/GMT-14 Etc/GMT-2 Etc/GMT-3 Etc/GMT-4 Etc/GMT-5 Etc/GMT-6 Etc/GMT-7 Etc/GMT-8 Etc/GMT-9 Etc/GMT0 Etc/Greenwich Etc/UCT Etc/UTC Etc/Universal Etc/Zulu Europe/Amsterdam Europe/Andorra Europe/Athens Europe/Belfast Europe/Belgrade Europe/Berlin Europe/Bratislava Europe/Brussels Europe/Bucharest Europe/Budapest Europe/Chisinau Europe/Copenhagen Europe/Dublin Europe/Gibraltar Europe/Guernsey Europe/Helsinki Europe/Isle_of_Man Europe/Istanbul Europe/Jersey Europe/Kaliningrad Europe/Kiev Europe/Lisbon Europe/Ljubljana Europe/London Europe/Luxembourg Europe/Madrid Europe/Malta Europe/Mariehamn Europe/Minsk Europe/Monaco Europe/Moscow Europe/Nicosia Europe/Oslo Europe/Paris Europe/Podgorica Europe/Prague Europe/Riga Europe/Rome Europe/Samara Europe/San_Marino Europe/Sarajevo Europe/Simferopol Europe/Skopje Europe/Sofia Europe/Stockholm Europe/Tallinn Europe/Tirane Europe/Tiraspol Europe/Uzhgorod Europe/Vaduz Europe/Vatican Europe/Vienna Europe/Vilnius Europe/Volgograd Europe/Warsaw Europe/Zagreb Europe/Zaporozhye Europe/Zurich GB GB-Eire GMT GMT0 Greenwich HST Hongkong IET IST Iceland Indian/Antananarivo Indian/Chagos Indian/Christmas Indian/Cocos Indian/Comoro Indian/Kerguelen Indian/Mahe Indian/Maldives Indian/Mauritius Indian/Mayotte Indian/Reunion Iran Israel JST Jamaica Japan Kwajalein Libya MET MIT MST MST7MDT Mexico/BajaNorte Mexico/BajaSur Mexico/General Mideast/Riyadh87 Mideast/Riyadh88 Mideast/Riyadh89 NET NST NZ NZ-CHAT Navajo PLT PNT PRC PRT PST PST8PDT Pacific/Apia Pacific/Auckland Pacific/Chatham Pacific/Easter Pacific/Efate Pacific/Enderbury Pacific/Fakaofo Pacific/Fiji Pacific/Funafuti Pacific/Galapagos Pacific/Gambier Pacific/Guadalcanal Pacific/Guam Pacific/Honolulu Pacific/Johnston Pacific/Kiritimati Pacific/Kosrae Pacific/Kwajalein Pacific/Majuro Pacific/Marquesas Pacific/Midway Pacific/Nauru Pacific/Niue Pacific/Norfolk Pacific/Noumea Pacific/Pago_Pago Pacific/Palau Pacific/Pitcairn Pacific/Ponape Pacific/Port_Moresby Pacific/Rarotonga Pacific/Saipan Pacific/Samoa Pacific/Tahiti Pacific/Tarawa Pacific/Tongatapu Pacific/Truk Pacific/Wake Pacific/Wallis Pacific/Yap Poland Portugal ROK SST Singapore SystemV/AST4 SystemV/AST4ADT SystemV/CST6 SystemV/CST6CDT SystemV/EST5 SystemV/EST5EDT SystemV/HST10 SystemV/MST7 SystemV/MST7MDT SystemV/PST8 SystemV/PST8PDT SystemV/YST9 SystemV/YST9YDT Turkey UCT US/Alaska US/Aleutian US/Arizona US/Central US/East-Indiana US/Eastern US/Hawaii US/Indiana-Starke US/Michigan US/Mountain US/Pacific US/Pacific-New US/Samoa UTC Universal VST W-SU WET Zulu
Determine the Time Difference Between Two Timezones in Java
To calculate the time difference between two different timezones, we can use a java.util.Calendar class to get the current time at a given timezone, including the local timezone. The difference in hours can then be calculated by subtracting the hour of day of two Calendar instances. Looking at the day of month allows you to correct for the case when the current time spans two days by adding 24.
Here is the output of the example code:
See also: Get All Timezones Available in the TimeZone Class in Java
import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.TimeZone; // Java 1.4+ Compatible // //The following example code demonstrates how to calculate //the time difference between two different timezones, in // particular New York and Alaska, given the current time. // Since daylight savings time effective dates are different // between countries, it's important to calculate the // timezone difference at a particular date. Calculating // the difference between the local timezone and a different // one is also demonstrated. // and a different one is also demonstrated. public class DifferenceBetweenTwoTimezones { public static void main(String[] args) { // East Coast Time Calendar c = new GregorianCalendar(TimeZone.getTimeZone("America/New_York")); c.setTimeInMillis(new Date().getTime()); int EastCoastHourOfDay = c.get(Calendar.HOUR_OF_DAY); int EastCoastDayOfMonth = c.get(Calendar.DAY_OF_MONTH); // Alaska c = new GregorianCalendar(TimeZone.getTimeZone("America/Anchorage")); c.setTimeInMillis(new Date().getTime()); int AlaskaHourOfDay = c.get(Calendar.HOUR_OF_DAY); int AlaskaDayOfMonth = c.get(Calendar.DAY_OF_MONTH); // Difference between New York and Alaska int hourDifference = EastCoastHourOfDay - AlaskaHourOfDay; int dayDifference = EastCoastDayOfMonth - AlaskaDayOfMonth; if (dayDifference != 0) { hourDifference = hourDifference + 24; } System.out.println(hourDifference); // Local Time int localHourOfDay = Calendar.getInstance().get(Calendar.HOUR_OF_DAY); int localDayOfMonth = Calendar.getInstance().get(Calendar.DAY_OF_MONTH); // Difference between New York and Local Time (for me Germany) hourDifference = EastCoastHourOfDay - localHourOfDay; dayDifference = EastCoastDayOfMonth - localDayOfMonth; if (dayDifference != 0) { hourDifference = hourDifference + 24; } System.out.println(hourDifference); } }
Here is the output of the example code:
4 -6
See also: Get All Timezones Available in the TimeZone Class in Java
Subscribe to:
Posts (Atom)