Set System Date Using C#

Recently we were looking for a solution to set system date programmatically using C#. We found one of the solution that worked well for us because we only wanted to set the date not the time.

cheezycode-set-system-date-csharp



Most of the solution were updating the time as well. This solution helps to set only the date whereas time remains unchanged. This code snippet performs exactly the same steps as if you run it via command prompt. Same thing can be achieved via .bat file - we are just mimicking the process to update the date.

Refer below snippet -

void updateDate(string inputDate)
{
 ProcessStartInfo processInfo = new ProcessStartInfo();
 processInfo.WorkingDirectory = @"C:\Windows\System32";
 processInfo.UseShellExecute = true;
 processInfo.CreateNoWindow = true;
 processInfo.FileName = @"C:\Windows\System32\cmd.exe";
 processInfo.Verb = "runas";
 processInfo.Arguments = "/C date " + inputDate;
 System.Diagnostics.Process.Start(processInfo);
}

Just input your date in mm/dd/yy format, it will update the date. This solution has an added advantage to let you know if provided input date is not in the correct format. For e.g if I enter date as - 04/20/16898 then it prompts us with a message The system cannot accept the date entered. and let's you enter correct date.

You can also run this command date mm/dd/yy on command prompt. You need to have administrator rights to execute this command, so just open command prompt by right clicking it and run it as administrator.

Here is the demo we have created -




Let us know if you have any concerns or query. Happy Learning.



Comments

Popular posts from this blog

Just Maths - Views, View Groups and Layouts

Create Android Apps - Getting Started