Tag Archives: Date TimeZone

JAVA : Daylight Saving Time (DST) Handling


Pre-Requisite : Java : Date and Time Handling Tutorial

Most of the United States practice of advancing clock during summer month in order to leverage an additional hour of natural light(saving heating power, illumination power, enhancing the mood, and so on).

When clocks change time

In United States Daylight Saving Time begins at 2:00 a.m. on the second Sunday in March and reverts to standard time on the first Sunday in November. In United States each time zone switches clocks at different time.

Daylight Saving Time on time zone

In United States , When Daylight Saving Time are being followed in EST then it’s become EDT. These names just are abbreviation and having different meaning in different continents.
Ex:

  • IST : Indian Standard Time
  • IST : Irish Standard Time
  • IST : Israel Standard Time

For United States (Follow Day Light Saving)

Standard Time Daylight Savings Time
CST : Central Standard Time (North America) CDT : Central Daylight Time
EST : Eastern Standard Time (North America) EDT : Eastern Daylight Time
PST : Pacific Standard Time (North America) PDT : Pacific Daylight Time

Complete List of timezone abbreviations

Note : The 3-letter abbreviations should be wholeheartedly avoided in favor of TZDB zone IDs. EST is not time zone such 3-4 letter codes are neither standardized nor unique, and further the confusion over Daylight saving time (DST). Whenever need to set time zone in code in the code always use proper time zone name in the “continent/region” format.

Complete List of time zone with continent/region

Example of Daylight Saving Time with Time Zone

In this example cover all the case for applying Daylight Saving Time on different time zone. Here I have try to apply with abbreviation, continent / region and show with standard time and Daylight saving time.

package datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.ZoneId;
import java.util.Date;
import java.util.TimeZone;

public class DayLightSavingExample {

