ZonedDateTime
holds no format, no text
but I need to return ZonedDateTime not String.
Short answer: It is not possible.
Explanation:
The standard Date-Time classes do not have any attribute to hold the formatting information. Even if some library or custom class promises to do so, it is breaking the Single Responsibility Principle. A Date-Time object is supposed to store the information about Date, Time, Timezone etc., not about the formatting. The only way to represent a Date-Time object in the desired format is by formatting it into a String
using a Date-Time parsing/formatting type:
- For the modern Date-Time API:
java.time.format.DateTimeFormatter
- For the legacy Date-Time API:
java.text.SimpleDateFormat
The 3-letter abbreviation for the timezone ID:
The problem with the 3-letter abbreviation e.g. IST
is that it can specify many timezones; therefore, you need to change it to the desired timezone ID as per the naming convention, Region/City. Given below is an excerpt from the documentation:
Three-letter time zone IDs
For compatibility with JDK 1.1.x, some other three-letter time zone
IDs (such as "PST", "CTT", "AST") are also supported. However, their
use is deprecated because the same abbreviation is often used for
multiple time zones (for example, "CST" could be U.S. "Central
Standard Time" and "China Standard Time"), and the Java platform can
then only recognize one of them.
Demo:
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
public class Main {
public static void main(String[] args) {
ZonedDateTime z1 = ZonedDateTime.parse("2021-08-06T19:01:32.632+05:30[Asia/Calcutta]");
DateTimeFormatter df = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm:ss z", Locale.ENGLISH);
String s = z1.format(df);
System.out.println(s);
// Getting the original ZonedDateTime from the string
s = s.replace("IST", "Asia/Calcutta");
ZonedDateTime z2 = ZonedDateTime.parse(s, df);
System.out.println(z2);
}
}
Output:
06-Aug-2021 19:01:32 IST
2021-08-06T19:01:32+05:30[Asia/Calcutta]
ONLINE DEMO