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 ?

5
  • Because they don't use the console command to set the time; they probably use the SetSystemTime function, which (like any other Windows function) you can't easily access from Java. Commented Nov 10, 2015 at 9:53
  • Thank you for comment. So it wouldn't be possible to call that function with ProcessBuilder/Runtime, have to use JNI ? Commented Nov 10, 2015 at 9:55
  • 2
    Why can't you just use an NTP client directly? Commented Nov 10, 2015 at 9:55
  • It's just an assignment i am working on and am not allowed to do so. Commented Nov 10, 2015 at 9:56
  • To call methods that are not part of Java (but C ish) you'll have to use JNI stackoverflow.com/a/17035731/995891 (or jna). Or maybe you could start a script / custom exe via Runtime that allows to set time in ms precision Commented Nov 10, 2015 at 10:02

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.