	public static void main(String[] args) {
	/**
	* DST = Daylight Saving Time (Begins Daylight Saving Time at 2:00 a.m.
	* on the second Sunday in March and reverts to standard time on the
	* first Sunday in November)
	*/
	SimpleDateFormat sourceFormat = new SimpleDateFormat("MM/dd/yyyy");
	SimpleDateFormat targetFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'+|-hh:mm");
	String strWithDLS = "03/10/2019"; // MM/DD/YYYY
	String strWithOutDLS = "03/11/2019";
	try {
	     Date dateWithDLS = sourceFormat.parse(strWithDLS);
	     Date dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("Default Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("Default Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with EST (No difference in time) because 3 letter
		* time zone not consider DST (Day light saving time)
		*/
		sourceFormat.setTimeZone(TimeZone.getTimeZone("EST"));
		dateWithDLS = sourceFormat.parse(strWithDLS);
		dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
		System.out.println("EST Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
		System.out.println("EST Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

		/**
		* Set time zone with America/New_York (1 hour difference in time)
		* when you need to use day light saving always use with
		* continent/region format.
		*/
			sourceFormat.setTimeZone(TimeZone.getTimeZone(ZoneId.of("America/New_York")));
dateWithDLS = sourceFormat.parse(strWithDLS);
dateWithOutDLS = sourceFormat.parse(strWithOutDLS);
System.out.println("America/New_York Timezone with Day Light Saving :" + targetFormat.format(dateWithDLS));
System.out.println(
"America/New_York Timezone without Day Light Saving :" + targetFormat.format(dateWithOutDLS));

} catch (ParseException ex) {
			ex.printStackTrace();
}

	}

}

Output :


Default Timezone with Day Light Saving :2019-03-10T00:00:00Z+|-12:00
Default Timezone without Day Light Saving :2019-03-11T00:00:00Z+|-12:00
EST Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
EST Timezone without Day Light Saving :2019-03-11T10:30:00Z+|-10:30
America/New_York Timezone with Day Light Saving :2019-03-10T10:30:00Z+|-10:30
America/New_York Timezone without Day Light Saving :2019-03-11T09:30:00Z+|-09:30

 

Here i have tried to cover all the points as developer prospects. If you know more ways to handle it and any issues related to date and time please suggest in comments.

Java 8+ Date Time Exmples


Pre-Requisite : Java Date and Time Tutorial

In this below example try to cover all possible cases and operations with date and time with Java 8+ APIs.

import java.time.DateTimeException;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.Period;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjusters;
import java.time.zone.ZoneRulesException;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;

public class Java8DateTime {

	public static void main(String[] args) {
		//LocalDate lastDay_2014 = LocalDate.of(2014, 12, 32);
		//LocalTime lastDay_2014 = LocalTime.of(12, 12, 23,-1);
		currentDateTime();
		instantAPI();
		GregorianCalendarAPI();
		TimeZoneAPI();
		dateTimeFormattingAndParsing();
		localDateAPI();
		localDateTimeAPI();
		localTimeAPI();

		System.out.println("*********Set Date and Time Manually***************");
		LocalDateTime dateTimePoint=LocalDateTime.now();
		// Set Date and Time manually
		LocalDate datePoint = LocalDate.of(2012, Month.DECEMBER, 12);
		System.out.println("Local Date :" + datePoint);
		// Days after 1970
		datePoint = LocalDate.ofEpochDay(150);
		System.out.println("Local Date :" + datePoint);
		// set String
		LocalTime timePoint = LocalTime.parse("10:15:30");
		System.out.println("Local Time :" + timePoint);
		// Set hours and minutes
		timePoint = LocalTime.of(13, 18);
		System.out.println("Local Time :" + timePoint);

		// Retrieve values
		System.out.println("*********Get Date and Time Values***************");
		datePoint = dateTimePoint.toLocalDate();
		Month month = dateTimePoint.getMonth();
		int day = dateTimePoint.getDayOfMonth();
		int year = dateTimePoint.getYear();
		int hour = dateTimePoint.getHour();
		int minute = dateTimePoint.getMinute();
		int second = dateTimePoint.getSecond();
		System.out.println("Local Date :" + datePoint);
		System.out.printf("Local Date time Format : %d/%d/%d %d:%d:%d", day, month.getValue(), year, hour, minute,
				second);
		System.out.println();
		System.out.println("*********Operation On LocalDate***************");
		// Operation on Local Date
		// Period of 1 year 3 month 2 days
		Period period = Period.of(1, 3, 2);
		LocalDate startDatePoint = datePoint.minus(period);
		System.out.println("Local Date :" + startDatePoint);
		LocalDate endDatePoint = datePoint.plus(period);
		System.out.println("Local Date :" + endDatePoint);

		System.out.println("*********Diffrence of On LocalDate***************");
		// Difference of Date
		Period daysPeriod = Period.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + daysPeriod.getDays());
		System.out.println("Months :" + daysPeriod.getMonths());
		System.out.println("Years :" + daysPeriod.getYears());
		// Another Way
		long days = ChronoUnit.DAYS.between(startDatePoint, endDatePoint);
		long months = ChronoUnit.MONTHS.between(startDatePoint, endDatePoint);
		long years = ChronoUnit.YEARS.between(startDatePoint, endDatePoint);
		System.out.println("Days :" + days);
		System.out.println("Months :" + months);
		System.out.println("Years :" + years);

		// Duration

		// A duration of 3 seconds and 5 nanoseconds
		Duration duration = Duration.ofSeconds(3, 5);
		// Duration oneDay = Duration.between(Temporal., yesterday);

	}

	private static void currentDateTime() {
		System.out.println("*********Current Date and Time***************");

		// Current Date and Time
		LocalDateTime dateTimePoint = LocalDateTime.now();
		System.out.println("Local Date Time :" + dateTimePoint);
		// Current Date
		LocalDate datePoint = LocalDate.now();
		System.out.println("Local Date :" + datePoint);
		// Current Time
		LocalTime timePoint = LocalTime.now();
		System.out.println("Local Time :" + timePoint);

		// Get Instant from java.util.Date
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);

		// java.util.Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);
	}

	private static void instantAPI() {
		System.out.println("*****************Instant API*******************");
		// Date to Instant
		Instant timestamp = new Date().toInstant();
		System.out.println("Current Timestamp = " + timestamp);
		// Now we can convert Instant to LocalDateTime or other similar classes
		LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("PST")));
		System.out.println("Date = " + date);

