Date Formatting In Java With Time Zone
This tutorial will help you getting the current time, date and day in any given format for any particular time zone in java.
Listed below are some IDs for some common Time zones in the US:
Time Zone | Java Time Zone ID |
Hawaiian Standard Time | US/Hawaii |
Alaska Standard Time | US/Alaska |
Pacific Standard Time | US/Pacific |
Mountain Standard Time | US/Mountain |
Central Standard Time | US/Central |
Eastern Standard Time | US/Eastern |
Java 6 makes available 575 different time zone IDs for places around the world. It is recommended that Java Time zone IDs mentioned in the above table are used, instead of using three letter time zone abbreviations like “EST”, “PDT”, etc. as they are not unique in their usage around the world.
For Example, CST can stand for both Central Standard Time and China Standard Time.
Though Java can still recognise these for compatibility with Java 1.1, Usage of these abbreviations in JREs may produce unpredictable results. Currently Java uses the “tz database” for listing of time zone related to a particular location.
Sample Code for obtaining the list of Time Zones in the US:
For the purpose of learning, “US/Eastern” has been used in the code in the below example.The functions used in the below complete code, takes in the values of the date format and the time zone. The user needs to decide the format in which the date/day/time value is required and the target time zone. For date formatting you can refer Date formatting in java.
import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class ObtainDate < public static void main(String[] args) < ObtainDate obtainDate = new ObtainDate(); TimeZone timeZone = TimeZone.getTimeZone("US/Eastern"); String dateFormat = "MMMM dd,yyyy G"; //MMMM dd,yyyy G String timeFormat = "hh:mm:ss.SSS a zzzz"; String dayFormat = "EEEEEE"; System.out.println("Todays Day:" + obtainDate.getTodaysDay(dayFormat,timeZone)); System.out.println("Todays Date:" + obtainDate.getTodayDate(dateFormat,timeZone)); System.out.println("Current Time:" + obtainDate.getCurrentTime(timeFormat,timeZone)); >/** * Description - Method to Get Today's day * @author Chaitanya * @param dateFormat * @param TimeZone */ public String getTodaysDay(String dayFormat, TimeZone timeZone) < Date date = new Date(); /* Specifying the format */ DateFormat requiredFormat = new SimpleDateFormat(dayFormat); /* Setting the Timezone */ requiredFormat.setTimeZone(timeZone); /* Picking the day value in the required Format */ String strCurrentDay = requiredFormat.format(date).toUpperCase(); return strCurrentDay; >/** * Description - Method to Get Current time * @author Chaitanya * @param dateFormat * @param TimeZone */ public String getCurrentTime(String timeFormat, TimeZone timeZone) < /* Specifying the format */ DateFormat dateFormat = new SimpleDateFormat(timeFormat); /* Setting the Timezone */ Calendar cal = Calendar.getInstance(timeZone); dateFormat.setTimeZone(cal.getTimeZone()); /* Picking the time value in the required Format */ String currentTime = dateFormat.format(cal.getTime()); return currentTime; >/** * Description - Method to Get Today's date * @author Chaitanya * @param dateFormat * @param TimeZone */ public String getTodayDate(String dateFormat, TimeZone timeZone) < Date todayDate = new Date(); /* Specifying the format */ DateFormat todayDateFormat = new SimpleDateFormat(dateFormat); /* Setting the Timezone */ todayDateFormat.setTimeZone(timeZone); /* Picking the date value in the required Format */ String strTodayDate = todayDateFormat.format(todayDate); return strTodayDate; >>
Todays Day:THURSDAY Todays Date:October 19,2017 AD Current Time:12:15:44.232 PM Eastern Daylight Time
Steps involved:
The basic steps in the calculation of day/date/time in a particular time zone:
- Obtain a new Date object
- A date format object is created in Simple Date Format
- The required format is assigned to the date format object – For Eg: hh:mm:ss.SSS
- Set the required time zone to the date format object
- Pick the day/date/time value from the date format object by passing the date object created in the first step.
The following table provides the various date patterns and their significance in Java Timestamp Format:
Pattern | Denotes |
yyyy | Current Year |
MM | Current Month in number |
MMM | Current Month abbreviated |
MMMM | Current Month in Full |
dd | Current Date of the month |
DD | Current Day of the year |
hh | Current Time’s Hour (12 Hour clock) |
HH | Current Time’s Hour (24 Hour clock) |
a | AM/PM |
mm | Current Time’s Minute |
ss | Current Time’s Second |
SSS | Current Time’s Millisecond (the number of SSS can be incremented to obtain the fraction of the second) |
G | Epoch |
zzz | Time Zone abbreviated |
zzzz | Time Zone in Full |
EEEEEE | Current Day in Full |
EEE | Current Day abbreviated |
A reference like yyyy.MM.dd G hh:mm:ss would yield an output like 2011.11.07 AD 1:11:57 PM. At the same time yyyy.MMM.DD G HH:mm.SSS would yield output of 2011.JUL.194 AD 23:11.938.
References:
Related Posts:
Top Related Articles:
About the Author
I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.
Converting Date and Time between Timezones
Learn to convert a given date-time object from one timezone to another timezone. We will see the examples using ZonedDateTime , Date and Calendar classes.
1. Changing Timezones of ZonedDateTime
In Java 8, date and time with timezone information is represented with ZonedDateTime . To convert a ZonedDateTime instance from one timezone to another, follow the two steps:
- Create ZonedDateTime in 1st timezone. You may already have it in your application.
- Convert the first ZonedDateTime in second timezone using withZoneSameInstant() method.
ZonedDateTime instant = ZonedDateTime.now(); System.out.println(instant); ZonedDateTime instantInUTC = instant.withZoneSameInstant(ZoneId.of("UTC")); System.out.println(instantInUTC);
2022-02-16T18:36:14.509742500+05:30[Asia/Calcutta] 2022-02-16T13:06:14.509742500Z[UTC]
2. Changing Timezones of OffsetDateTime
Similar to ZonedDateTime, OffsetDateTime also represents an instant in universal timeline with an offset from UTC/Greenwich in the ISO-8601 calendar system. To convert a OffsetDateTime instance from one timezone to another, follow the two steps:
- Create OffsetDateTime in 1st timezone. You may already have it in your application.
- Convert the first OffsetDateTime in second timezone using withOffsetSameInstant() method.
OffsetDateTime now = OffsetDateTime.now(); System.out.println(now); OffsetDateTime nowInUTC = now.withOffsetSameInstant(ZoneOffset.of( "00:00" )); System.out.println(instantInUTC);
2022-02-16T18:36:14.509742500+05:30 2022-02-16T13:06:14.509742500Z[UTC]
3. Changing Timezones of java.util.Date
- java.util.Date represents a time instant without timezone information.
- It only represents the total time since the epoch in milliseconds.
- This is very important to understand that, by default, if we print the Date object, it will always print the date and time information along with the system’s current timezone. This is misleading behavior because it suggests that Date objects can have timezone information, which is incorrect.
The correct way to deal with Date instance in different timezones is to print the date information in other timezones using the SimpleDateFormat class. It is not a good solution to adjust the instant in the timeline by adjusting the zone offset in the milliseconds of Date object.
SimpleDateFormat FORMATTER = new SimpleDateFormat("MM/dd/yyyy 'at' hh:mma z"); //In Default Timezone Date currentDate = new Date(); //Date in current timezone System.out.println(FORMATTER.format(currentDate)); //In UTC Timezone TimeZone utcTimeZone = TimeZone.getTimeZone("UTC"); FORMATTER.setTimeZone(utcTimeZone); String sDateInUTC = FORMATTER.format(currentDate); System.out.println(sDateInUTC);
02/16/2022 at 06:36pm IST 02/16/2022 at 01:06pm UTC
How to convert Java Date into Specific TimeZone format
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
In the last example, we learned how to convert Date to String in Java. In this example, I am converting a Java Date object from one timezone to another. We will use SimpleDateFormat class to format the Date in a specific format and we will set its timezone to print the date in a specific timezone.
package com.journaldev.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class DateFormatter < /** * Utility function to convert java Date to TimeZone format * @param date * @param format * @param timeZone * @return */ public static String formatDateToString(Date date, String format, String timeZone) < // null check if (date == null) return null; // create SimpleDateFormat object with input format SimpleDateFormat sdf = new SimpleDateFormat(format); // default system timezone if passed null or empty if (timeZone == null || "".equalsIgnoreCase(timeZone.trim())) < timeZone = Calendar.getInstance().getTimeZone().getID(); >// set timezone to SimpleDateFormat sdf.setTimeZone(TimeZone.getTimeZone(timeZone)); // return Date in required format with timezone as String return sdf.format(date); > public static void main(String[] args) < //Test formatDateToString method Date date = new Date(); System.out.println("Default Date:"+date.toString()); System.out.println("System Date: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", null)); System.out.println("System Date in PST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "PST")); System.out.println("System Date in IST: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "IST")); System.out.println("System Date in GMT: "+formatDateToString(date, "dd MMM yyyy hh:mm:ss a", "GMT")); >>
Default Date:Wed Nov 14 21:37:01 PST 2012 System Date: 14 Nov 2012 09:37:01 PM System Date in PST: 14 Nov 2012 09:37:01 PM System Date in IST: 15 Nov 2012 11:07:01 AM System Date in GMT: 15 Nov 2012 05:37:01 AM
From the output, it’s clear that my system TimeZone is PST and then it’s converting same Date object to different timezones like IST and GMT and printing it. Using my last tutorial you can again convert the returned string to a Date object. Update: Java 8 has added new Date Time API, you should check it out at Java 8 Date.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases. Learn more about us