Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 288
  • Last Modified:

How to change System DATE and TIME ?

How we can change the current system's Date and time from a Java application ?

Thanks in advance !

:-)

c_sh.
0
c_sh
Asked:
c_sh
1 Solution
 
ValeriCommented:
Listening...
0
 
muhotrepiusCommented:
One way i see is by using RunTime.exec(...) but that's OS dependant...
Or write a native library and use JNI.
0
 
sdussingerCommented:
Try this. It'll work on both Windows and Linux (although on Linux you'll need to run it as root, since normal users can't change the date):

-----------------------------------------------------------

import java.lang.Process;
import java.lang.Runtime;
import java.text.*;
import java.util.*;

public class SetDate
{
  static Process p;
  static Runtime rt=Runtime.getRuntime();

  public static void main(String args[])
  {

      String sourceDate = "2001-01-01T00:00:00";

      SimpleDateFormat sourceFormat = new SimpleDateFormat ("yyyy-MM-dd'T'hh:mm:ss");
      SimpleDateFormat winDateFormat = new SimpleDateFormat ("MM/dd/yy");
      SimpleDateFormat winTimeFormat = new SimpleDateFormat ("hh:mm:ss");
      SimpleDateFormat linuxDateTimeFormat = new SimpleDateFormat ("MMddhhmmyy.ss");

      Date d = sourceFormat.parse (sourceDate, new ParsePosition (0));

      String osName = System.getProperty("os.name");

      try
      {

          if (osName.equalsIgnoreCase ("linux"))
          {
            String linuxDate = linuxDateTimeFormat.format (d);

            p = rt.exec ("date " + linuxDate);
          }
          else
          {

            String winDate = winDateFormat.format (d);
            String winTime = winTimeFormat.format (d);

            p = rt.exec("cmd /c date " + winDate);
            p = rt.exec ("cmd /c time " + winTime);
          }
      }
      catch(Exception e)
      {
          e.printStackTrace();
      }
  }
}

-----------------------------------------------------------

HTH

--Steve
0
 
c_shAuthor Commented:
Thanks to all of you for giving attention to this problem, and a special thanks for Steve.

Steve, your code showed me the right direction to move on. Thanks for the cooperation.


:-)
c_sh.
0
 
sdussingerCommented:
Glad I could help...

--Steve
0

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now