		// Calendar to Instant
		Instant time = Calendar.getInstance().toInstant();
		System.out.println(time);

		// Date API to Legacy classes
		Date dt = Date.from(Instant.now());
		System.out.println(dt);

		// Instant from timestamp
		Instant specificTime = Instant.ofEpochMilli(timestamp.toEpochMilli());
		System.out.println("Specific Time = " + specificTime);

		// Duration example
		Duration thirtyDay = Duration.ofDays(30);
		System.out.println(thirtyDay);
	}

	private static void localDateAPI() {
		System.out.println("*****************Local Date API*******************");
		LocalDate today = LocalDate.now();

		System.out.println("Current Date=" + today);

		// Creating LocalDate by providing input parameters.
		// Here are chnaces of getting DateTimeException if pass as Invalidate
		// Date format
		LocalDate firstDay_2016 = LocalDate.of(2016, Month.JANUARY, 1);
		System.out.println("Specific Date=" + firstDay_2016);

		try {
			// Here with throw DateTimeException if pass as Invalidate Date
			// format
			LocalDate lastDay_2014 = LocalDate.of(2014, Month.FEBRUARY, 29);
			System.out.println("Specific Date=" + lastDay_2014);
		} catch (DateTimeException ex) {
			ex.printStackTrace();
		}

		// Current date in "Asia/Kolkata", you can get it from ZoneId
		LocalDate todayKolkata = LocalDate.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in CST=" + todayKolkata);

		try
		{
		// Will throw java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		LocalDate todayIST = LocalDate.now(ZoneId.of("IST"));
		}
		catch(ZoneRulesException ex)
		{
			ex.printStackTrace();
		}

		// Getting date from the base date i.e 01/01/1970
		LocalDate dateFromBase = LocalDate.ofEpochDay(365);
		System.out.println("365th day from base date= " + dateFromBase);

        //Get 100 th day of year
		LocalDate hundredDay2014 = LocalDate.ofYearDay(2016, 100);
		System.out.println("100th day of 2014=" + hundredDay2014);

		//Other APIs and Operation on LocalDate

		// Get the Year, check if it's leap year
		System.out.println("Year " + today.getYear() + " is Leap Year? " + today.isLeapYear());

		// Compare two LocalDate for before and after
		System.out.println("Today is before 01/01/2017? " + today.isBefore(LocalDate.of(2017, 1, 1)));

		// Get LocalDateTime from LocalDate
		System.out.println("Current Time=" + today.atTime(LocalTime.now()));

		// plus and minus operations
		System.out.println("20 days after today will be " + today.plusDays(20));
		System.out.println("5 weeks after today will be " + today.plusWeeks(5));
		System.out.println("30 months after today will be " + today.plusMonths(30));

		System.out.println("20 days before today will be " + today.minusDays(20));
		System.out.println("5 weeks before today will be " + today.minusWeeks(5));
		System.out.println("30 months before today will be " + today.minusMonths(30));

		// TemporalAdjusters for adjusting the dates
		LocalDate firstDayOfMonth=today.with(TemporalAdjusters.firstDayOfMonth());
		System.out.println("First date of this month= " + firstDayOfMonth);

		LocalDate lastDayOfYear = today.with(TemporalAdjusters.lastDayOfYear());
		System.out.println("Last date of this year= " + lastDayOfYear);

		Period period = today.until(lastDayOfYear);
		System.out.println("Period Format= " + period);
		System.out.println("Months remaining in the year= " + period.getMonths());

	}

	private static void localTimeAPI() {
		System.out.println("*****************Local Time API*******************");
		// Current Time
		LocalTime time = LocalTime.now();
		System.out.println("Current Time=" + time);

		// Creating LocalTime by providing input arguments
		LocalTime specificTime = LocalTime.of(12, 20, 25, 40);
		System.out.println("Specific Time of Day=" + specificTime);

		// Try creating time by providing invalid inputs
		// LocalTime invalidTime = LocalTime.of(25,20);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalTime timeKolkata = LocalTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Time in IST=" + timeKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalTime todayIST = LocalTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalTime specificSecondTime = LocalTime.ofSecondOfDay(10000);
		System.out.println("10000th second time= " + specificSecondTime);

	}

	private static void localDateTimeAPI() {
		System.out.println("*****************Local Date Time API*******************");
		// Current Date
		LocalDateTime today = LocalDateTime.now();
		System.out.println("Current DateTime=" + today);

		// Current Date using LocalDate and LocalTime
		today = LocalDateTime.of(LocalDate.now(), LocalTime.now());
		System.out.println("Current DateTime=" + today);

		// Creating LocalDateTime by providing input arguments
		LocalDateTime specificDate = LocalDateTime.of(2014, Month.JANUARY, 1, 10, 10, 30);
		System.out.println("Specific Date=" + specificDate);

		// Try creating date by providing invalid inputs
		// LocalDateTime feb29_2014 = LocalDateTime.of(2014, Month.FEBRUARY, 28,
		// 25,1,1);
		// Exception in thread "main" java.time.DateTimeException:
		// Invalid value for HourOfDay (valid values 0 - 23): 25

		// Current date in "Asia/Kolkata", you can get it from ZoneId javadoc
		LocalDateTime todayKolkata = LocalDateTime.now(ZoneId.of("Asia/Kolkata"));
		System.out.println("Current Date in IST=" + todayKolkata);

		// java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
		// LocalDateTime todayIST = LocalDateTime.now(ZoneId.of("IST"));

		// Getting date from the base date i.e 01/01/1970
		LocalDateTime dateFromBase = LocalDateTime.ofEpochSecond(10000, 0, ZoneOffset.UTC);
		System.out.println("10000th second time from 01/01/1970= " + dateFromBase);

	}

	private static void dateTimeFormattingAndParsing() {
		System.out.println("*****************Local DateTime Formatting API*******************");
		// Format examples
		LocalDate date = LocalDate.now();
		// default format
		System.out.println("Default format of LocalDate=" + date);
		// specific format
		System.out.println(date.format(DateTimeFormatter.ofPattern("d::MMM::uuuu")));
		System.out.println(date.format(DateTimeFormatter.BASIC_ISO_DATE));

		LocalDateTime dateTime = LocalDateTime.now();
		// default format
		System.out.println("Default format of LocalDateTime=" + dateTime);
		// specific format
		System.out.println(dateTime.format(DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss")));
		System.out.println(dateTime.format(DateTimeFormatter.BASIC_ISO_DATE));

		Instant timestamp = Instant.now();
		// default format
		System.out.println("Default format of Instant=" + timestamp);

		// Parse examples
		LocalDateTime dt = LocalDateTime.parse("27::Apr::2014 21::39::48",
				DateTimeFormatter.ofPattern("d::MMM::uuuu HH::mm::ss"));
		System.out.println("Default format after parsing = " + dt);

	}

	private static void GregorianCalendarAPI() {
		System.out.println("*****************Gregorian Calendar API*******************");
		// ZonedDateTime from specific Calendar
		ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
		System.out.println(gregorianCalendarDateTime);

		GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
		System.out.println(gc);
	}

	private static void TimeZoneAPI() {
		System.out.println("*****************Time Zone API*******************");
		// TimeZone to ZoneId
		ZoneId defaultZone = TimeZone.getDefault().toZoneId();
		System.out.println(defaultZone);

		TimeZone tz = TimeZone.getTimeZone(defaultZone);
		System.out.println(tz);

	}

}

Output


*********Current Date and Time***************
Local Date Time :2019-05-16T11:50:59.302
Local Date :2019-05-16
Local Time :11:50:59.303
Current Timestamp = 2019-05-16T06:20:59.303Z
2019-05-16T06:20:59.358Z
*****************Instant API*******************
Current Timestamp = 2019-05-16T06:20:59.369Z
Date = 2019-05-15T23:20:59.369
2019-05-16T06:20:59.373Z
Thu May 16 11:50:59 IST 2019
Specific Time = 2019-05-16T06:20:59.369Z
PT720H
*****************Gregorian Calendar API*******************
2019-05-16T11:50:59.387+05:30[Asia/Calcutta]
java.util.GregorianCalendar[time=1557987659387,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null],firstDayOfWeek=2,minimalDaysInFirstWeek=4,ERA=1,YEAR=2019,MONTH=4,WEEK_OF_YEAR=20,WEEK_OF_MONTH=3,DAY_OF_MONTH=16,DAY_OF_YEAR=136,DAY_OF_WEEK=5,DAY_OF_WEEK_IN_MONTH=3,AM_PM=0,HOUR=11,HOUR_OF_DAY=11,MINUTE=50,SECOND=59,MILLISECOND=387,ZONE_OFFSET=19800000,DST_OFFSET=0]
*****************Time Zone API*******************
Asia/Calcutta
sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=7,lastRule=null]
*****************Local DateTime Formatting API*******************
Default format of LocalDate=2019-05-16
16::May::2019
20190516
Default format of LocalDateTime=2019-05-16T11:50:59.551
16::May::2019 11::50::59
20190516
Default format of Instant=2019-05-16T06:20:59.551Z
Default format after parsing = 2014-04-27T21:39:48
*****************Local Date API*******************
Current Date=2019-05-16
Specific Date=2016-01-01
java.time.DateTimeException: Invalid date 'February 29' as '2014' is not a leap year
Current Date in CST=2019-05-16
365th day from base date= 1971-01-01
    at java.time.LocalDate.create(Unknown Source)
    at java.time.LocalDate.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:160)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
