8

Am trying convert date which is in local time zone to GMT, i did some thing like this

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String gmtStrDate = sdf.format(Calendar.getInstance().getTime());

        System.out.println("GMT 1"+gmtStrDate);

        Date gmtDate = sdf.parse(gmtStrDate);

        System.out.println("GMT 2"+gmtDate);

i am getting GMT 1 o/p in GMT tz but GMT 2 o/p is again changing to local time zone...Can any tel me why?

to get the GMT 2 o/p in GMT i did like this :

Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT")); calendar.setTime(gmtDate);

        System.out.println("GMT 3 = "+calendar.getTime());

but still GMT 3o/p am getting in local tz. Please suggest on this.

3 Answers 3

17
import java.util.*;
import java.text.*;
public class CurrentTimeToGMT{
  public static void main(String args[]){
    Date date = new Date();
    DateFormat gmtFormat = new SimpleDateFormat();
    TimeZone gmtTime = TimeZone.getTimeZone("GMT");
    gmtFormat.setTimeZone(gmtTime);
    System.out.println("Current Time: "+date);
    System.out.println("GMT Time: " + gmtFormat.format(date));

  }
}

Output

Current Time: Wed Mar 10 11:21:18 IST 2010

GMT Time: 3/10/10 5:51 AM
0
2

After 'parse' you have to again format it before printing, e.g.:

System.out.println("GMT 2"+sdf.format(gmtDate));

EDIT: The reason is your gmtStrDate doesn't store any timezone information

2
  • Hello Nanda, Thanks for the update, but here if i again format it i will get it as String right, but i want to get in Date so i was trying to parse it. If u have any idea about this please let me know.
    – Sreekar
    Commented Jan 13, 2010 at 17:22
  • Hi... if that's your intention, you've got the correct result. You have to print it correctly (in GMT) though. System.out.println("GMT 3 = " + sdf.format(calendar.getTime())); calendar.getTime() contains the data you want.
    – nanda
    Commented Jan 13, 2010 at 23:39
0

You can do this using this function say you want to convert local time to GMT time and also this will be GMT+6 or GMT+5 then just use this function. This function will return answer.

public String getCurrentDate() {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy MM dd hh:mm a zzz");
    Date date = new Date();
    sdf.setTimeZone(TimeZone.getTimeZone("GMT+6:00"));
    return sdf.format(date);
 }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.