Please suggest a way to print a date in EST.
public Date convertToEST(Date date)
{
// some code here
}
If I pass in a date in IST, the method should return that date in EST.
You need the following
Date date = new Date();
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
// Set the formatter to use a different timezone
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
// Prints the date in the EST timezone
System.out.println(formatter.format(date));
To make return the method a Date
object, you will need as shown below
public static Date convertToEST(Date date) throws ParseException {
DateFormat formatter = new SimpleDateFormat("dd MMM yyyy HH:mm:ss z");
formatter.setTimeZone(TimeZone.getTimeZone("EST"));
return formatter.parse((formatter.format(date)));
}
Javadoc- DateFormat.format
, DateFormat.parse
The idea of "the method should return that date in EST" is wrong. Date is only a holder of milliseconds since January 1, 1970, 00:00:00 GMT. It has nothing to do with the time zone.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With