java.time.zone.ZoneRulesException: Unknown time-zone ID: IST
    at java.time.zone.ZoneRulesProvider.getProvider(Unknown Source)
    at java.time.zone.ZoneRulesProvider.getRules(Unknown Source)
    at java.time.ZoneRegion.ofId(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at datetime.Java8DateTime.localDateAPI(Java8DateTime.java:173)
    at datetime.Java8DateTime.main(Java8DateTime.java:34)
100th day of 2014=2016-04-09
Year 2019 is Leap Year? false
Today is before 01/01/2017? false
Current Time=2019-05-16T11:50:59.619
20 days after today will be 2019-06-05
5 weeks after today will be 2019-06-20
30 months after today will be 2021-11-16
20 days before today will be 2019-04-26
5 weeks before today will be 2019-04-11
30 months before today will be 2016-11-16
First date of this month= 2019-05-01
Last date of this year= 2019-12-31
Period Format= P7M15D
Months remaining in the year= 7
*****************Local Date Time API*******************
Current DateTime=2019-05-16T11:50:59.620
Current DateTime=2019-05-16T11:50:59.620
Specific Date=2014-01-01T10:10:30
Current Date in IST=2019-05-16T11:50:59.620
10000th second time from 01/01/1970= 1970-01-01T02:46:40
*****************Local Time API*******************
Current Time=11:50:59.620
Specific Time of Day=12:20:25.000000040
Current Time in IST=11:50:59.620
10000th second time= 02:46:40
*********Set Date and Time Manually***************
Local Date :2012-12-12
Local Date :1970-05-31
Local Time :10:15:30
Local Time :13:18
*********Get Date and Time Values***************
Local Date :2019-05-16
Local Date time Format : 16/5/2019 11:50:59
*********Operation On LocalDate***************
Local Date :2018-02-14
Local Date :2020-08-18
*********Difference of On LocalDate***************
Days :4
Months :6
Years :2
Days :916
Months :30
Years :2

Above solutions are my search to perform all type of operations with date and time with java 8 API generally face while development. If you face other issue apart from it. Please mention in comments that will help with others.

Java : How to convert GMT, CST, IST and PST timezone?


In this article, you will learn to convert a date to GMT, CST, EST and PST format.

  • GMT : Greenwich Mean Time
  • CST : Central Standard Time= GMT-5
  • EST : Eastern Standard Time = GMT-6
  • PST : Pacific Standard Time=GMT-7

Example
This example helps you in converting a date to  GMT, CST, EST and PST time on the console. The SimpleDateFormat() constructor uses the given pattern and date format symbols. Here we use the date format as gmtFormat for date format in GMT timezone same way can convert for CST, EST and PST. Then we have used getTimeZone() method to get the time of both the zones to be converted.

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

public class ConvertTimeZoneFromGMT {

public static void main(String[] args) {
//Current Date and Time
Date date = new Date();

//GMT Format
DateFormat gmtFormat = new SimpleDateFormat();
TimeZone gmtTime = TimeZone.getTimeZone("GMT");
gmtFormat.setTimeZone(gmtTime);
System.out.println("GMT Time: " + gmtFormat.format(date));

//CST Time
DateFormat cstFormat = new SimpleDateFormat();
TimeZone cstTime = TimeZone.getTimeZone("CST");
cstFormat.setTimeZone(cstTime);
System.out.println("CST Time: " + cstFormat.format(date));

//EST Time
DateFormat istFormat = new SimpleDateFormat();
TimeZone estTime = TimeZone.getTimeZone("EST");
estFormat.setTimeZone(estTime);
System.out.println("EST Time: " + estFormat.format(date));

// PST Time
DateFormat pstFormat = new SimpleDateFormat();
TimeZone pstTime = TimeZone.getTimeZone("PST");
pstFormat.setTimeZone(pstTime);
System.out.println("PST Time: " + pstFormat.format(date)); 

}
}

Output


GMT Time: 3/22/19 8:39 AM
CST Time: 3/22/19 3:39 AM
EST Time: 3/22/19 2:09 PM
PST Time: 3/22/19 1:39 AM

Java : Date Format Locale and Internationalization


java.text.SimpleDateFormat class is subclass for java.text.DateFormat which use to convert String to Date and Date to different formatted String. DateFormat class supports TimeZone and Locale specific conversions also.

In below example you will see conversion of date to different Internationalization date by using Locale in SimpleDateFormat.

Example

package com.date;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
public class DateFormatLocaleAndInternationalization {

// Date formats
private static final String MAIN_DATE_FORMAT = "yyyy-MM-dd'T'hh:mm:ss.SSS'Z'";

public static void main(String[] args) {

Date date = new Date();
System.out.println("Date:" + date);

SimpleDateFormat formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.CANADA);
System.out.println("CANADA DATE :" + formatter.format(date));

formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.CANADA_FRENCH);
System.out.println("CANADA FRENCH DATE :" + formatter.format(date));

formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.GERMANY);
System.out.println("GERMANY :" + formatter.format(date));

formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.CHINESE);
System.out.println("CHINESE DATE :" + formatter.format(date));
formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.ITALIAN);
System.out.println("ITALIAN :" + formatter.format(date));

formatter = new SimpleDateFormat(MAIN_DATE_FORMAT, Locale.TAIWAN);
System.out.println("TAIWAN DATE :" + formatter.format(date));

	}

}

Output


Date:Mon Jul 30 12:01:13 PDT 2018
CANADA DATE :2018-07-30T12:01:13.909Z
CANADA FRENCH DATE :2018-07-30T12:01:13.909Z
GERMANY :2018-07-30T12:01:13.909Z
CHINESE DATE :2018-07-30T12:01:13.909Z
ITALIAN :2018-07-30T12:01:13.909Z
TAIWAN DATE :2018-07-30T12:01:13.909Z

Java : Date Format and TimeZone Conversion


In below example convert date to different date format and time zone.

Example

package com.date;

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

public class Date2TimeZoneUtility {
public static String LEGACY_FORMAT = "EEE MMM dd hh:mm:ss zzz yyyy";
public static String ISO_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSS zzz";
public static String SHORT_DATE = "yyyy-MM-dd";
private static final TimeZone utc = TimeZone.getTimeZone("UTC");
private static final SimpleDateFormat legacyFormatter = new SimpleDateFormat(LEGACY_FORMAT);
private static final SimpleDateFormat isoFormatter = new SimpleDateFormat(ISO_FORMAT);
private static final SimpleDateFormat shortFormatter = new SimpleDateFormat(SHORT_DATE);
static {
		legacyFormatter.setTimeZone(utc);
		isoFormatter.setTimeZone(utc);
	}

public static void main(String[] args) {
Date2TimeZoneUtility dateUtility = new Date2TimeZoneUtility();
Date date = new Date();
System.out.println("Current Date Default:" + date);
System.out.println("--->Change Date Format");
// Legacy Date Format
System.out.println("Current Date Legacy Format:" + dateUtility.toString(date, legacyFormatter));
// ISO Date Format
System.out.println("Current Date ISO Format:" + dateUtility.toString(date, isoFormatter));
// Short Date Format
System.out.println("Current Date Short Format:" + dateUtility.toString(date, shortFormatter));
System.out.println("--->Change Date Format with Time Zone UTC");
// Legacy Date Format UTC TimeZone
System.out.println("Current Date Legacy Format:" + dateUtility.toLegacyFormat(date));
// ISO Date Format UTC TimeZone
System.out.println("Current Date ISO Format:" + dateUtility.toISOFormat(date));
// Short Date Format UTC TimeZone
System.out.println("Current Date Short Format:" + dateUtility.toShortFormat(date));
System.out.println("--->Change Date Format with different Time Zone");
// Legacy Date Format with time Zone EST
System.out.println("Current Date Legacy Format with TimeZone EST:"
				+ dateUtility.toStringWithTimeZone(date, legacyFormatter, "EST"));
// ISO Date Format with time zone IST
System.out.println( "Current Date ISO Format with TimeZone IST:" + dateUtility.toStringWithTimeZone(date, isoFormatter, "IST"));
// Short Date Format Short Date with PST
System.out.println("Current Date Short Format with TimeZone PST:"
				+ dateUtility.toStringWithTimeZone(date, shortFormatter, "PST"));
}

public String toString(final Date date, SimpleDateFormat dateformat) {
		return dateformat.format(date);
}

public String toStringWithTimeZone(final Date date, SimpleDateFormat dateformat, final String timezone) {
		final TimeZone tz = TimeZone.getTimeZone(timezone);
		dateformat.setTimeZone(tz);
		return dateformat.format(date);
}

public String toLegacyFormat(final Date date) {
		return legacyFormatter.format(date);
}

public String toISOFormat(final Date date) {
		return isoFormatter.format(date);
}

public String toShortFormat(final Date date) {
		return shortFormatter.format(date);
}

}

Output


Current Date Default:Sat Jul 28 12:58:38 PDT 2018
--->Change Date Format
Current Date Legacy Format:Sat Jul 28 07:58:38 UTC 2018
Current Date ISO Format:2018-07-28T19:58:38.932 UTC
Current Date Short Format:2018-07-28
--->Change Date Format with Time Zone UTC
Current Date Legacy Format:Sat Jul 28 07:58:38 UTC 2018
Current Date ISO Format:2018-07-28T19:58:38.932 UTC
Current Date Short Format:2018-07-28
--->Change Date Format with different Time Zone
Current Date Legacy Format with TimeZone EST:Sat Jul 28 02:58:38 EST 2018
Current Date ISO Format with TimeZone IST:2018-07-29T01:28:38.932 IST
Current Date Short Format with TimeZone PST:2018-07-28