Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
    {
    }
}
like image 456
chipmunk Avatar asked Mar 11 '26 23:03

chipmunk


1 Answers

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);
    }
like image 128
Rahul Avatar answered Mar 13 '26 11:03

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!