FileSetTime: Sommer-/Winterzeit?

Post a reply


In an effort to prevent automatic submissions, we require that you complete the following challenge.
Smilies
:D :) ;) :( :o :shock: :? 8-) :lol: :x :P :oops: :cry: :evil: :twisted: :roll: :!: :?: :idea: :| :mrgreen: :geek: :ugeek: :arrow: :angel: :clap: :crazy: :eh: :lolno: :problem: :shh: :shifty: :sick: :silent: :think: :thumbup: :thumbdown: :salute: :wave: :wtf: :yawn: :facepalm: :bravo: :dance: :beard: :morebeard: :xmas: :HeHe: :trollface: :cookie: :rainbow: :monkeysee: :monkeysay: :happybday: :headwall: :offtopic: :superhappy: :terms: :beer:
View more smilies

BBCode is ON
[img] is OFF
[flash] is OFF
[url] is ON
Smilies are ON

Topic review
   

Expand view Topic review: FileSetTime: Sommer-/Winterzeit?

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 14 Dec 2018, 11:03

... jepp - perfekt :-)
Danke dir, auch für die Aufklärung über den Parameter.

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 14 Dec 2018, 04:52

Moin LuckyJoe,
  1. ...
    Versuch mal diese Version der Funktion:

    Code: Select all

    ; ======================================================================================================================
    ; SetFileTime
    ;     -> docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfiletime
    ; TzSpecificLocalTimeToSystemTime
    ;     -> docs.microsoft.com/en-us/windows/desktop/api/timezoneapi/nf-timezoneapi-tzspecificlocaltimetosystemtime
    ; SystemTimeToFileTime
    ;     -> docs.microsoft.com/en-us/windows/desktop/api/timezoneapi/nf-timezoneapi-systemtimetofiletime
    ; CreateFile
    ;     -> docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea
    ;     FILE_WRITE_ATTRIBUTES 0x0100
    ;     FILE_SHARE_READ       0x01 +
    ;     FILE_SHARE_WRITE      0x02 +- 0X07
    ;     FILE_SHARE_DELETE     0x04 +
    ;     OPEN_EXISTING         3
    ;     FILE_ATTRIBUTE_NORMAL 0x80
    ; ======================================================================================================================
    SetFileTime(FilePath, TimeStamp, Type := "M") {
       If !TimeStamp2SystemTime(TimeStamp, LocalTime)
          Return False
       If !(Handle := DllCall("CreateFile", "Str", FilePath, "UInt", 0x0100, "UInt", 0x07, "Ptr", 0
                                          , "UInt", 3, "UInt", 0x80, "Ptr", 0, "UPtr"))
          Return False
       ; Aktuelle Daten einlesen
       VarSetCapacity(CTime, 16, 0)
       VarSetCapacity(ATime, 16, 0)
       VarSetCapacity(MTime, 16, 0)
       If !DllCall("GetFileTime", "Ptr", Handle, "Ptr", &CTime, "Ptr", &ATime, "Ptr", &MTime, "UInt") {
          DllCall("CloseHandle", "Ptr", Handle, "UInt")
          Return False
       }
       ; Geändertes Datum schreiben
       VarSetCapacity(SystemTime, 16, 0)
       DllCall("TzSpecificLocalTimeToSystemTime", "Ptr", 0, "Ptr", &LocalTime, "Ptr", &SystemTime, "UInt")
       VarSetCapacity(FileTime, 8, 0)
       DllCall("SystemTimeToFileTime", "Ptr", &SystemTime, "Ptr", &FileTime, "UInt")
       PCT := Type = "C" ? &FileTime : &CTime
       PAT := Type = "A" ? &FileTime : &ATime
       PMT := Type = "M" ? &FileTime : &MTime
       Result := DllCall("SetFileTime", "Ptr", Handle, "Ptr", PCT, "Ptr", PAT, "Ptr", PMT, "UInt")
       DllCall("CloseHandle", "Ptr", Handle, "UInt")
       Return Result
    }
  2. ...
    Type := "M" bestimmt den Standardwert des Parameters. Dieser Wert (hier M) wird verwendet, wenn der Parameter im Funktionsaufruf weggelassen wird.

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 13 Dec 2018, 05:28

Hallo justme,

... wow - ich bin mal wieder tief beeindruckt! Chapeau!
Danke für die Funktionen, die hätte ich alleine nie hinbekommen.
Die Zeiten kann man nicht nur für das aktuelle Jahr verwenden, sondern zurück bis zum 01.01.1601, 01:00:01. ;-)

Zwei Fragen dazu:

1.
Wenn ich bei einer bestehenden Datei (nicht neu erstellte) die Erstellungszeit ("C") oder die Zeit des letzten Zugriffs ("A") ändere, wird der Zeitstempel für die letzte Änderung ("M") immer auf die Zeit der Programmausführung (spich auf "jetzt") gesetzt. Liest sich das zu kompliziert? Beispiel:

SetTime.txt hat folgende Zeitstempel:

Code: Select all

