raven-ai
raven-ai

Reputation: 253

How to set system time in Windows 10 IoT?

Is there a way to set system time from my app running on a Raspberry Pi 2 in Windows 10 IoT Core Insider Preview?

This doesn't work for lack of kernel32.dll

    [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
    extern static bool Win32SetSystemTime(ref SystemTime sysTime);

Upvotes: 16

Views: 25291

Answers (8)

Fables Alive
Fables Alive

Reputation: 2798

1-New Universal Project
2-Add Reference>Extensions>Windows IOT Extensions for UWP
3- Put a button, a datepicker and a timepicer control on your MainPage.xaml
and

private void buttonSetSystemDatetime_Click(object sender, RoutedEventArgs e)
        {
            DateTimeOffset dto = datePicker1.Date+ timePicker1.Time;
            Windows.System.DateTimeSettings.SetSystemDateTime(dto);
        }

4- in poject settings> set your target version and min version 10.0; build 16299
5- double click appxmanifest > Capabilities > check ON "System Management"

6- run app in IOT and press button. than return to default app. voila! system datetime changed.

note: rather to set it everytime. I offer you buy a cheap rtc (real time clock) module. (also needs extra coding)

Upvotes: 8

Parsa Karami
Parsa Karami

Reputation: 722

refer to Microsoft API Reference Docs and in the Windows.System namespace you can sets the system date and time with SetSystemDateTime method.

but you must know it`s available in

  • Windows IoT Extension SDK (introduced v10.0.16225.0) and above

you can use DateTimeSettings static class

public static class DateTimeSettings

then call SetSystemDateTime static method and send your object of DateTimeOffset type for setting date and time on Windows Iot.

public static void SetSystemDateTime(DateTimeOffset utcDateTime)

https://learn.microsoft.com/en-us/uwp/api/windows.system.datetimesettings

Upvotes: 1

Nathan Price
Nathan Price

Reputation: 21

Use Renci SSH shell to sign back into the device as an administrator and then use powershell command to set date and time.

public static int SshCommand(string command, out string dataOut, out string error)
    {

        dataOut = "";
        error = "";

        try
        {

            using (var client = new SshClient("127.0.0.1", USER_NAME, PASSWORD))
            {
                client.Connect();
                //command = "powershell -Command " + "\u0022" + "set-date -date '8/10/2017 8:30:00 AM'" + "\u0022";
                //command = "netsh interface ip show config";
                var cmd = client.RunCommand(command);
                var output = cmd.Result;
                client.Disconnect();
            }

            return 1;
        }
        catch (Exception ex)
        {
            error = ex.Message;
            return 0;
        }

    }


public static int SSHSetDateTime(DateTime dateTime)
    {

        // Variables
        int returnValue = 0;
        string command;
        string error;
        string dataOut;

        // Build date
        command = String.Format("powershell -Command \u0022set-date -date '{0:M/d/yyyy H:mm:ss tt}'\u0022", dateTime);

        //Build date
        if (SystemEx.SshCommand(command, out dataOut, out error) == 1)
        {
            // Ok
            returnValue = 1;
        }

        // Return
        return returnValue;

    }

Upvotes: 2

Joel
Joel

Reputation: 2361

I used a RTC to set the time on my Raspberry Pi. While Windows-iot doesn't have native support for initializing the Raspberry Pi's software clock from a real time clock after several hours of considering options I found something that works for me.

I made a console program that can either save the system time to the RTC or read the time in the RTC and print it as a string. I made a power shell script that will run this program at the time of system startup to get the time from the real time clock and pass the string to the set-date command.

Details are here: http://www.codeproject.com/Articles/1113626/Adding-the-Missing-Real-Time-Clock-to-Windows-IoT

Upvotes: 3

GGleGrand
GGleGrand

Reputation: 1650

You can call any PowerShell routine from C# on UWP/IoT-Core systems. As such, the PowerShell commands are always available in/to your App.

For an example, see the ProcessLauncher sample on GitHub.

ALTERNATIVE, schedule a startup PS script as follows:

Run PowerShell as an Administrator on the board (Press the Windows button, and start typing PowerShell, right click on the icon and select “Run as Administrator”).

Set-ExecutionPolicy RemoteSigned

PuTTy to RPi as admin and:

setx PATH "%PATH%;C:\Windows\System32"

schtasks /create /tn "StartupPowerShell" /tr c:\Startup.bat /sc onstart /ru SYSTEM

Startup.bat

powershell -command "C:\IotCoreStartup.ps1"

IotCoreStartup.ps

$logFile = 'C:\StartupLog.txt'

get-date > $logFile

tzutil /s "UTC" >> $logFile

# set alternate time servers
"Setting additional time servers" >> $logFile
w32tm /config /syncfromflags:manual /manualpeerlist:"0.windows.time.com 1.pool.ntp.org" >> $logFile

Deleting a scheduled task if required:

schtasks /Delete /TN "StartupPowerShell"

Running a scheduled task if to test:

schtasks /Run /tn "StartupPowerShell"

Upvotes: 4

Paul DeCarlo
Paul DeCarlo

Reputation: 416

I realize you are asking how to do this programmatically, however, the following should provide enough information to create a PS script to run at startup.

Remote Access Raspberry Pi via Powershell

1.) Run the Windows 10 IoT Core Watcher utility (C:\Program Files (x86)\Microsoft IoT\WindowsIoTCoreWatcher.exe) on your development PC and copy your Raspberry Pi IP address by right-clicking on the detected device and selecting Copy IP Address.

◦Click the windows "Start" button

◦Type "WindowsIoTCoreWatcher" to pull it up in the search results

◦You may want to right click on the program name and select "Pin to Start" to pin it to your start screen for easy access

◦Press Enter to run it

◦Your device should appear in the list within 5 seconds or so. If it does not, close the Windows 10 IoT Core Watcher, and relaunch it again

Windows IoT Core Watcher

2.) Launch an administrator PowerShell console on your local PC. The easiest way to do this is to type "powershell" in the Search the web and Windows textbox near the Windows Start Menu. Windows will find PowerShell on your machine. Right-click the Windows PowerShell entry and select Run as administrator. The PS console will show.

Running Powershell as Administrator

3.) You may need to start the WinRM service on your desktop to enable remote connections. From the PS console type the following command:

 net start WinRM 

4.) From the PS console, type the following command, substituting '' with the IP value copied in prev:

 Set-Item WSMan:\localhost\Client\TrustedHosts -Value <machine-name or IP Address>

5.Type Y and press Enter to confirm the change.

6.Now you can start a session with you Windows IoT Core device. From you administrator PS console, type:

Enter-PSSession -ComputerName <IP Address> -Credential localhost\Administrator

7.In the credential dialog enter the following default password:

p@ssw0rd

Note: The connection process is not immediate and can take up to 30 seconds.

If you successfully connected to the device, you should see the IP address of your device before the prompt.

Connected to the Raspberry using PS

Renaming your Device and Setting the Date and Time

1.To change the computer name, use the setcomputername utility. In PowerShell, type the following command.

setcomputername

2.The date and time on the Pi must be correct for the security tokens used to publish to Azure later in the lab to be valid. To check the current time zone setting on the Pi, type:

tzutil /g

3.If the time zone reported is not correct, you can find a list of valid time zones using (you may need to increase the buffer size on your powershell window):

tzutil /l

4.To set the time zone, locate the id of the time zone you want from the step above, then use:

tzutil /s "Your TimeZone Name"

For example, for "Pacific Standard Time"

tzutil /s "Pacific Standard Time"

5.To check the date on the Raspberry Pi, type

Get-Date

6.If the date or time is incorrect, use the Set-Date utility

Set-Date "mm/dd/yy hh:mm:ss AM/PM"

For Example, if it was 12:15 pm on January 3rd, 2016:

Set-Date "01/03/16 12:15 PM"

7.Reboot the device for the change to take effect. You can use the shutdown command as follows:

shutdown /r /t 0

Upvotes: 1

kiran
kiran

Reputation: 127

First, connect to your Pi 2 using PowerShell.

Use the command set-date to set the time. For example, if you want to set the date to Saturday, October 3, 2015, 2:00PM, you would type set-date 10/3/2015 2:00PM.

The command tzutil sets the time zone. Type tzutil /? for usage

Upvotes: 11

raven-ai
raven-ai

Reputation: 253

Seemingly as of now there appears to be no way to actually edit the system time, but here is a work around I came up with to get correct time in your app at least. I created a TimeManager class, the important parts are as follows.

Get the correct time how ever you want (e.g. NTP, other network time, user input, etc) and input into the UpdateOffset method.

In the rest of the App use TimeManager.Now instead of DateTime.Now

    static TimeSpan _offset = new TimeSpan(0,0,0);
    public static TimeSpan CurrentOffset //Doesn't have to be public, it is for me because I'm presenting it on the UI for my information
    {
        get { return _offset; }
        private set { _offset = value; }
    }

    public static DateTime Now
    {
        get
        {
            return DateTime.Now - CurrentOffset;
        }
    }

    static void UpdateOffset(DateTime currentCorrectTime) //May need to be public if you're getting the correct time outside of this class
    {
        CurrentOffset = DateTime.UtcNow - currentCorrectTime;
        //Note that I'm getting network time which is in UTC, if you're getting local time use DateTime.Now instead of DateTime.UtcNow. 
    }

I also suggest adding things like tracking the last update time, and flag to indicate whether the time has ever been updated, just didn't want to clutter up the code sample.

Upvotes: 3

Related Questions