0

Here this last_checked_datetime is my date stored in database which is in utc format,

 Timestamp ts1=rs9.getTimestamp("last_checked_datetime");
 java.sql.Date last_chk=new java.sql.Date(ts1.getTime());
 java.util.Date time=new java.util.Date(last_chk.getTime());
 java.text.SimpleDateFormat sdf=new java.text.SimpleDateFormat("HH:mm:ss");
 String old_time=sdf.format(time);

When I call this Date() it was print EST time

 String new_time=sdf.format(new Date());
 Date date1 = sdf.parse(old_time);
 Date date2 = sdf.parse(new_time);

I want difference of these two but date1 take utc time and date2 take est time which cause a barrier in my code? Please suggest

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
qwerty
  • 41
  • 2
  • 8
  • Maybe look into `GregorianCalendar` to allow for timezone control. – AlexR Jul 24 '14 at 08:53
  • Check this out: http://stackoverflow.com/questions/2891361/how-to-set-time-zone-of-a-java-util-date – alobodzk Jul 24 '14 at 08:56
  • but same code i use on other machine , and it works correctly. Is there any machine related problem or i have to change in a code – qwerty Jul 24 '14 at 09:07

3 Answers3

1

Try setting a default time zone as such-

TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
user3201181
  • 62
  • 1
  • 9
0

Take a look at org.joda.time.DateTime

This allows you to control what timezone you want the date to be in.

For example:

DateTime.now().withZone(DateTimeZone.UTC).toDate()
Ben Green
  • 3,953
  • 3
  • 29
  • 49
  • but same code i use on other machine , and it works correctly. Is there any machine related problem or i have to change in a code? – qwerty Jul 24 '14 at 09:06
  • By default, the timezone comes from the `user.timezone` system property, so if these are different on your two machines, this would explain why there is a difference between your results. – Ben Green Jul 24 '14 at 09:32
  • If my answer has helped you solve your problem, it is general practise on stack overflow to accept the answer by pressing the green tick next to it :) – Ben Green Jul 24 '14 at 10:37
  • could you please tell me how can i see this timezone of my system? because when i use date command in my both machine, it shows same date in utc. – qwerty Jul 24 '14 at 10:42
  • Write a quick test containing the following: `System.out.println(System.getProperty("user.timezone"));` This will show you the current timezone of your jvm – Ben Green Jul 24 '14 at 10:48
0
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("EST"));
//change the timezone
cal.setTimeZone(TimeZone.getTimeZone("UTC"));
Deepu--Java
  • 3,742
  • 3
  • 19
  • 30