Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the System Time in Java?

Tags:

Is it possible to change the System Time in Java?

It should run under Windows and Linux. I've tried it with the Runtime Class in but there is a problem with the permissions.

This is my code:

String cmd="date -s \""+datetime.format(ntp_obj.getDest_Time())+"\""; try {     Runtime.getRuntime().exec(cmd); } catch (IOException e1) { // TODO Auto-generated catch block   e1.printStackTrace(); } System.out.println(cmd); 

The output of cmd is:

date -s "06/01/2011 17:59:01" 

But the System time is the same as before.

I will set the time because I am writing an NTP-Client and there I get the time from a NTP-Server and will set it.

like image 637
joen Avatar asked Jun 01 '11 15:06

joen


People also ask

How do you set a specific time in Java?

The setTime() method of Java Date class sets a date object. It sets date object to represent time milliseconds after January 1, 1970 00:00:00 GMT. Parameters: The function accepts a single parameter time which specifies the number of milliseconds. Return Value: It method has no return value.

How can I get system time in Java?

Java. time. LocalTime − This class represents a time object without time zone in ISO-8601 calendar system. The now() method of this class obtains the current time from the system clock.

How do I get system on time?

To retrieve the system time, use the GetSystemTime function. GetSystemTime copies the time to a SYSTEMTIME structure that contains individual members for month, day, year, weekday, hour, minute, second, and milliseconds. It is easy to display this format to a user.


1 Answers

Java doesn't have an API to do this.

Most system commands to do it require admin rights, so Runtime can't help unless you run the whole process as administrator/root or you use runas/sudo.

Depending on what you need, you can replace System.currentTimeMillis(). There are two approaches to this:

  1. Replace all calls to System.currentTimeMillis() with a call to a static method of your own which you can replace:

    public class SysTime {     public static SysTime INSTANCE = new SysTime();      public long now() {         return System.currentTimeMillis();     } } 

    For tests, you can overwrite INSTANCE with something that returns other times. Add more methods to create Date and similar objects.

  2. If not all code is under your control, install a ClassLoader which returns a different implementation for System. This is more simple than you'd think:

    @Override public Class<?> loadClass( String name, boolean resolve ) {     if ( "java.lang.System".equals( name ) ) {         return SystemWithDifferentTime.class;     }      return super.loadClass( name, resolve ); } 
like image 68
Aaron Digulla Avatar answered Sep 25 '22 22:09

Aaron Digulla