Erstellt ("C"): 01.01.2018, 01:01:01
geändert ("M"):	02.02.2018, 02:02:02
letzter Zugriff ("A"): 03.03.2018, 03:03:03
Mit Aufruf SetFileTime(FilePath, 20180303030303, "A") wird der letzte Zugriffszeit wunschgemäß geändert, aber gleichzeitig "geändert" auf heute gesetzt.
Ebenso wird mit Aufruf SetFileTime(FilePath, 20180101010101, "C") die Erstellungszeit wunschgemäß geändert, aber gleichzeitig wiederum "geändert" auf heute gesetzt.

Wie muss die Funktion aussehen, wenn ich die Zeit der letzten Änderung ("M") "unangetastet", also den bestehenden Zeitstempel dafür ungeändert lassen möchte (vlt. mit zusätzlichem (boolschem) Parameter)?

2.
Bei der Funktion

Code: Select all

SetFileTime(FilePath, TimeStamp, Type := "M") {
...
}
ist mir das Type := "M" nicht ganz klar. Bezieht sich das auf den Buchstaben, der mit dem Funktionsaufruf korresponiert oder korrespondieren soll? Bei meinen Testaufrufen ändert sich überhaupt nichts, wenn ich dort "A", "C", "M", "X" oder irgendeinen anderen Buchstaben verwende.

HG - Lucky Joe

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 13 Dec 2018, 03:28

LuckyJoe wrote: ... bei der ich die gewünschte Zeit "einfach" mit "TT.MM.JJJJ hh:mm:ss" übergeben kann.
Nö! Aber vielleicht reicht Dir auch JJJJMMTThhmmss (bzw. YYYYMMDDHH24MISS)?

Das Übersetzen von Systemzeit in lokale Zeit und umgekehrt lässt sich nicht immer mit einem Funktionsaufruf erledigen. Bei den für Dateien gespeicherten Zeiten ist Microsoft wohl davon ausgegangen, dass bei Änderungen sogut wie immer die aktuelle Zeit benutzt wird. Das ist nachvollziehbar und AHK hat sich dieser Auffassung angeschlossen, wenn vielleicht auch nur deswegen, weil 16-Bit Windows Versionen wie z.B. Win95 nur sehr rudimentäre API-Funktionen anboten.

Die folgende Funktion scheint Sommer- bzw. Winterzeit zumindest dann korrekt zu behandeln, wenn die Zeit im aktuellen Jahr liegt. Weiter habe ich das nicht getestet.

Code: Select all

#NoEnv
FilePath := A_ScriptDir . "\SetTime.txt"
If FileExist(FilePath)
   FileDelete, %FilePath%
