Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get date in EST

Tags:

java

date

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.

like image 773
buttowski Avatar asked Dec 25 '12 11:12

buttowski


2 Answers

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

like image 136
mtk Avatar answered Oct 13 '22 09:10

mtk


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.

like image 38
Evgeniy Dorofeev Avatar answered Oct 13 '22 11:10

Evgeniy Dorofeev