Pregunta

¿Cómo puedo cambiar la fecha del sistema local & amp; tiempo programáticamente con C #?

¿Fue útil?

Solución

Aquí es donde encontré la respuesta.

Lo he vuelto a publicar aquí para mejorar la claridad.

Defina esta estructura:

[StructLayout(LayoutKind.Sequential)]
public struct SYSTEMTIME
{
    public short wYear;
    public short wMonth;
    public short wDayOfWeek;
    public short wDay;
    public short wHour;
    public short wMinute;
    public short wSecond;
    public short wMilliseconds;
}

Agregue el siguiente método extern a su clase:

[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool SetSystemTime(ref SYSTEMTIME st);

Luego llame al método con una instancia de su estructura como esta:

SYSTEMTIME st = new SYSTEMTIME();
st.wYear = 2009; // must be short
st.wMonth = 1;
st.wDay = 1;
st.wHour = 0;
st.wMinute = 0;
st.wSecond = 0;

SetSystemTime(ref st); // invoke this method.

Otros consejos

Puede usar una llamada a un comando de DOS, pero la invocación de la función en el dll de Windows es una mejor manera de hacerlo.

public struct SystemTime
{
    public ushort Year;
    public ushort Month;
    public ushort DayOfWeek;
    public ushort Day;
    public ushort Hour;
    public ushort Minute;
    public ushort Second;
    public ushort Millisecond;
};

[DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
public extern static void Win32GetSystemTime(ref SystemTime sysTime);

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

private void button1_Click(object sender, EventArgs e)
{
    // Set system date and time
    SystemTime updatedTime = new SystemTime();
    updatedTime.Year = (ushort)2009;
    updatedTime.Month = (ushort)3;
    updatedTime.Day = (ushort)16;
    updatedTime.Hour = (ushort)10;
    updatedTime.Minute = (ushort)0;
    updatedTime.Second = (ushort)0;
    // Call the unmanaged function that sets the new date and time instantly
    Win32SetSystemTime(ref updatedTime);
}  

Muchos puntos de vista y enfoques excelentes ya están aquí, pero aquí hay algunas especificaciones que actualmente se omiten y que creo que podrían tropezar y confundir a algunas personas.

  1. En Windows Vista, 7, 8 OS esto requerirá un aviso UAC para obtener los derechos administrativos necesarios para ejecutar con éxito el SetSystemTime función. La razón es que el proceso de llamada necesita el privilegio SE_SYSTEMTIME_NAME .
  2. La función SetSystemTime espera una estructura SYSTEMTIME en tiempo universal coordinado (UTC) . De lo contrario, no funcionará como se desea.

Dependiendo de dónde / cómo esté obteniendo sus valores de DateTime , podría ser mejor hacerlo de forma segura y usar ToUniversalTime () antes de establecer los valores correspondientes en SYSTEMTIME struct.

Ejemplo de código:

DateTime tempDateTime = GetDateTimeFromSomeService();
DateTime dateTime = tempDateTime.ToUniversalTime();

SYSTEMTIME st = new SYSTEMTIME();
// All of these must be short
st.wYear = (short)dateTime.Year;
st.wMonth = (short)dateTime.Month;
st.wDay = (short)dateTime.Day;
st.wHour = (short)dateTime.Hour;
st.wMinute = (short)dateTime.Minute;
st.wSecond = (short)dateTime.Second;

// invoke the SetSystemTime method now
SetSystemTime(ref st); 
  1. PInvoke para llamar a Win32 API SetSystemTime, ( ejemplo )
  2. Clases de System.Management con la clase WMI Win32_OperatingSystem y llame a SetDateTime en esa clase.

Ambos requieren que se le haya otorgado al llamante SeSystemTimePrivilege y que este privilegio esté habilitado.

Use esta función para cambiar la hora del sistema (probado en la ventana 8)

 void setDate(string dateInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C date " + dateInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }
void setTime(string timeInYourSystemFormat)
    {
        var proc = new System.Diagnostics.ProcessStartInfo();
        proc.UseShellExecute = true;
        proc.WorkingDirectory = @"C:\Windows\System32";
        proc.CreateNoWindow = true;
        proc.FileName = @"C:\Windows\System32\cmd.exe";
        proc.Verb = "runas";
        proc.Arguments = "/C time " + timeInYourSystemFormat;
        try
        {
            System.Diagnostics.Process.Start(proc);
        }
        catch
        {
            MessageBox.Show("Error to change time of your system");
            Application.ExitThread();
        }
    }

Ejemplo: Llamada en método de carga de formulario setDate (" 5-6-92 "); setTime (" 2: 4: 5 AM ");

Como lo mencioné en un comentario, aquí hay un contenedor C ++ / CLI:

#include <windows.h>
namespace JDanielSmith
{
    public ref class Utilities abstract sealed /* abstract sealed = static */
    {
    public:
        CA_SUPPRESS_MESSAGE("Microsoft.Security", "CA2122:DoNotIndirectlyExposeMethodsWithLinkDemands")
        static void SetSystemTime(System::DateTime dateTime) {
            LARGE_INTEGER largeInteger;
            largeInteger.QuadPart = dateTime.ToFileTimeUtc(); // "If your compiler has built-in support for 64-bit integers, use the QuadPart member to store the 64-bit integer."


            FILETIME fileTime; // "...copy the LowPart and HighPart members [of LARGE_INTEGER] into the FILETIME structure."
            fileTime.dwHighDateTime = largeInteger.HighPart;
            fileTime.dwLowDateTime = largeInteger.LowPart;


            SYSTEMTIME systemTime;
            if (FileTimeToSystemTime(&fileTime, &systemTime))
            {
                if (::SetSystemTime(&systemTime))
                    return;
            }


            HRESULT hr = HRESULT_FROM_WIN32(GetLastError());
            throw System::Runtime::InteropServices::Marshal::GetExceptionForHR(hr);
        }
    };
}

El código del cliente C # ahora es muy simple:

JDanielSmith.Utilities.SetSystemTime(DateTime.Now);

¡Ten cuidado! Si elimina la propiedad no utilizada de la estructura, establece el tiempo incorrecto. He perdido 1 día por esto. Creo que el orden de la estructura es importante.

Esta es la estructura correcta:

public struct SystemTime
        {
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Millisecond;

        };

Si ejecuta SetSystemTime (), funciona como se esperaba. Para la prueba, configuré la hora de la siguiente manera;

SystemTime st = new SystemTime();
st.Year = 2019;
st.Month = 10;
st.Day = 15;
st.Hour = 10;
st.Minute = 20;
st.Second = 30;

SetSystemTime(ref st);

El horario establecido: 15.10.2019 10:20, está bien.

Pero elimino la propiedad DayOfWeek que no se usa;

public struct SystemTime
            {
                public ushort Year;
                public ushort Month;
                public ushort Day;
                public ushort Hour;
                public ushort Minute;
                public ushort Second;
                public ushort Millisecond;

            };

SystemTime st = new SystemTime();
    st.Year = 2019;
    st.Month = 10;
    st.Day = 15;
    st.Hour = 10;
    st.Minute = 20;
    st.Second = 30;

    SetSystemTime(ref st);

Ejecute el mismo código pero el tiempo establecido en: 10.10.2019 20:30

Tenga cuidado de ordenar y todos los campos de la estructura SystemTime. Yusuf

  

Argumentos de proceso = " / C Fecha: " + dateInYourSystemFormat;

Esta es la función de trabajo:

void setDate(string dateInYourSystemFormat)
{
    var proc = new System.Diagnostics.ProcessStartInfo();
    proc.UseShellExecute = true;
    proc.WorkingDirectory = @"C:\Windows\System32";
    proc.CreateNoWindow = true;
    proc.FileName = @"C:\Windows\System32\cmd.exe";
    proc.Verb = "runas";
    proc.Arguments = "/C Date:" + dateInYourSystemFormat;
    try
    {
        System.Diagnostics.Process.Start(proc);
    }
    catch
    {
        MessageBox.Show("Error to change time of your system");
        Application.ExitThread();
    }
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top