chipmunk
chipmunk

Reputation: 213

Convert EST time to local Time in java

I'm unable to convert (12/19/2012 8:57am EST) to local Time (now Indian Time). While converting I'm getting wrong time (Dec 19 2012 11:27). I'm using the following code:

private void convertEdtToLocalTime(String pubDate)
{
    //pubDate = 12/19/2012 8:57am EST;
    String localPubDate;
    try
    {
        SimpleDateFormat sdf = new SimpleDateFormat(
            "MM/dd/yyyy HH:mma z");
        TimeZone timeZone = TimeZone.getDefault();
        sdf.setTimeZone(timeZone);
        if (pubDate != null)
        {
            Date date = sdf.parse(pubDate);
            sdf = new SimpleDateFormat("MMM dd yyyy HH:mm");
            localPubDate = sdf.format(date);
        }
    }
    catch (ParseException e)
    {
    }
}

Upvotes: 3

Views: 2699

Answers (1)

Rahul
Rahul

Reputation: 16335

You dont need to set the timeZone as the the time zone is already specified in the pubDate string. When you want to format using different SDF, the default timezone will convert it into default timezone itself. For eg. if you are in india, IST time = Dec 19 2012 19:27

private static  void convertEdtToLocalTime(String pubDate)
    {
        //pubDate = 12/19/2012 8:57am EST;
        String localPubDate=null;
        try
        {
            SimpleDateFormat sdf = new SimpleDateFormat(
                "MM/dd/yyyy HH:mma z");
//          TimeZone timeZone = TimeZone.getDefault(); // No need to do it
//          sdf.setTimeZone(timeZone);
            if (pubDate != null)
            {
                Date date = sdf.parse(pubDate);
                sdf = new SimpleDateFormat("MMM dd yyyy HH:mm");
                localPubDate = sdf.format(date);
            }
        }
        catch (ParseException e)
        {
        }
        System.out.println(localPubDate);
    }

Upvotes: 2

Related Questions