Change date and time in Windows using C and C++


In this post we will see how to change ‘date‘ and ‘time‘ in Windows using only C++ or C and any of the IDE(compiler)-Code::Blocks,Dev ,Visual Studio.With this method we need not use the system setting to change the date or the time,all you need to do is execute one code of line each for ‘date’ and ‘time’ to change them,easy huh? well then let’s get started.

Note to change the date and the time in your system ,it is required that your IDE should have “administrator privileges“.To give your IDE(Code:::block ,Visual Studio,Dev etc.) an “administrator privileges” right click on the IDE icon and choose the option “Run as administrator“.This will make sure that your IDE have the right to customize changes in your system at it’s will.After this proceed on to the main part-writing the code.

Changing the date

In C and C++ we have a library name <cstdlib> which includes a function known as ‘system‘.This function can help you interact with the Windows command prompt without actually using the command prompt interface.So to speak ‘system’ function accept the commands of the command prompt and execute them without any complaint.

Link : C++ cstdlib system function

To change the date,the argument passed to the system function is ‘DATE‘.Passing this command will give you an option to set the date correctly.

Code example : C++ source code

#include <iostream>
#include <cstdlib>

using namespace std ;

int main( )
{
system( “DATE” );

cin.get( );
return 0;
}

Code example : C source code

#include <stdio.h>
#include <stdlib.h>

using namespace std ;

int main( )
{
system( “DATE” );

getchar( );
return 0;
}

Running either of the code above will give you an output console as shown below.

Change date using C and C++

Simply enter the date in the format “09-11-2018” and press ‘Enter‘.You will notice the date is changed.


Changing the time

Changing the ‘time‘ in Windows is also similar to changing the ‘date’ as described above.We will still use the function ‘system’ and the command to be passed is ‘TIME‘ instead of the ‘DATE’ that is use to change the date.A source code of C++ and and C is shown below.

Code example : C++ source code

#include <iostream>
#include <cstdlib>

using namespace std ;

int main( )
{
system( “TIME” );

cin.get( );
return 0;
}

Code example : C source code

#include <stdio.h>
#include <stdlib.h>

using namespace std ;

int main( )
{
system( “TIME” );

getchar( );
return 0;
}

Running either of the code above will give an output console as shown below.

Change time using C and C++

Enter the time in the 24 hours format,for instance if you want to change the time to ’10:30 pm’ ,simply enter “20:30:00”.And press Enter.After this check if the time has been changed,I am sure it has 🙂 .