How to set a computer's date

Best practices, code snippets for common functionality, examples, and guidelines.
jmchughsmart
Posts: 28
Joined: Wed Aug 12, 2015 6:44 pm

How to set a computer's date

Post by jmchughsmart » Mon Sep 14, 2015 12:31 pm

I have a testcase where the start date on the computer needs to be 09/14/15.
I want to get todays date change it and the be able to reset to original date.
Does anyone have code for this??
Thanks.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: How to set a computer's date

Post by odklizec » Mon Sep 14, 2015 1:22 pm

Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

User avatar
jasoncleo
Posts: 37
Joined: Mon Jun 08, 2015 7:37 am

Re: How to set a computer's date

Post by jasoncleo » Tue Oct 13, 2015 3:40 am

This one can be quite tricky based on whether you need the test to manipulate the date/time on just the local machine or on a remote server.

We had a similar requirement to manage date/time, but our tests had to manage it on both the local machine and a remote server to ensure that business hours accounting logic was being handled correctly.

Basically WMI is going to be your friend here for achieving this, and the same logic can be used regardless of whether the target machine is "localhost" or a remote machine. You will need user credentials with admin permissions though.

We ended up building a class that provided the following:
- Turn the Windows Time Service On/Off. If you don't disable this service, then the machine will reset the time when the next sync with Internet time comes around. It isn't that often (once every couple of days or something) but you don't want it to happen in the middle of a test. You also want to turn it back on and force a resync of time, so that the test machine can be used for other stuff without having garbage date/time settings.
- Get the date/time. If you need to confirm that the values are correct. Very easy if you're just working with localhost, but with a remote server, this was harder because WMI doesn't let you get console output, so we had to write to a file, within a public folder on that remote machine, and then read it back.
- Set the date/time. WMI can run a host of commandline items remotely, and the windows shell commands of "date" / "time" / "tzutil" (if you need to change timezone), will tick all the boxes you need.

As odklizec has mentioned, there are plenty of code samples around. If you're working with localhost, you should find it easy to knock together with StackOverflow. :)