FileAppend, %A_Now%, %FilePath%
SetFileTime(FilePath, 20180615151525, "C")
ExitApp
; ======================================================================================================================
; SetFileTime
;     -> docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-setfiletime
; TzSpecificLocalTimeToSystemTime
;     -> docs.microsoft.com/en-us/windows/desktop/api/timezoneapi/nf-timezoneapi-tzspecificlocaltimetosystemtime
; SystemTimeToFileTime
;     -> docs.microsoft.com/en-us/windows/desktop/api/timezoneapi/nf-timezoneapi-systemtimetofiletime
; CreateFile
;     -> docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-createfilea
;     FILE_WRITE_ATTRIBUTES 0x0100
;     FILE_SHARE_READ       0x01 +
;     FILE_SHARE_WRITE      0x02 +- 0X07
;     FILE_SHARE_DELETE     0x04 +
;     OPEN_EXISTING         3
;     FILE_ATTRIBUTE_NORMAL 0x80
; ======================================================================================================================
SetFileTime(FilePath, TimeStamp, Type := "M") {
   If !TimeStamp2SystemTime(TimeStamp, LocalTime)
      Return False
   If !(Handle := DllCall("CreateFile", "Str", FilePath, "UInt", 0x0100, "UInt", 0x07, "Ptr", 0
                                      , "UInt", 3, "UInt", 0x80, "Ptr", 0, "UPtr"))
      Return False
   VarSetCapacity(SystemTime, 16, 0)
   DllCall("TzSpecificLocalTimeToSystemTime", "Ptr", 0, "Ptr", &LocalTime, "Ptr", &SystemTime, "UInt")
   VarSetCapacity(FileTime, 8, 0)
   DllCall("SystemTimeToFileTime", "Ptr", &SystemTime, "Ptr", &FileTime, "UInt")
   CTime := Type = "C" ? &FileTime : 0
   ATime := Type = "A" ? &FileTime : 0
   MTime := Type = "M" ? &FileTime : 0
   Result := DllCall("SetFileTime", "Ptr", Handle, "Ptr", CTime, "Ptr", ATime, "Ptr", MTime, "UInt")
   DllCall("CloseHandle", "Ptr", Handle, "UInt")
   Return Result
}
; ======================================================================================================================
; TimeStamp = YYYYMMDDHH24MISS (autohotkey.com/docs/commands/FileSetTime.htm#YYYYMMDD)
; SystemTime -> msdn.microsoft.com/en-us/f77cdf86-0f97-4a89-b565-95b46fa7d65b
; ======================================================================================================================
TimeStamp2SystemTime(TimeStamp, ByRef SystemTime) {
   VarSetCapacity(SystemTime, 16, 0)
   TimeStamp += 0, S
   If (TimeStamp = "")
      Return False
   NumPut(SubStr(TimeStamp,  1, 4), SystemTime,  0, "UShort")
   NumPut(SubStr(TimeStamp,  5, 2), SystemTime,  2, "UShort")
   NumPut(SubStr(TimeStamp,  7, 2), SystemTime,  6, "UShort")
   NumPut(SubStr(TimeStamp,  9, 2), SystemTime,  8, "UShort")
   NumPut(SubStr(TimeStamp, 11, 2), SystemTime, 10, "UShort")
   NumPut(SubStr(TimeStamp, 13, 2), SystemTime, 12, "UShort")
   Return True
}

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 11 Dec 2018, 02:22

So, ein paar Tage erfolglos herumexperimentiert. Ich wusste nicht, dass die Zeitangabe offensichtlich so komplizert sein kann (oder ich sehe den Wald vor lauter Bäumen niocht mehr).
Das habe ich im Netz zum Setzen des Dateidatums gefunden:

1. https://docs.microsoft.com/de-de/window ... -file-time
Converting a time_t Value to a File Time
The time functions included in the C run-time use the time_t type to represent the number of seconds elapsed since midnight, January 1, 1970. The following example converts a time_t value to a file time, using the Int32x32To64 function (C+):

Code: Select all

#include <windows.h>
#include <time.h>

void TimetToFileTime( time_t t, LPFILETIME pft )
{
    LONGLONG ll = Int32x32To64(t, 10000000) + 116444736000000000;
    pft->dwLowDateTime = (DWORD) ll;
    pft->dwHighDateTime = ll >>32;
}

2. https://msdn.microsoft.com/de-de/librar ... s.85).aspx
FILETIME structure
Contains a 64-bit value representing the number of 100-nanosecond intervals since January 1, 1601 (UTC).

Code: Select all

typedef struct _FILETIME {
  DWORD dwLowDateTime;
  DWORD dwHighDateTime;
} FILETIME, *PFILETIME;

3. https://docs.microsoft.com/de-de/window ... rrent-time
Changing a File Time to the Current Time
The following example sets the last-write time for a file to the current system time using the SetFileTime function.
The NTFS file system stores time values in UTC format, so they are not affected by changes in time zone or daylight saving time. The FAT file system stores time values based on the local time of the computer.
The file must be opened with the CreateFile function using FILE_WRITE_ATTRIBUTES access.

Code: Select all

#include <windows.h>

// SetFileToCurrentTime - sets last write time to current system time
// Return value - TRUE if successful, FALSE otherwise
// hFile  - must be a valid file handle

BOOL SetFileToCurrentTime(HANDLE hFile)
{
    FILETIME ft;
    SYSTEMTIME st;
    BOOL f;

    GetSystemTime(&st);              // Gets the current system time
    SystemTimeToFileTime(&st, &ft);  // Converts the current system time to file time format
    f = SetFileTime(hFile,           // Sets last-write time of the file 
        (LPFILETIME) NULL,           // to the converted current system time 
        (LPFILETIME) NULL, 
        &ft);    

    return f;
}

4. https://docs.microsoft.com/en-us/window ... etfiletime
SetFileTime function
Sets the date and time that the specified file or directory was created, last accessed, or last modified.

Code: Select all

BOOL SetFileTime(
  HANDLE         hFile,
  const FILETIME *lpCreationTime,
  const FILETIME *lpLastAccessTime,
  const FILETIME *lpLastWriteTime
);

5. https://docs.microsoft.com/de-de/window ... reatefilea
CreateFileA function
Creates or opens a file or I/O device. The most commonly used I/O devices are as follows: file, file stream, directory, physical disk, volume, console buffer, tape drive, communications resource, mailslot, and pipe. The function returns a handle that can be used to access the file or device for various types of I/O depending on the file or device and the flags and attributes specified.
To perform this operation as a transacted operation, which results in a handle that can be used for transacted I/O, use the CreateFileTransacted function.

Code: Select all

HANDLE CreateFileA(
  LPCSTR                lpFileName,
  DWORD                 dwDesiredAccess,
  DWORD                 dwShareMode,
  LPSECURITY_ATTRIBUTES lpSecurityAttributes,
  DWORD                 dwCreationDisposition,
  DWORD                 dwFlagsAndAttributes,
  HANDLE                hTemplateFile
);

...so, alles schön in C+-Syntax, die ich nicht in AHK adaptieren kann. Gibt es hier jemanden, der da durchblickt und eine AHK-Funktion bauen kann, mit der ich das Datum einer Datei verändern kann? Idealerweise ähnlich der AHK-Funktion FileSetTime (M = Zeitpunkt der letzten Änderung / C = Zeitpunkt der Erstellung / A = Zeitpunkt des letzten Zugriffs), bei der ich die gewünschte Zeit "einfach" mit "TT.MM.JJJJ hh:mm:ss" übergeben kann.

Danke schon mal im Voraus.
HG - Lucky Joe

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 07 Dec 2018, 03:13

Moin,

Microsoft sagt, dass man für jeden der drei Parameter entweder 0 oder die Adresse einer mit Nullen gefüllten FILETIME Struktur übergeben kann, wenn der zugehörige Zeitstempel nicht verändert werden soll.
If the application does not need to change this information, set this parameter either to NULL or to a pointer to a FILETIME structure that has both the dwLowDateTime and dwHighDateTime members set to 0.
Die Funktionsdefinition sollte also so aussehen können:

Code: Select all

setFileTimes(file, ftCreate := 0, ftAccess := 0, ftModify := 0) {
...
}
Die Zeitparameter werden so optional.

Übrigens:
LuckyJoe wrote:... (also mit SetFileTimes(%file%, , , %ftModify%)
Eher nicht! Funktionsaufrufe sind Ausdrücke/Expressions. Variablennamen dürfen deshalb für eine einfache Referenz nicht in %-Zeichen eingeschlossen werden. ;)

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 06 Dec 2018, 13:20

... danke, justme, ich bagger mich da erst einmal alleine durch ... will ja was lernen. Bei Bedarf frage ich gerne noch einmal nach.
Vielleicht schon mal vorweg: kann ich ftCreate und ftAccess weglassen, wenn ich nur ftModify ändern will (also mit SetFileTimes(%file%, , , %ftModify%))?

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 06 Dec 2018, 11:18

Hi LuckyJoe,

das Ergebnis Deiner Recherche ist völlig korrekt. Es klammert aber die einzige 'echte' Schwierigkeit aus: Welche Werte müssen in ftCreate, ftAccess und ftModify bei Aufruf der Funktion setFileTimes() übergeben werden, wenn man das jeweilige Datum ändern will? Ich kann gern versuchen, Dich bei der Konvertierung der Zeitformate zu unterstützen.

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 06 Dec 2018, 11:03

Hi justme,

danke, dass du an mich gedacht hast ... - auch wenn du mich zum Arbeiten zwingst ;-)
Ok, ich habe zwischenzeitlich etwas recherchiert und das hier gefunden: https://autohotkey.com/board/topic/9905 ... -attribute. Werde mich dann damit mal in den nächsten Tagen "herumschlagen". Melde mich, wenn ich Hilfe brauche (oder bin ich schon jetzt auf dem falschen Weg?)

