Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
The moose likes Java in General and the fly likes Need to compare date time in GMT Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Need to compare date time in GMT" Watch "Need to compare date time in GMT" New topic

Need to compare date time in GMT

Sankar Ramakrishnan

Joined: Aug 09, 2005
Posts: 4
I need to run a thread every 4 hours from GMT. This application can run from any Time zone (thats why GMT is preferred.) When the application starts i can do the processing and i need to set the sleep value of the thread. i am not able to to calculate the remaining milliseconds from the current time to the next scheduled time in GMT so that i can make set the thread to sleep for that particulcar period of time. Please help.

Phil Johnston

Joined: Jul 25, 2005
Posts: 6
Not sure if it's what you're after but:

package com;

import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

* Created by IntelliJ IDEA.
* User: Phil Johnston
* Date: 09-Aug-2005
* Time: 20:22:37
public class TestTimer
private static TimeZone GMT = TimeZone.getTimeZone("GMT");
private static int DELAY = 1000*60*60*4;

public static void main(String[] args)
Timer t = new Timer();
TimerTask task = new LocalTimerTask();

Calendar midnight = GregorianCalendar.getInstance(GMT);
midnight.set(2005, 8, 10, 0, 0, 0);

t.scheduleAtFixedRate(task, midnight.getTime(), DELAY);


private static class LocalTimerTask extends TimerTask
public void run()
// do my stuff
Sankar Ramakrishnan

Joined: Aug 09, 2005
Posts: 4
Thanks dude,
One small issue is it gets executed for the elapsed time.

I need to schedule every 4 hrs from GMT. but it should not execute for elapsed values.

i.e If i start the exe at 9 AM GMT, it should run next time at 12 PM GMT, not 2 times for 4 AM and 8 AM GMT.

Hope i am clear.

Sankar Ramakrishnan

Joined: Aug 09, 2005
Posts: 4
This is the method i wrote to get the no of milliseconds remaining to reach the next scheduled task.

private long getSleepInterval(int repeatHours)
Calendar cal = new GregorianCalendar();

Calendar newCal = new GregorianCalendar(TimeZone.getTimeZone("GMT"));

int maxLength = 24/repeatHours + 1;

long[] timeinMilliSeconds = new long[maxLength];

long timeinMillis = cal.getTime().getTime();

timeinMilliSeconds[0] = newCal.getTime().getTime();

if(timeinMilliSeconds[0] > timeinMillis)
return (timeinMilliSeconds[0] - timeinMillis);

for (int i = 1;i < maxLength ;i++ )
timeinMilliSeconds[i] = newCal.getTime().getTime();
if(timeinMilliSeconds[i] > timeinMillis)
return (timeinMilliSeconds[i] - timeinMillis);

return 0;

I agree. Here's the link:
subject: Need to compare date time in GMT
It's not a secret anymore!