3

I tried to convert current date is in "UTC" timezone format

    Calendar cal = Calendar.getInstance();
    cal.setTime(new Date());
    DateFormat sdf = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
    String dat = sdf.format(cal.getTime());
    System.out.println("In string format" + dat);
    System.out.println(("Date After parses " + (Date) sdf.parse(dat)));

Below is op:

In string format Mon Apr 11 09:57:12 +0000 2016 Date After parses Mon Apr 11 15:27:12 IST 2016

When i tried to convert date(Parse) in Date Format from String,I am getting the date is in Current date time and also in IST format.

Vaibs
  • 1,546
  • 9
  • 31
  • 1
    A `Date` object does not have any timezone associated with it... If you want to print it out in a particular timezone, you need to use `DateFormat.format()` as you have done... – Codebender Apr 11 '16 at 11:15
  • I just found the solution for above problem.We have to change the default time zone for that.In my case default timezone is IST so i changed it from UTC. TimeZone.setDefault(TimeZone.getTimeZone("UTC")); Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTime(new Date()); – Vaibs Apr 11 '16 at 11:28
  • 1
    If you are going to change your default timezone just for the sake of displaying a `Date` object, then you are doing it wrong... What is the problem you are trying to solve here? Why do you want to printout a Date object without using a DateFormat? – Codebender Apr 11 '16 at 11:30
  • My DB is in UTC timeZone and my application is in IST timezone.So each hour i have to generate report for application from DB for that i need current time which is in UTC timezone format. – Vaibs Apr 11 '16 at 11:42
  • @Vaibs Please search Stack Overflow before posting. Your question has been covered hundreds of times already. – Basil Bourque Apr 11 '16 at 15:12

1 Answers1

2

Try the solution explained in this post

Basically he gets the Calendar instance with the timeZone set as "UTC"

Here is the code:

 TimeZone timeZone = TimeZone.getTimeZone("UTC");
 Calendar calendar = Calendar.getInstance(timeZone);
 calendar.setTime(new Date());
 DateFormat simpleDateFormat = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
 simpleDateFormat.setTimeZone(timeZone);

 System.out.println("Time zone: " + timeZone.getID());
 System.out.println("default time zone: " + TimeZone.getDefault().getID());
 System.out.println();

 System.out.println("UTC:     " + simpleDateFormat.format(calendar.getTime()));
 System.out.println("Default: " + calendar.getTime());
Community
  • 1
  • 1
Manu AG
  • 188
  • 1
  • 6