HG - Lucky Joe

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 06 Dec 2018, 06:17

LuckyJoe wrote: Dann bliebe noch meine bescheidene Frage: wie läßt sich das Dateidatum alternativ per DllCall (SystemTimeToFileTime oder so was Ähnlichem) setzen?
Dafür gibt es die API-Funktion SetFileTime. Wenn man die selbst aufrufen will, muss man allerdings die Zeit(en) selbst von lokaler zu Systemzeit (UTC) umrechnen. Zumindest ab Win Vista gibt es dafür recht zuverlässige Funktionen. Willst Du das mal ausprobieren?

Re: FileSetTime: Sommer-/Winterzeit?

Post by garry » 05 Dec 2018, 13:51

@LuckyJoe , vielen Dank , bin auch 'LuckyGarry' , kann jetzt Funktion benützen , danke auch an 'just me' für den script
die Zeit ( oder Datum ) hatte ich vorher so eingestellt ( und mit tmplinshi's Time Sync kann man wieder grad richtigstellen , statt manuell , war nützlich beim alten Computer dessen Zeit/Datum verloren war beim Einschalten )

Code: Select all

adm:=a_isadmin
if (adm=0)
Gosub, RunAsAdmin1
;-----------
stringmid,h,a_now,9,2
stringmid,m,a_now,11,2
stringmid,s,a_now,13,2
now:=h . "." . m . "." . s
;- Set time
runwait,%comspec% /k date /T&time /T&time
return
;--------------------------------------------------------------------
RunAsAdmin1:
Try
Run, *RunAs "%A_ScriptFullPath%"
Exitapp
Return
;--------------------------------------------------------------------

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 05 Dec 2018, 13:08

Hi garry,

probier das mal (Vorsicht mit der manuell eingegebenen Zeit - wirkt sich ggf. auf Programme/Prozesse im PC aus!):

Code: Select all

#SingleInstance ignore
#NoEnv

if(!A_IsAdmin){
	Run *RunAs "%A_ScriptFullPath%",, UseErrorLevel
	If(ErrorLevel){
		MsgBox, 53, Administatorrechte benötigt
	IfMsgBox, Retry
		Reload
	Else
		ExitApp
	}
	Return
}
;   SetLocalTime(Year, Month, Day, Hour, Minute, Second := 0)
If (SetLocalTime(2018, 12,    05,  18,   55,     00))
	MsgBox, Computerzeit erfolgreich angepasst
Else
	MsgBox, Fehler! - Computerzeit nicht angepasst

ExitApp

; ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SetLocalTime(Year, Month, Day, Hour, Minute, Second := 0) {
	; docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-setlocaltime
	; SYSTEMTIME -> msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
	VarSetCapacity(SYSTEMTIME, 16, 0)
	NumPut(Year,   SYSTEMTIME,  0, "UShort")
	NumPut(Month,  SYSTEMTIME,  2, "UShort")
	NumPut(Day,    SYSTEMTIME,  6, "UShort")
	NumPut(Hour,   SYSTEMTIME,  8, "UShort")
	NumPut(Minute, SYSTEMTIME, 10, "UShort")
	NumPut(Second, SYSTEMTIME, 12, "UShort")
	; It's recommended to call the function twice
	If DllCall("SetLocalTime", "Ptr", &SYSTEMTIME, "UInt")
		Return DllCall("SetLocalTime", "Ptr", &SYSTEMTIME, "UInt")
	Return False
}
Viel Erfolg!
HG - Lucky Joe

Re: FileSetTime: Sommer-/Winterzeit?

Post by garry » 05 Dec 2018, 12:34

@just me , danke , jetzt bin ich zu blöd um die Funktion zu benützen
mal start als admin ...

Code: Select all

#warn
setworkingdir,%a_scriptdir%
if !A_IsAdmin {
    try
	Run *RunAs "%A_ScriptFullPath%"
	ExitApp
}

;---
;---

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 05 Dec 2018, 10:01

... ich habe mittlerweile auch andere Stimmen zu FileSetTime gelesen, z.B. hier: https://autohotkey.com/board/topic/6814 ... 7-machine/. Von daher schließe ich mich mal der Meinung von justme an, dass es sich um einen Bug innerhalb von AHK handelt. Es macht meiner Meinung nach auch keinen Sinn, dass die Funktion nach Sommer-/Winterzeit unterscheidet, um ein Datei-Datum zu ändern.

Dann bliebe noch meine bescheidene Frage: wie läßt sich das Dateidatum alternativ per DllCall (SystemTimeToFileTime oder so was Ähnlichem) setzen?
Am besten noch wie bei FileSetTime mit
M = Zeitpunkt der letzten Änderung
C = Zeitpunkt der Erstellung
A = Zeitpunkt des letzten Zugriffs

Danke vorab an die Profis.
HG - Lucky Joe

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 05 Dec 2018, 09:11

Hallo garry,

meinst Du das so?

Code: Select all

SetLocalTime(Year, Month, Day, Hour, Minute, Second := 0) {
   ; docs.microsoft.com/en-us/windows/desktop/api/sysinfoapi/nf-sysinfoapi-setlocaltime
   ; SYSTEMTIME -> msdn.microsoft.com/en-us/library/windows/desktop/ms724950(v=vs.85).aspx
   VarSetCapacity(SYSTEMTIME, 16, 0)
   NumPut(Year,   SYSTEMTIME,  0, "UShort")
   NumPut(Month,  SYSTEMTIME,  2, "UShort")
   NumPut(Day,    SYSTEMTIME,  6, "UShort")
   NumPut(Hour,   SYSTEMTIME,  8, "UShort")
   NumPut(Minute, SYSTEMTIME, 10, "UShort")
   NumPut(Second, SYSTEMTIME, 12, "UShort")
   ; It's recommended to call the function twice
   If DllCall("SetLocalTime", "Ptr", &SYSTEMTIME, "UInt")
      Return DllCall("SetLocalTime", "Ptr", &SYSTEMTIME, "UInt")
   Return False
}

Die merkwürdigen Ergebnisse beim Setzen von Zeiten, über die Lucky Joe berichtet, halte ich inzwischen für einen AHK Bug. Die Umrechnung von lokaler Zeit in Systemzeit (UTC) muss die Anwendung selbst bewältigen. AHK nutzt hier meiner Meinung nach alte bzw. veraltete Funktionen.

Re: FileSetTime: Sommer-/Winterzeit?

Post by garry » 05 Dec 2018, 05:57

@just me , danke für Info und Function > display = Sommerzeit / Normalzeit
müsste mal lernen wie man API anwenden kann ...

Re: FileSetTime: Sommer-/Winterzeit?

Post by just me » 05 Dec 2018, 05:48

garry wrote: kann ich den einfachen script von 'just me' verwenden um die Computer-Zeit zu setzen ? ( DllCall("SetLocalTime", "Ptr", &SystemTime) )
Hi garry,

ich verstehe nicht, was Du damit meinst. Wenn Du die genaue lokale Zeit hast und die für den Rechner setzen willst, solltest Du Folgendes beachten:
SetLocalTime:

The system uses UTC internally. Therefore, when you call SetLocalTime, the system uses the current time zone information to perform the conversion, including the daylight saving time setting. Note that the system uses the daylight saving time setting of the current time, not the new time you are setting. Therefore, to ensure the correct result, call SetLocalTime a second time, now that the first call has updated the daylight saving time setting.

Re: FileSetTime: Sommer-/Winterzeit?

Post by garry » 05 Dec 2018, 05:06

script von tmplinshi liest von http://www.baidu.com/ UTC aus ( China hat +8h ohne DST )
habe script gebraucht für den alten Computer dessen Lithium Batterie defekt war um die Zeit zu setzen
kann ich den einfachen script von 'just me' verwenden um die Computer-Zeit zu setzen ? ( DllCall("SetLocalTime", "Ptr", &SystemTime) )
Sommerzeit sollte in Europa abgeschafft werden ... (?)
https://www.timesofmalta.com/articles/v ... ock.691589

Image
hier wieder mal kompliziert ...

Code: Select all

;-------- saved at Dienstag, 4. Dezember 2018 18:19:31 --------------
;;-------- https://autohotkey.com/boards/viewtopic.php?f=28&t=46997 ---
;- modified= 20180910
;- created = 20180910
;- descript= show time e.g. 7-Countries / synchronize time / change time ( for test or if needed ( or if no internet-connection) )
;- DST     = only calculate  CET Central-European-Time
;- https://www.timeanddate.com/time/dst/
;- https://www.timeanddate.com/worldclock/
;- https://www.science.co.il/language/Locale-codes.php
;- https://autohotkey.com/boards/viewtopic.php?f=28&t=46997  
;             ( UTC + 1 / CET  - Central European        Time - begin last sunday in octobre / e.g  sun 2018-10-28 03:00>02:00 UTC 01:00)
;             ( UTC + 2 / CEST - Central European SUMMER Time - begin last sunday in mars    / e.g. sun 2018-03-25 02:00>03:00 UTC 01:00)  
;- https://en.wikipedia.org/wiki/Summer_Time_in_Europe
;- On 8  February 2018, the European Parliament voted to ask the European Commission to re-evaluate DST in Europe.
;- On 31 August   2018, the European Commission announced that they, after a web query giving high support of not switching clock twice annually, intend to go ahead with a new directive.  
/*
A formula which cn be used to calculate the beginning of European Summer Time is:
Sunday (31 − ((((5 × y) ÷ 4) + 4) mod 7)) March at 01:00 UTC
The corresponding formula for the end of European Summer Time is:
Sunday (31 − ((((5 × y) ÷ 4) + 1) mod 7)) October at 01:00 UTC
where y is the year, and a mod b is b times the fractional part of a/b. These formulae are valid until 2099
*/
  
       
#warn
#NoEnv
#singleinstance,force
SendMode Input
SetWorkingDir %A_ScriptDir%
SetBatchLines, -1
Fileencoding,UTF-8
Autotrim,off
SplitPath,a_scriptfullpath, name, dir, ext, name_no_ext, drive
name1=%name_no_ext%
gosub,createsecondscript
gosub,3rdscript
;- country , +/-hours , DST , Language
e4x=
(Ltrim Join`r`n
UTC_GMT    ,0,N,L2057
Portugal   ,0,Y,L2070
Switzerland,1,Y,L2055
Finland    ,2,Y,L1035
China      ,8,N,L2052
Vietnam    ,7,N,L1066
Montevideo ,-3,N,L11274
)
wa:=A_screenwidth
ha:=A_screenHeight
xx:=105
GW  :=(wa*50) /xx   
GH  :=(ha*33) /xx      
Info=%a_osversion% | %a_ostype% | 64bit=%a_is64bitos% | %wa%*%ha% | %a_username%=%a_isadmin% | %a_computername% | AHK=%a_ahkversion%
Gui,2:default
Gui,2: -DPIScale
SS_REALSIZECONTROL := 0x40
Gui,2:Color,Black
Gui,2:Color,ControlColor, Black
Gui,2:Font,s12 cYellow,Lucida Console
;A_GuiFont     := GuiDefaultFont()
;A_GuiFontSize := A_LastError
;aac:= a_screendpi   ;- 168 at 4k
;=================================================
sectA=Country,DATE       TIME,DaylightSavingTime DST,Language
stringsplit,k,sectA,`,
           columns:=k0   ;- 4
SectB=SYNC-TIME,ChangeTime,Worldclock,LanguageCode
stringsplit,b,sectB,`,
;------------------------------		   
rows:=9
all :=(rows*columns)     ;- 36
;------------------------------		   
d :=(wa*.3)/xx     ;-  difference horizontal
h :=(ha* 2)/xx     ;-  ROW-height
w :=(wa*11)/xx     ;- xROW-width
i:=0
r:=0
e:=0
q:=0
s:=3
col:=""
Loop,%all%
  {
  ;-----------------
  M:=mod(i,columns)
  if m=0             ;- skip to next line
     R++
  ;-----------------	 
  ;--- (Line-1) first line text 	 
  if (m=0 and R=1)
    {
	x :=(wa*.5)/xx
    y :=(ha* 1)/xx
    Gui,2:add,text,section x%x% y%y% w0 h0,
	}
  if (R=1)	
    Gui,2:Add,text,ys x+%d% h%h% w%w% ,% k%a_index%
	
  ;--- ( Line 2-8 )second line begin with EDIT ED1... ED28	
  if (m=0 and R>1 and R<9)
    {
	x :=(wa*.5)/xx
    y :=(ha* s)/xx
	s :=(s+3)      ;- add difference vertikal 
    Gui,2:add,text,section x%x% y%y% w0 h0,
	}
  if (R>1 and R<9)
    {
    e++	
	if (e=2 or e=6 or e=10 or e= 14 or e=18 or e=22 or e=26)
      col=Gray
	else
      col=D5E66D  ;-yellow	
	Gui,2:Add,Edit , ys  x+%d%  w%w% h%h% vED%e% c%col% readonly left,
	}
  
  ;------------ Line 9  ------------	 
  if (m=0 and R>8 and R<10)
    {
	x :=(wa*.5)/xx
    y :=(ha* s)/xx
	s :=(s+3) 
    Gui,2:add,text,section x%x% y%y% w0 h0,
	}
  if (R>8 and R<10)
    {
	q++
	;Gui,2:add,button, ys x+%d% w%w% h%h% gStart2,% b%q%
    Gui,2:Add,Progress,ys x+%d% w%w% h%h%  Disabled BackgroundGray
    if (q<2)
      Gui,2:Add,Text,     xp   yp  wp  hp   cYellow    BackgroundTrans Center 0x200 gStart2 ,% b%q%
    else
      Gui,2:Add,Text,     xp   yp  wp  hp   cBlack     BackgroundTrans Center 0x200 gStart2 ,% b%q%
	}
  i++
  }
;----------------  
y :=(ha*27   )/xx
x :=(wa*11.92)/xx   
Gui,2:Add,Edit ,x%x% y%y%  w%w% h%h% vTimex readonly left,
y :=(ha*30)/xx
x :=(wa* 1)/xx   
Gui,2:Add,text ,x%x% y%y%  cGray center,%info% 
  
Gui,2:show, x100 y5 w%gw% h%gh% ,%name1%
settimer,clock,1000
settimer,a0,1000
return
;--------------
2Guiclose:
exitapp
;--------------
Start2:
gui,2:submit,nohide
r:= a_guicontrol
goto,%r%
return
;--------------
changetime:
try
run,%f1%
return
sync-time:
try
run,%f31%
return
;--------------
dst:
run,https://www.timeanddate.com/time/dst/
return
;--------------
worldclock:
run,https://www.timeanddate.com/worldclock/
return
;--------------
languagecode:
run,https://www.science.co.il/language/Locale-codes.php
return
;--------------
clock:
GuiControl,2: ,timex, %A_YYYY%-%A_MM%-%A_DD% %a_hour%:%a_min%:%a_sec%
return
;--------------
a0:
;UTC       := GetTimestampUTC()
UTC:=a_nowutc
e=
Loop,parse,e4x,`n,`r
  {
  x:=a_loopfield
  if x=
     continue
  stringsplit,p,x,`,
  country:=p1
  p1:=utc
  if (p3="Y")
     {
     gosub,cc
     continue
     }
  else
     {
     p1 += +P2,hours
     FormatTime,px, %p1% %p4%,MMMM dddd
     FormatTime,p1, %p1% %p4%,yyyy-MM-dd HH:mm:ss
     e .= country . "," . p1 . ",NO DST," . px . "`r`n"
     continue
     }
  }
;msgbox,%e%
i=0
Loop,parse,e,`n,`r
   {
   stringsplit,d,a_loopfield,`,
   loop,4
      {
	  i++
      GuiControl,2:,ed%i%,% d%a_index%
	  }
   }
e=
return
;---------------------------
cc:
stringmid,q,p1,1,8
stringmid,Y,p1,1,4
q:=(q)
lsm := LastSunday(Y . "03")
lso := LastSunday(Y . "10")
if (q >= lsm) and (q < lso)
   {
   p2:=(P2+1)
   p1 += +P2,hours
   FormatTime,px, %p1% %p4%,MMMM dddd
   FormatTime,p1, %p1% %p4%,yyyy-MM-dd HH:mm:ss
   e .= country "," p1 ",-Summer-Time," px "`r`n"
   }
else
   {
   p1 += +P2,hours
   FormatTime,px, %p1% %p4%,MMMM dddd
   FormatTime,p1, %p1% %p4%,yyyy-MM-dd HH:mm:ss
   e .= country "," p1 ",-NORMAL-TIME," px "`r`n"
   }
return
;--------------------------
;-----------------------------------------------------------------------
;- Function last sunday in mars and october for DST daylight saving time
;- https://autohotkey.com/board/topic/97664-find-specific-wday/ ---
LastSunday(Date)
    {
    Date += 31, D
    Date := SubStr(Date, 1, 6)
    Date += -1, Day
    FormatTime, WD , %Date%, WDay
    Date += -(WD - 1), D
    return, SubStr(Date, 1, 8)
   }
return
;============================================================================
createsecondscript:
f1=%a_scriptdir%\%name1%-change-time.ahk
IfNotExist,%f1%
{
e4x=
(LTrim Join`r`n % `
adm:=a_isadmin
if (adm=0)
Gosub, RunAsAdmin1
;-----------
stringmid,h,a_now,9,2
stringmid,m,a_now,11,2
stringmid,s,a_now,13,2
now:=h . "." . m . "." . s
;- Set time
runwait,%comspec% /k date /T&time /T&time
return
;--------------------------------------------------------------------
RunAsAdmin1:
  Try
  Run, *RunAs "%A_ScriptFullPath%"
Exitapp		
Return
;--------------------------------------------------------------------
RunAsAdmin2:
full_command_line := DllCall("GetCommandLine", "str")
if not (A_IsAdmin or RegExMatch(full_command_line, " /restart(?!\S)"))
{
  try
  {
  if A_IsCompiled
    Run *RunAs "%A_ScriptFullPath%" /restart
      else
    Run *RunAs "%A_AhkPath%" /restart "%A_ScriptFullPath%"
  }
ExitApp
}
return
)
fileappend,%e4x%,%f1%
}
return
;=================== end script DateandTime.com ===========================
;- function SYNCHRONIZE user tmplinshi
;- https://autohotkey.com/boards/viewtopic.php?f=28&t=46997
3rdscript:
f31=%a_scriptdir%\%name1%-SYNC-time.ahk
IfNotExist,%f31%
{
e5x=
(LTrim Join`r`n %
;-------- saved at Montag, 10. September 2018 22:24:45 --------------
;;-------- https://autohotkey.com/boards/viewtopic.php?f=28&t=46997 ---
;- this script :
;- https://autohotkey.com/boards/viewtopic.php?f=28&t=46997 ---
;- https://www.timeanddate.com/time/dst/
;- https://www.timeanddate.com/worldclock/
;- https://www.science.co.il/language/Locale-codes.php
;- 歐洲 CET / CEST Central European Summer-Time
;-----------------------------------------------------
#warn
setworkingdir,%a_scriptdir%
; 以管理员身份运行
if !A_IsAdmin {
    Try
	Run *RunAs "%A_ScriptFullPath%"  ; Requires v1.0.92.01+
	ExitApp
}
global dst
if SynTime.DoIt()
    msgbox, 262208,SUCCESS ,Succes synchronized %dst%,1
else
    msgbox, 262208,NO SUCCESS ,	NO Succes synchronized CET,1
return
/*
if SynTime.DoIt()
	MsgBox, 64, 成功 , 同步北京时间成功!
else
	MsgBox, 48, 失败 , 同步失败!
; 同步北京时间。用法: SynTime.DoIt()
return
*/
Class SynTime
{
	DoIt() { ; 成功返回 1
		return this.SetLocalTime( this.BeijingTime() )
	}
	SetLocalTime(YYYYMMDDHHMISS) {
		FormatTime, t, %YYYYMMDDHHMISS%, yyyy/M/1/d/H/m/s/0
		VarSetCapacity(SystemTime, 16, 0)
		Loop, Parse, t, /
			NumPut(A_LoopField, SystemTime, (A_Index-1)*2, "UShort")
		return DllCall("SetLocalTime", "Ptr", &SystemTime)
	}
	BeijingTime() { ; 返回 YYYYMMDDHHMISS
		whr := ComObjCreate("WinHttp.WinHttpRequest.5.1")
		whr.Open("HEAD", "http://baidu.com", true)
		whr.Send()
		whr.WaitForResponse()
		_date := whr.GetResponseHeader("Date") ; 示例数据: Mon, 21 Apr 2014 14:58:23 GMT
		arr := StrSplit( _date, [A_Space, ":"] )
		oMonth := {Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"}
		Mon    := oMonth[ arr.3 ] ; 月份英文缩写转换成数字
		timestamp := arr.4 Mon arr.2 arr.5 arr.6 arr.7 ; YYYYMMDDHHMISS 格式的日期
		p2:=1                             ;- ( UTC + 1 / CET - Central European Time - begin last sunday in octobre / e.g  sun 2018-10-28 03:00>02:00 )
        stringmid,q,timestamp,1,8
        stringmid,Y,timestamp,1,4
        q:=(q)
        lsm := LastSunday(Y . "03")
        lso := LastSunday(Y . "10")
        if (q >= lsm) and (q < lso)
           {
		   DST:="CEST summertime UTC+2"
           p2:=(P2+1)                     ;- ( UTC + 2 / CEST - Central European SUMMER Time - DST begin last sunday in mars / e.g. sun 2018-03-25 02:00>03:00 )
           timestamp += +P2,hours
           }
        else
		   {
		   DST:="CET normaltime UTC+1"
           timestamp += +P2,hours
		   }
		;timestamp += 8, Hours ; 加 8 小时就是北京时间
		return timestamp
	}
}
;-----------------------------------------------------------------------
;- Function last sunday in mars and october for DST daylight saving time in Europe
;- https://autohotkey.com/board/topic/97664-find-specific-wday/ ---
LastSunday(Date)
    {
    Date += 31, D
    Date := SubStr(Date, 1, 6)
    Date += -1, Day
    FormatTime, WD , %Date%, WDay
    Date += -(WD - 1), D
    return, SubStr(Date, 1, 8)
   }
;============================================================================
)
fileappend,%e5x%,%f31%
}
return
;================== END script =========================================

Re: FileSetTime: Sommer-/Winterzeit?

Post by nnnik » 05 Dec 2018, 04:15

Also Zeitzonen an sich sind ne Sache die sollte man mal anders lösen.
Über Sommer und Winterzeit will ich gar nicht erst anfangen.

Re: FileSetTime: Sommer-/Winterzeit?

Post by LuckyJoe » 05 Dec 2018, 03:36

@garry: Danke für das Script, aber das synchronisiert offensichtlich nur die Systemzeit. Ich blicke durch die Klasse nicht so ganz durch, wobei ich die chinesischen Kommentare recht nett finde ;-)
Die "LastSunday(Date)"-Funktion ist aber identisch mit der von jNizM.

@justme: Danke - das ist genau die Funktion, die ich gesucht habe, kurz und knackig (auch wenn ich DLLCalls noch nicht wirklich durchblicke) :bravo:
... dann wäre das doch was für die Sammlung, die schon jNizM angesprochen hatte: https://autohotkey.com/boards/viewtopic ... 11&t=10600.

Top