Tek-Tips is the largest IT community on the Internet today!
Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!
-
Congratulations bkrike on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!
-
Home
-
Forums
-
Software
-
Programmers
-
Development Methodologies and Architecture
-
Win API (Microsoft)
You should upgrade or use an alternative browser.
Which Windows API function sets the system date and time?
-
Thread starternagyf
-
Start date
- Status
- Not open for further replies.
-
#1
How can I retain the creation and modification dates of the database objects when I import them?
Can I set these properties to a past date programatically?
I plan this solution:
1. Read the true system date and time.
In a cycle for each objects to be imported:
2. Read the modifiaction date of the actual object.
3. Set the system date back to the read date.
4. Import the actual object.
Repeat steps #2-4.
5. Reset the system date and time to its true value.
How can I do step #3?
How can I set the system date back to the value read in step#2 programmatically? Is there any Visual Basic object or an API call for date and time setting?
I simplify my question:
Which Windows API function sets the system date and time?
Where can I read about its usage?
TIA
[tt]
Ferenc Nagy
|\ /~ ~~|~~~ nagyf@alpha0.iki.kfki.hu Fax: (36-1)-392-2529 New!
| \ | | Institute of Isotope and Surface Chemistry
| \ | -+- 1525 Bp. POB 77. Tel. 36-1)-392-2550
| \| |
`-‘ ‘ `-‘ "The goal of the life is the struggle itself"
[/tt]
-
#2
Private Type SYSTEMTIME
wYear As Integer
wMonth As Integer
wDayOfWeek As Integer
wDay As Integer
wHour As Integer
wMinute As Integer
wSecond As Integer
wMilliseconds As Integer
End Type
Private Declare Function SetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME) As Long
Private Declare Sub GetSystemTime Lib "kernel32" (lpSystemTime As SYSTEMTIME) Good Luck
—————
As a circle of light increases so does the circumference of darkness around it. — Albert Einstein
- Status
- Not open for further replies.
Similar threads
-
Home
-
Forums
-
Software
-
Programmers
-
Development Methodologies and Architecture
-
Win API (Microsoft)
-
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.
Как использовать OAuth2 со Spring Security в Java
Javaican 14.05.2025
Протокол OAuth2 часто путают с механизмами аутентификации, хотя по сути это протокол авторизации. Представьте, что вместо передачи ключей от всего дома вашему другу, который пришёл полить цветы, вы. . .
Анализ текста на Python с NLTK и Spacy
AI_Generated 14.05.2025
NLTK, старожил в мире обработки естественного языка на Python, содержит богатейшую коллекцию алгоритмов и готовых моделей. Эта библиотека отлично подходит для образовательных целей и. . .
Реализация DI в PHP
Jason-Webb 13.05.2025
Когда я начинал писать свой первый крупный PHP-проект, моя архитектура напоминала запутаный клубок спагетти. Классы создавали другие классы внутри себя, зависимости жостко прописывались в коде, а о. . .
Обработка изображений в реальном времени на C# с OpenCV
stackOverflow 13.05.2025
Объединение библиотеки компьютерного зрения OpenCV с современным языком программирования C# создаёт симбиоз, который открывает доступ к впечатляющему набору возможностей. Ключевое преимущество этого. . .
POCO, ACE, Loki и другие продвинутые C++ библиотеки
NullReferenced 13.05.2025
В C++ разработки существует такое обилие библиотек, что порой кажется, будто ты заблудился в дремучем лесу. И среди этого многообразия POCO (Portable Components) – как маяк для тех, кто ищет. . .
Паттерны проектирования GoF на C#
UnmanagedCoder 13.05.2025
Вы наверняка сталкивались с ситуациями, когда код разрастается до неприличных размеров, а его поддержка становится настоящим испытанием. Именно в такие моменты на помощь приходят паттерны Gang of. . .
Создаем CLI приложение на Python с Prompt Toolkit
py-thonny 13.05.2025
Современные командные интерфейсы давно перестали быть черно-белыми текстовыми программами, которые многие помнят по старым операционным системам. CLI сегодня – это мощные, интуитивные и даже. . .
Конвейеры ETL с Apache Airflow и Python
AI_Generated 13.05.2025
ETL-конвейеры – это набор процессов, отвечающих за извлечение данных из различных источников (Extract), их преобразование в нужный формат (Transform) и загрузку в целевое хранилище (Load). . . .
Выполнение асинхронных задач в Python с asyncio
py-thonny 12.05.2025
Современный мир программирования похож на оживлённый мегаполис – тысячи процессов одновременно требуют внимания, ресурсов и времени. В этих джунглях операций возникают ситуации, когда программа. . .
Работа с gRPC сервисами на C#
UnmanagedCoder 12.05.2025
gRPC (Google Remote Procedure Call) — открытый высокопроизводительный RPC-фреймворк, изначально разработанный компанией Google. Он отличается от традиционых REST-сервисов как минимум тем, что. . .
1. Windows API to modify the system time
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SystemTime lpSystemTime);
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SystemTime lpSystemTime);
[DllImport("Kernel32.dll")]
public static extern void GetSystemTime(ref SystemTime lpSystemTime);
[DllImport("Kernel32.dll")]
public static extern bool SetSystemTime(ref SystemTime lpSystemTime);
Note:
① The first two APIs are for obtaining local time and setting local time, and the latter two APIs are for obtaining system time and setting system time.
② The difference is that the system time is UTC time, and the local time is the time we actually see on the computer.
③ If the computer’s time zone is set to China, the local time is Beijing time, which is 8 hours away from the system time.
2. Related structure struct type
[StructLayout(LayoutKind.Sequential)]
struct SystemTime
{
[MarshalAs(UnmanagedType.U2)]
internal ushort year; // year
[MarshalAs(UnmanagedType.U2)]
internal ushort month; // month
[MarshalAs(UnmanagedType.U2)]
internal ushort dayOfWeek; // week
[MarshalAs(UnmanagedType.U2)]
internal ushort day; // day
[MarshalAs(UnmanagedType.U2)]
internal ushort hour; // hour
[MarshalAs(UnmanagedType.U2)]
internal ushort minute; // minute
[MarshalAs(UnmanagedType.U2)]
internal ushort second; // second
[MarshalAs(UnmanagedType.U2)]
internal ushort milliseconds; // milliseconds
}
3. Call Windows API to obtain and modify local/system time
/// <summary>
/// Get local time
/// </summary>
/// <returns></returns>
public DateTime getLocalTime()
{
SystemTime sysTime = new SystemTime();
GetLocalTime(ref sysTime);
return SystemTime2DateTime(sysTime);
}
/// <summary>
/// Set local time
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public bool setLocalTime(DateTime dateTime)
{
if (grantPrivilege(SE_SYSTEMTIME_NAME))
{
// Authorization is successful
SystemTime sysTime = DateTime2SystemTime(dateTime);
bool success = SetLocalTime(ref sysTime);
if (!revokePrivilege(SE_SYSTEMTIME_NAME))
{
// The revocation failed
}
return success;
}
// authorization failed
return false;
}
/// <summary>
/// Get system time
/// </summary>
/// <returns></returns>
public DateTime getSystemTime()
{
SystemTime sysTime = new SystemTime();
GetSystemTime(ref sysTime);
return SystemTime2DateTime(sysTime);
}
/// <summary>
/// Set the system time (UTC)
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public bool setSystemTime(DateTime dateTime)
{
if (grantPrivilege(SE_SYSTEMTIME_NAME))
{
// Authorization is successful
SystemTime sysTime = DateTime2SystemTime(dateTime);
bool success = SetSystemTime(ref sysTime);
if (!revokePrivilege(SE_SYSTEMTIME_NAME))
{
// The revocation failed
}
return success;
}
// authorization failed
return false;
}
/// <summary>
/// Convert SystemTime to DateTime
/// </summary>
/// <param name="sysTime"></param>
/// <returns></returns>
public DateTime SystemTime2DateTime(SystemTime sysTime)
{
return new DateTime(sysTime.year, sysTime.month, sysTime.day, sysTime.hour, sysTime.minute, sysTime.second, sysTime.milliseconds);
}
/// <summary>
/// Convert DateTime to SystemTime
/// </summary>
/// <param name="dateTime"></param>
/// <returns></returns>
public SystemTime DateTime2SystemTime(DateTime dateTime)
{
SystemTime sysTime = new SystemTime();
sysTime.year = Convert.ToUInt16(dateTime.Year);
sysTime.month = Convert.ToUInt16(dateTime.Month);
sysTime.day = Convert.ToUInt16(dateTime.Day);
sysTime.hour = Convert.ToUInt16(dateTime.Hour);
sysTime.minute = Convert.ToUInt16(dateTime.Minute);
sysTime.second = Convert.ToUInt16(dateTime.Second);
sysTime.milliseconds = Convert.ToUInt16(dateTime.Millisecond);
return sysTime;
}
4. Automatically synchronize local time
Obtain the time from the NTP server and automatically modify the local time, which can realize automatic synchronization of the local time. For how to get the time from the NTP server, you can refer to:Get time from NTP server (C#)
5. Matters needing attention:
① GrantPrivilege (SE_SYSTEMTIME_NAME) and revokePrivilege (SE_SYSTEMTIME_NAME) in the above code are used to grant/revoke the permission of process modification time, no specific code is given here;
② You can refer to Zifeng’s blog post:Click to open the link
③ You can also directlyDownload code:Click to open the link
④ You can also directly delete the above authorization and revoke codes, and you can modify the time by running the program as an administrator.
WIN 32 API поддерживает пять форматов времени, и функции для получения времени и преобразования форматов с учетом часовых поясов. Вот эти типы.
System SYSTEMTIME Года, месяц, день, час, секунда, и миллисекунды, взятые с внутренних аппаратных часов. File FILETIME 100-наносекунд интервалов 1 Января, 1601. Local SYSTEMTIME ИЛИ FILETIME Системное время или файловое время преобразованное в локальное время с учетом часовых поясов. MS-DOS WORD Упакованное 16-битовое слово для даты другое для времени. Windows DWORD Количество миллисекунд с тех пор как загруженная система; повторяется каждые 49.7 дней.
Как видите у нас время храниться в WORD, DWROD и еще есть две струтуры. Структура SYSTEMTIME хранит дату и время используя отдельные поля для месяца, дня, года, дня недели, часа, минут, секунд и миллисекунд.
typedef struct _SYSTEMTIME { WORD wYear; // Указывает текущий год WORD wMonth; // Текущий месяц; Январь = 1, Февраль = 2, и так далее WORD wDayOfWeek; // Текущий день недели; Воскресенье = 0, Понедельник = 1, и так далее. WORD wDay; // Текущий день месяца. WORD wHour; // Час. WORD wMinute; // Минуты. WORD wSecond; // Секунды. WORD wMilliseconds; // Миллисекунды. } SYSTEMTIME;
Структура FILETIME — это 64-х разрядное значение, представляющее число сто-наносекундных интервалов, прошедших с первого Января 1601 года:
typedef struct _FILETIME { DWORD dwLowDateTime; // Младшие 32 бита времени файла DWORD dwHighDateTime; // Старшие 32 бита времени файла } FILETIME;