Converting String into Date and Time Zones and java.util.Date


Converting String into Date

parse() from SimpleDateFormat class helps to convert a String pattern into a Date object.

DateFormat dateFormatter = DateFormat.getDateInstance(DateFormat.SHORT, Locale.US);
String dateString = "07/04/2023"; // Input String
Date newDate = dateFormatter.parse(dateString);
System.out.println(newDate.getYear()); // 123

There are 4 different styles for the text format, SHORT, MEDIUM (this is the default), LONG and FULL, all of which depend on the locale. If no locale is specified, the system default locale is used.

Format Locale.US Locale.France
SHORT 6/30/09 30/06/09
MEDIUM Jun 30, 2009 30 juin 2009
LONG June 30, 2009 30 juin 2009
FULL Tuesday, June 30, 2009 mardi 30 juin 2009

Time Zones and java.util.Date

A java.util.Date object does not have a concept of time zone.

  • There is no way to set a timezone for a Date
  • There is no way to change the timezone of a Date object
  • A Date object created with the new Date() default constructor will be initialised with the current time in the system default timezone

However, it is possible to display the date represented by the point in time described by the Date object in a different time zone using e.g. java.text.SimpleDateFormat:

Date currentDate = new Date();
 
// Print the default time zone
System.out.println(TimeZone.getDefault().getDisplayName());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
// Print the date in the original time zone
System.out.println(dateFormat.format(currentDate));
 
// Current time in a different time zone (e.g., New York)
dateFormat.setTimeZone(TimeZone.getTimeZone("America/New_York"));
System.out.println(dateFormat.format(currentDate));
 

Output:

Your_Default_Time_Zone
2023-12-30 15:25:30
2023-12-30 10:25:30

Basic Programs