0

Would it be possible to set system time with milliseconds component on Windows OS using Java? I am trying to synchronize clocks between couple of computers but the OS API seems to offer only set time in format: HH:MM:SS.

This is what i tried:

public static void main(String[] args) throws InterruptedException, IOException {


    String time="10:00:20"; // this works

    String timeWithMiliseconds = "10:00:20.100"; // this doesn't change time at all

    Runtime rt = Runtime.getRuntime();
    rt.exec("cmd /C time " + time);


}

I am wondering how do NTP clients work if it's not possible to set milliseconds component ?

One way to deal with this issue could be to calculate time in milliseconds when server should reach next second, and sleep for that time. Is there a better, more direct way to achieve this ?

John
  • 5,189
  • 2
  • 38
  • 62
  • Because they don't use the console command to set the time; they probably use the [SetSystemTime](https://msdn.microsoft.com/en-us/library/windows/desktop/ms724942%28v=vs.85%29.aspx) function, which (like any other Windows function) you can't easily access from Java. – user253751 Nov 10 '15 at 09:53
  • Thank you for comment. So it wouldn't be possible to call that function with ProcessBuilder/Runtime, have to use JNI ? – John Nov 10 '15 at 09:55
  • 2
    Why can't you just use an NTP client directly? – Andy Turner Nov 10 '15 at 09:55
  • It's just an assignment i am working on and am not allowed to do so. – John Nov 10 '15 at 09:56
  • To call methods that are not part of Java (but C ish) you'll have to use JNI http://stackoverflow.com/a/17035731/995891 (or [jna](http://blog.caplin.com/2014/12/01/jnajni/)). Or maybe you could start a script / custom exe via `Runtime` that allows to set time in ms precision – zapl Nov 10 '15 at 10:02

1 Answers1

2

As mentioned by immibis you could use the Windows function SetSystemTime to set the time.

Find below a snippet which call the Windows function using JNA 4.2

Kernel32 kernel = Kernel32.INSTANCE;
WinBase.SYSTEMTIME newTime = new WinBase.SYSTEMTIME();
newTime.wYear = 2015; 
newTime.wMonth = 11;
newTime.wDay = 10;
newTime.wHour = 12;
newTime.wMinute = 0;
newTime.wSecond = 0;
newTime.wMilliseconds = 0;
kernel.SetSystemTime(newTime);

For further information have a look into the sources of JNA and on those links SetSystemTime Windows function and SYSTEMTIME structure.

An introduction to JNA from 2009. Simplify Native Code Access with JNA

SubOptimal
  • 22,518
  • 3
  • 53
  • 69