dati.inc 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587
  1. {
  2. *********************************************************************
  3. Copyright (C) 1997, 1998 Gertjan Schouten
  4. See the file COPYING.FPC, included in this distribution,
  5. for details about the copyright.
  6. This program is distributed in the hope that it will be useful,
  7. but WITHOUT ANY WARRANTY; without even the implied warranty of
  8. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  9. **********************************************************************
  10. System Utilities For Free Pascal
  11. }
  12. {==============================================================================}
  13. { internal functions }
  14. {==============================================================================}
  15. Function DoEncodeDate(Year, Month, Day: Word): longint;
  16. Var
  17. D : TDateTime;
  18. begin
  19. If TryEncodeDate(Year,Month,Day,D) then
  20. Result:=Trunc(D)
  21. else
  22. Result:=0;
  23. end;
  24. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  25. begin
  26. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  27. Result:=0;
  28. end;
  29. {==============================================================================}
  30. { Public functions }
  31. {==============================================================================}
  32. { ComposeDateTime converts a Date and a Time into one TDateTime }
  33. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  34. begin
  35. if Date < 0 then Result := trunc(Date) - Abs(frac(Time))
  36. else Result := trunc(Date) + Abs(frac(Time));
  37. end;
  38. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  39. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  40. Var
  41. D : Double;
  42. begin
  43. D:=DateTime * Single(MSecsPerDay);
  44. if D<0 then
  45. D:=D-0.5
  46. else
  47. D:=D+0.5;
  48. result.Time := Abs(Trunc(D)) Mod MSecsPerDay;
  49. result.Date := DateDelta + Trunc(D) div MSecsPerDay;
  50. end;
  51. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  52. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  53. begin
  54. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time / MSecsPerDay)
  55. end;
  56. { MSecsToTimeStamp }
  57. function MSecsToTimeStamp(MSecs: comp): TTimeStamp;
  58. begin
  59. result.Date := Trunc(msecs / msecsperday);
  60. msecs:= msecs-comp(result.date)*msecsperday;
  61. result.Time := Round(MSecs);
  62. end ;
  63. { TimeStampToMSecs }
  64. function TimeStampToMSecs(const TimeStamp: TTimeStamp): comp;
  65. begin
  66. result := TimeStamp.Time + comp(timestamp.date)*msecsperday;
  67. end ;
  68. Function TryEncodeDate(Year,Month,Day : Word; Out Date : TDateTime) : Boolean;
  69. var
  70. c, ya: cardinal;
  71. begin
  72. Result:=(Year>0) and (Year<10000) and
  73. (Month in [1..12]) and
  74. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  75. If Result then
  76. begin
  77. if month > 2 then
  78. Dec(Month,3)
  79. else
  80. begin
  81. Inc(Month,9);
  82. Dec(Year);
  83. end;
  84. c:= Year DIV 100;
  85. ya:= Year - 100*c;
  86. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*cardinal(Month)+2) DIV 5 + cardinal(Day);
  87. // Note that this line can't be part of the line above, since TDateTime is
  88. // signed and c and ya are not
  89. Date := Date - 693900;
  90. end
  91. end;
  92. function TryEncodeTime(Hour, Min, Sec, MSec:word; Out Time : TDateTime) : boolean;
  93. begin
  94. Result:=((Hour<24) and (Min<60) and (Sec<60) and (MSec<1000)) or
  95. { allow leap second }
  96. ((Hour=23) and (Min=59) and (Sec=60) and (MSec<1000));
  97. If Result then
  98. Time:=TDateTime(cardinal(Hour)*3600000+cardinal(Min)*60000+cardinal(Sec)*1000+MSec)/MSecsPerDay;
  99. end;
  100. { EncodeDate packs three variables Year, Month and Day into a
  101. TDateTime value the result is the number of days since 12/30/1899 }
  102. function EncodeDate(Year, Month, Day: word): TDateTime;
  103. begin
  104. If Not TryEncodeDate(Year,Month,Day,Result) then
  105. Raise EConvertError.CreateFmt('%d-%d-%d is not a valid date specification',
  106. [Year,Month,Day]);
  107. end;
  108. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  109. a TDateTime value }
  110. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  111. begin
  112. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  113. Raise EConvertError.CreateFmt('%d:%d:%d.%d is not a valid time specification',
  114. [Hour,Minute,Second,MilliSecond]);
  115. end;
  116. { DecodeDate unpacks the value Date into three values:
  117. Year, Month and Day }
  118. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  119. var
  120. ly,ld,lm,j : cardinal;
  121. begin
  122. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  123. begin
  124. Year := 0;
  125. Month := 0;
  126. Day := 0;
  127. end
  128. else
  129. begin
  130. if Date>0 then
  131. Date:=Date+1/(msecsperday*2)
  132. else
  133. Date:=Date-1/(msecsperday*2);
  134. if Date>MaxDateTime then
  135. Date:=MaxDateTime;
  136. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  137. j := pred((longint(Trunc(System.Int(Date))) + 693900) SHL 2);
  138. ly:= j DIV 146097;
  139. j:= j - 146097 * cardinal(ly);
  140. ld := j SHR 2;
  141. j:=(ld SHL 2 + 3) DIV 1461;
  142. ld:= (cardinal(ld) SHL 2 + 7 - 1461*j) SHR 2;
  143. lm:=(5 * ld-3) DIV 153;
  144. ld:= (5 * ld +2 - 153*lm) DIV 5;
  145. ly:= 100 * cardinal(ly) + j;
  146. if lm < 10 then
  147. inc(lm,3)
  148. else
  149. begin
  150. dec(lm,9);
  151. inc(ly);
  152. end;
  153. year:=ly;
  154. month:=lm;
  155. day:=ld;
  156. end;
  157. end;
  158. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  159. begin
  160. DecodeDate(DateTime,Year,Month,Day);
  161. DOW:=DayOfWeek(DateTime);
  162. Result:=IsLeapYear(Year);
  163. end;
  164. { DecodeTime unpacks Time into four values:
  165. Hour, Minute, Second and MilliSecond }
  166. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  167. Var
  168. l : cardinal;
  169. begin
  170. l := DateTimeToTimeStamp(Time).Time;
  171. Hour := l div 3600000;
  172. l := l mod 3600000;
  173. Minute := l div 60000;
  174. l := l mod 60000;
  175. Second := l div 1000;
  176. l := l mod 1000;
  177. MilliSecond := l;
  178. end;
  179. { DateTimeToSystemTime converts DateTime value to SystemTime }
  180. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  181. begin
  182. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  183. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  184. Dec(SystemTime.DayOfWeek);
  185. end ;
  186. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  187. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  188. begin
  189. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  190. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  191. end ;
  192. { DayOfWeek returns the Day of the week (sunday is day 1) }
  193. function DayOfWeek(DateTime: TDateTime): integer;
  194. begin
  195. Result := 1 + ((Trunc(DateTime) - 1) mod 7);
  196. If (Result<=0) then
  197. Inc(Result,7);
  198. end;
  199. { Date returns the current Date }
  200. function Date: TDateTime;
  201. var
  202. SystemTime: TSystemTime;
  203. begin
  204. GetLocalTime(SystemTime);
  205. result := DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day);
  206. end ;
  207. { Time returns the current Time }
  208. function Time: TDateTime;
  209. var
  210. SystemTime: TSystemTime;
  211. begin
  212. GetLocalTime(SystemTime);
  213. Result := DoEncodeTime(SystemTime.Hour,SystemTime.Minute,SystemTime.Second,SystemTime.MilliSecond);
  214. end ;
  215. { Now returns the current Date and Time }
  216. function Now: TDateTime;
  217. var
  218. SystemTime: TSystemTime;
  219. begin
  220. GetLocalTime(SystemTime);
  221. result := systemTimeToDateTime(SystemTime);
  222. end;
  223. { IncMonth increments DateTime with NumberOfMonths months,
  224. NumberOfMonths can be less than zero }
  225. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  226. var
  227. Year, Month, Day : word;
  228. begin
  229. DecodeDate(DateTime, Year, Month, Day);
  230. IncAMonth(Year, Month, Day, NumberOfMonths);
  231. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  232. end ;
  233. { IncAMonth is the same as IncMonth, but operates on decoded date }
  234. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  235. var
  236. TempMonth, S: Integer;
  237. begin
  238. If NumberOfMonths>=0 then
  239. s:=1
  240. else
  241. s:=-1;
  242. inc(Year,(NumberOfMonths div 12));
  243. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  244. if (TempMonth>11) or
  245. (TempMonth<0) then
  246. begin
  247. Dec(TempMonth, S*12);
  248. Inc(Year, S);
  249. end;
  250. Month:=TempMonth+1; { Months from 1 to 12 }
  251. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  252. Day:=MonthDays[IsLeapYear(Year)][Month];
  253. end;
  254. { IsLeapYear returns true if Year is a leap year }
  255. function IsLeapYear(Year: Word): boolean;
  256. begin
  257. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  258. end;
  259. { DateToStr returns a string representation of Date using ShortDateFormat }
  260. function DateToStr(Date: TDateTime): string;
  261. begin
  262. DateTimeToString(Result, 'ddddd', Date);
  263. end ;
  264. function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings): string;
  265. begin
  266. DateTimeToString(result, FormatSettings.ShortDateFormat, Date, FormatSettings);
  267. end;
  268. { TimeToStr returns a string representation of Time using LongTimeFormat }
  269. function TimeToStr(Time: TDateTime): string;
  270. begin
  271. DateTimeToString(Result, 'tt', Time);
  272. end ;
  273. function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings): string;
  274. begin
  275. DateTimeToString(Result, FormatSettings.LongTimeFormat, Time, FormatSettings);
  276. end;
  277. { DateTimeToStr returns a string representation of DateTime using ShortDateFormat and LongTimeFormat }
  278. Const
  279. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  280. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  281. begin
  282. DateTimeToString(Result, DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  283. end ;
  284. function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings; ForceTimeIfZero : Boolean = False): string;
  285. begin
  286. DateTimeToString(Result, DateTimeToStrFormat[ForceTimeIfZero], DateTime ,FormatSettings);
  287. end;
  288. { StrToDate converts the string S to a TDateTime value
  289. if S does not represent a valid date value
  290. an EConvertError will be raised }
  291. function IntStrToDate(Out ErrorMsg : AnsiString; const S: PChar; Len : integer; const useformat : string; const defs:TFormatSettings; separator : char = #0): TDateTime;
  292. const SInvalidDateFormat = '"%s" is not a valid date format';
  293. procedure FixErrorMsg(const errm :ansistring;const errmarg : ansistring);
  294. begin
  295. errormsg:=format(errm,[errmarg]);
  296. end;
  297. var
  298. df:string;
  299. d,m,y,ly:integer;
  300. n,i:longint;
  301. c:word;
  302. dp,mp,yp,which : Byte;
  303. s1:string;
  304. values:array[0..3] of longint;
  305. LocalTime:tsystemtime;
  306. YearMoreThenTwoDigits : boolean;
  307. begin
  308. ErrorMsg:=''; Result:=0;
  309. While (Len>0) and (S[Len-1] in [' ',#8,#9,#10,#12,#13]) do
  310. Dec(len);
  311. if (Len=0) then
  312. begin
  313. FixErrorMsg(SInvalidDateFormat,'');
  314. exit;
  315. end;
  316. YearMoreThenTwoDigits := False;
  317. if separator = #0 then
  318. separator := defs.DateSeparator;
  319. df := UpperCase(useFormat);
  320. { Determine order of D,M,Y }
  321. yp:=0;
  322. mp:=0;
  323. dp:=0;
  324. Which:=0;
  325. i:=0;
  326. while (i<Length(df)) and (Which<3) do
  327. begin
  328. inc(i);
  329. Case df[i] of
  330. 'Y' :
  331. if yp=0 then
  332. begin
  333. Inc(Which);
  334. yp:=which;
  335. end;
  336. 'M' :
  337. if mp=0 then
  338. begin
  339. Inc(Which);
  340. mp:=which;
  341. end;
  342. 'D' :
  343. if dp=0 then
  344. begin
  345. Inc(Which);
  346. dp:=which;
  347. end;
  348. end;
  349. end;
  350. for i := 1 to 3 do
  351. values[i] := 0;
  352. s1 := '';
  353. n := 0;
  354. dec(len);
  355. for i := 0 to len do
  356. begin
  357. if s[i] in ['0'..'9'] then
  358. s1 := s1 + s[i];
  359. { space can be part of the shortdateformat, and is defaultly in slovak
  360. windows, therefor it shouldn't be taken as separator (unless so specified)
  361. and ignored }
  362. if (Separator <> ' ') and (s[i] = ' ') then
  363. Continue;
  364. if (s[i] = separator) or ((i = len) and (s[i] in ['0'..'9'])) then
  365. begin
  366. inc(n);
  367. if n>3 then
  368. begin
  369. FixErrorMsg(SInvalidDateFormat,s);
  370. exit;
  371. end;
  372. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  373. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  374. val(s1, values[n], c);
  375. // Writeln(s1,'->',values[n]);
  376. if c<>0 then
  377. begin
  378. FixErrorMsg(SInvalidDateFormat,s);
  379. Exit;
  380. end;
  381. s1 := '';
  382. end
  383. else if not (s[i] in ['0'..'9']) then
  384. begin
  385. FixErrorMsg(SInvalidDateFormat,s);
  386. Exit;
  387. end;
  388. end ;
  389. if (Which<3) and (N>Which) then
  390. begin
  391. FixErrorMsg(SInvalidDateFormat,s);
  392. Exit;
  393. end;
  394. // Fill in values.
  395. getLocalTime(LocalTime);
  396. ly := LocalTime.Year;
  397. for I:=1 to 3 do
  398. if values[i]>high(Word) then
  399. begin
  400. errormsg:='Invalid date';
  401. exit;
  402. end;
  403. If N=3 then
  404. begin
  405. y:=values[yp];
  406. m:=values[mp];
  407. d:=values[dp];
  408. end
  409. Else
  410. begin
  411. Y:=ly;
  412. If n<2 then
  413. begin
  414. d:=values[1];
  415. m := LocalTime.Month;
  416. end
  417. else
  418. If dp<mp then
  419. begin
  420. d:=values[1];
  421. m:=values[2];
  422. end
  423. else
  424. begin
  425. d:=values[2];
  426. m:=values[1];
  427. end;
  428. end;
  429. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  430. begin
  431. ly := ly - defs.TwoDigitYearCenturyWindow;
  432. Inc(Y, ly div 100 * 100);
  433. if (defs.TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  434. Inc(Y, 100);
  435. end;
  436. if not TryEncodeDate(y, m, d, result) then
  437. errormsg:='Invalid date';
  438. end;
  439. function StrToDate(const S: PChar; Len : integer; const useformat : string; separator : char = #0): TDateTime;
  440. Var
  441. MSg : AnsiString;
  442. begin
  443. Result:=IntStrToDate(Msg,S,Len,useFormat,DefaultFormatSettings,Separator);
  444. If (Msg<>'') then
  445. Raise EConvertError.Create(Msg);
  446. end;
  447. function StrToDate(const S: string; FormatSettings: TFormatSettings): TDateTime;
  448. var
  449. Msg: AnsiString;
  450. begin
  451. Result:=IntStrToDate(Msg,PChar(S),Length(S),FormatSettings.ShortDateFormat,FormatSettings);
  452. if Msg<>'' then
  453. raise EConvertError.Create(Msg);
  454. end;
  455. function StrToDate(const S: ShortString; const useformat : string; separator : char = #0): TDateTime;
  456. begin
  457. // S[1] always exists for shortstring. Length 0 will trigger an error.
  458. result := StrToDate(@S[1],Length(s),UseFormat,separator);
  459. end;
  460. function StrToDate(const S: AnsiString; const useformat : string; separator : char = #0): TDateTime;
  461. begin
  462. result := StrToDate(PChar(S),Length(s),UseFormat,separator);
  463. end;
  464. function StrToDate(const S: ShortString; separator : char): TDateTime;
  465. begin
  466. // S[1] always exists for shortstring. Length 0 will trigger an error.
  467. result := StrToDate(@S[1],Length(s),DefaultFormatSettings.ShortDateFormat,separator)
  468. end;
  469. function StrToDate(const S: ShortString): TDateTime;
  470. begin
  471. // S[1] always exists for shortstring. Length 0 will trigger an error.
  472. result := StrToDate(@S[1],Length(s),DefaultFormatSettings.ShortDateFormat,#0);
  473. end;
  474. function StrToDate(const S: AnsiString; separator : char): TDateTime;
  475. begin
  476. result := StrToDate(Pchar(S),Length(s),DefaultFormatSettings.ShortDateFormat,separator)
  477. end;
  478. function StrToDate(const S: AnsiString): TDateTime;
  479. begin
  480. result := StrToDate(Pchar(S),Length(s),DefaultFormatSettings.ShortDateFormat,#0);
  481. end;
  482. { StrToTime converts the string S to a TDateTime value
  483. if S does not represent a valid time value an
  484. EConvertError will be raised }
  485. function IntStrToTime(Out ErrorMsg : AnsiString; const S: PChar; Len : integer;const defs:TFormatSettings; separator : char = #0): TDateTime;
  486. const
  487. AMPM_None = 0;
  488. AMPM_AM = 1;
  489. AMPM_PM = 2;
  490. tiHour = 0;
  491. tiMin = 1;
  492. tiSec = 2;
  493. tiMSec = 3;
  494. type
  495. TTimeValues = array[tiHour..tiMSec] of Word;
  496. var
  497. AmPm: integer;
  498. TimeValues: TTimeValues;
  499. function StrPas(Src : PChar; len: integer = 0) : ShortString;
  500. begin
  501. //this is unsafe for len > 255, it will trash memory (I tested this)
  502. //reducing it is safe, since whenever we use this a string > 255 is invalid anyway
  503. if len > 255 then len := 255;
  504. SetLength(Result, len);
  505. move(src[0],result[1],len);
  506. end;
  507. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  508. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  509. const
  510. Digits = ['0'..'9'];
  511. var
  512. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  513. Value: Word;
  514. DigitPending, MSecPending: Boolean;
  515. AmPmStr: ShortString;
  516. CurChar: Char;
  517. begin
  518. Result := False;
  519. AmPm := AMPM_None; //No Am or PM in string found yet
  520. MSecPending := False;
  521. TimeIndex := 0; //indicating which TTimeValue must be filled next
  522. FillChar(TimeValues, SizeOf(TTimeValues), 0);
  523. Cur := 0;
  524. //skip leading blanks
  525. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  526. Offset := Cur;
  527. //First non-blank cannot be Separator or DecimalSeparator
  528. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = defs.Decimalseparator) then Exit;
  529. DigitPending := (S[Cur] in Digits);
  530. While (Cur < Len) do
  531. begin
  532. //writeln;
  533. //writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len);
  534. CurChar := S[Cur];
  535. if CurChar in Digits then
  536. begin//Digits
  537. //HH, MM, SS, or Msec?
  538. //writeln('Digit');
  539. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  540. //and TimeIndex must be <= tiMSec
  541. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  542. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then Exit;
  543. OffSet := Cur;
  544. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  545. while (Cur < Len -1) and (S[Cur + 1] in Digits) do
  546. begin
  547. //Mark first Digit that is not '0'
  548. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  549. Inc(Cur);
  550. end;
  551. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  552. ElemLen := 1 + Cur - FirstSignificantDigit;
  553. //writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', StrPas(S + Offset, ElemLen));
  554. //writeln(' Cur = ',Cur);
  555. //this way we know that Val() will never overflow Value !
  556. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  557. begin
  558. Val(StrPas(S + FirstSignificantDigit, ElemLen), Value, Err);
  559. //writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  560. //This is safe now, because we know Value < High(Word)
  561. TimeValues[TimeIndex] := Value;
  562. Inc(TimeIndex);
  563. DigitPending := False;
  564. end
  565. else Exit; //Value to big, so it must be a wrong timestring
  566. end//Digits
  567. else if (CurChar = #32) then
  568. begin
  569. //writeln('#32');
  570. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  571. end
  572. else if (CurChar = Separator) then
  573. begin
  574. //writeln('Separator');
  575. if DigitPending or (TimeIndex > tiSec) then Exit;
  576. DigitPending := True;
  577. MSecPending := False;
  578. end
  579. else if (CurChar = defs.DecimalSeparator) then
  580. begin
  581. //writeln('DecimalSeparator');
  582. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then Exit;
  583. DigitPending := True;
  584. MSecPending := True;
  585. end
  586. else
  587. begin//AM/PM?
  588. //None of the above, so this char _must_ be the start of AM/PM string
  589. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  590. //writeln('AM/PM?');
  591. if (AmPm <> AMPM_None) or DigitPending then Exit;
  592. OffSet := Cur;
  593. while (Cur < Len -1) and (not (S[Cur + 1] in [Separator, #32, defs.DecimalSeparator]))
  594. and not (S[Cur + 1] in Digits) do Inc(Cur);
  595. ElemLen := 1 + Cur - OffSet;
  596. //writeln(' S[Offset] = ',S[Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', StrPas(S + Offset, ElemLen));
  597. //writeln(' Cur = ',Cur);
  598. AmPmStr := StrPas(S + OffSet, ElemLen);
  599. //writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  600. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  601. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  602. if (AnsiCompareText(AmPmStr, defs.TimeAMString) = 0) then AmPm := AMPM_AM
  603. else if (AnsiCompareText(AmPmStr, defs.TimePMString) = 0) then AmPm := AMPM_PM
  604. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  605. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  606. else Exit; //If text does not match any of these, timestring must be wrong;
  607. //if AM/PM is at beginning of string, then a digit is mandatory after it
  608. if (TimeIndex = tiHour) then
  609. begin
  610. DigitPending := True;
  611. end
  612. //otherwise, no more TimeValues allowed after this
  613. else
  614. begin
  615. TimeIndex := tiMSec + 1;
  616. DigitPending := False;
  617. end;
  618. end;//AM/PM
  619. Inc(Cur)
  620. end;//while
  621. //If we arrive here, parsing the elements has been successfull
  622. //if not at least Hours specified then input is not valid
  623. //when am/pm is specified Hour must be <= 12 and not 0
  624. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then Exit;
  625. Result := True;
  626. end;
  627. begin
  628. if separator = #0 then
  629. separator := defs.TimeSeparator;
  630. AmPm := AMPM_None;
  631. if not SplitElements(TimeValues, AmPm) then
  632. begin
  633. ErrorMsg:=Format(SErrInvalidTimeFormat,[StrPas(S, Len)]);
  634. Exit;
  635. end;
  636. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  637. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  638. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  639. //errormsg:='Invalid time.';
  640. ErrorMsg:=Format(SErrInvalidTimeFormat,[StrPas(S, Len)]);
  641. end ;
  642. function StrToTime(const S: PChar; Len : integer; separator : char = #0): TDateTime;
  643. Var
  644. Msg : AnsiString;
  645. begin
  646. Result:=IntStrToTime(Msg,S,Len,DefaultFormatSettings,Separator);
  647. If (Msg<>'') then
  648. Raise EConvertError.Create(Msg);
  649. end;
  650. function StrToTime(const S: string; FormatSettings : TFormatSettings): TDateTime;
  651. Var
  652. Msg : AnsiString;
  653. begin
  654. Result:=IntStrToTime(Msg, PChar(S), length(S), FormatSettings, #0);
  655. If (Msg<>'') then
  656. Raise EConvertError.Create(Msg);
  657. end;
  658. function StrToTime(const s: ShortString; separator : char): TDateTime;
  659. begin
  660. // S[1] always exists for shortstring. Length 0 will trigger an error.
  661. result := StrToTime(@s[1], length(s), separator);
  662. end;
  663. function StrToTime(const s: AnsiString; separator : char): TDateTime;
  664. begin
  665. result := StrToTime(PChar(S), length(s), separator);
  666. end;
  667. function StrToTime(const s: ShortString): TDateTime;
  668. begin
  669. // S[1] always exists for shortstring. Length 0 will trigger an error.
  670. result := StrToTime(@s[1], length(s), #0);
  671. end;
  672. function StrToTime(const s: AnsiString): TDateTime;
  673. begin
  674. result:= StrToTime(PChar(s), length(s), #0);
  675. end;
  676. { StrToDateTime converts the string S to a TDateTime value
  677. if S does not represent a valid date and/or time value
  678. an EConvertError will be raised }
  679. function SplitDateTimeStr(DateTimeStr: AnsiString; const FS: TFormatSettings; out DateStr, TimeStr: AnsiString): Integer;
  680. { Helper function for StrToDateTime
  681. Pre-condition
  682. Date is before Time
  683. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  684. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  685. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  686. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  687. Post-condition
  688. DateStr holds date as string or is empty
  689. TimeStr holds time as string or is empty
  690. Result = number of strings returned, 0 = error
  691. }
  692. const
  693. WhiteSpace = [#9,#10,#13,#32];
  694. Space : String = #32; // String, to avoid error 'Cannot decide what overload to call'
  695. var
  696. p: Integer;
  697. DummyDT: TDateTime;
  698. begin
  699. Result := 0;
  700. DateStr := '';
  701. TimeStr := '';
  702. DateTimeStr := Trim(DateTimeStr);
  703. if Length(DateTimeStr) = 0 then exit;
  704. if (FS.DateSeparator = #32) and (FS.TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  705. begin
  706. DateStr:=DateTimeStr;
  707. {
  708. Assume a date: dd [mm [yy]].
  709. Really fancy would be counting the number of whitespace occurrences and decide
  710. and split accordingly
  711. }
  712. Exit(1);
  713. end;
  714. p:=1;
  715. //find separator
  716. if Pos(Space,FS.DateSeparator)=0 then
  717. begin
  718. while (p<Length(DateTimeStr)) and (not (DateTimeStr[p+1] in WhiteSpace)) do
  719. Inc(p);
  720. end
  721. else
  722. begin
  723. p:=Pos(FS.TimeSeparator, DateTimeStr);
  724. if (p<>0) then
  725. repeat
  726. Dec(p);
  727. until (p=0) or (DateTimeStr[p] in WhiteSpace);
  728. end;
  729. //Always fill DateStr, it eases the algorithm later
  730. if (p=0) then
  731. p:=Length(DateTimeStr);
  732. DateStr:=Copy(DateTimeStr,1,p);
  733. TimeStr:=Trim(Copy(DateTimeStr,p+1,MaxInt));
  734. if (Length(TimeStr)<>0) then
  735. Result:=2
  736. else
  737. begin
  738. Result:=1; //found 1 string
  739. // 2 cases when DateTimeStr only contains a time:
  740. // Date/time separator differ, and string contains a timeseparator
  741. // Date/time separators are equal, but transformation to date fails.
  742. if ((FS.DateSeparator<>FS.TimeSeparator) and (Pos(FS.TimeSeparator,DateStr) > 0))
  743. or ((FS.DateSeparator=FS.TimeSeparator) and (not TryStrToDate(DateStr, DummyDT, FS))) then
  744. begin
  745. TimeStr := DateStr;
  746. DateStr := '';
  747. end;
  748. end;
  749. end;
  750. function StrToDateTime(const s: AnsiString; const FormatSettings : TFormatSettings): TDateTime;
  751. var
  752. TimeStr, DateStr: AnsiString;
  753. PartsFound: Integer;
  754. begin
  755. PartsFound := SplitDateTimeStr(S, FormatSettings, DateStr, TimeStr);
  756. case PartsFound of
  757. 0: Result:=StrToDate('');
  758. 1: if (Length(DateStr) > 0) then
  759. Result := StrToDate(DateStr, FormatSettings.ShortDateFormat,FormatSettings.DateSeparator)
  760. else
  761. Result := StrToTime(TimeStr, FormatSettings);
  762. 2: Result := ComposeDateTime(StrTodate(DateStr,FormatSettings.ShortDateFormat,FormatSettings.DateSeparator),
  763. StrToTime(TimeStr,FormatSettings));
  764. end;
  765. end;
  766. function StrToDateTime(const s: AnsiString): TDateTime;
  767. begin
  768. Result:=StrToDateTime(S,DefaultFormatSettings);
  769. end;
  770. function StrToDateTime(const s: ShortString; const FormatSettings : TFormatSettings): TDateTime;
  771. var
  772. A : AnsiString;
  773. begin
  774. A:=S;
  775. Result:=StrToDateTime(A,FormatSettings);
  776. end;
  777. { FormatDateTime formats DateTime to the given format string FormatStr }
  778. function FormatDateTime(const FormatStr: string; DateTime: TDateTime; Options : TFormatDateTimeOptions = []): string;
  779. begin
  780. DateTimeToString(Result, FormatStr, DateTime, DefaultFormatSettings,Options);
  781. end;
  782. function FormatDateTime(const FormatStr: string; DateTime: TDateTime; const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []): string;
  783. begin
  784. DateTimeToString(Result, FormatStr, DateTime, FormatSettings,Options);
  785. end;
  786. { DateTimeToString formats DateTime to the given format in FormatStr }
  787. procedure DateTimeToString(out Result: string; const FormatStr: string;
  788. const DateTime: TDateTime; Options : TFormatDateTimeOptions = []);
  789. begin
  790. DateTimeToString(Result, FormatStr, DateTime, DefaultFormatSettings, Options);
  791. end;
  792. procedure DateTimeToString(out Result: string; const FormatStr: string; const DateTime: TDateTime;
  793. const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []);
  794. var
  795. ResultLen: integer;
  796. ResultBuffer: array[0..255] of char;
  797. ResultCurrent: pchar;
  798. {$if defined(win32) or defined(win64)}
  799. isEnable_E_Format : Boolean;
  800. isEnable_G_Format : Boolean;
  801. eastasiainited : boolean;
  802. procedure InitEastAsia;
  803. var ALCID : LCID;
  804. PriLangID , SubLangID : Word;
  805. begin
  806. ALCID := GetThreadLocale;
  807. PriLangID := ALCID and $3FF;
  808. if (PriLangID>0) then
  809. SubLangID := (ALCID and $FFFF) shr 10
  810. else
  811. begin
  812. PriLangID := SysLocale.PriLangID;
  813. SubLangID := SysLocale.SubLangID;
  814. end;
  815. isEnable_E_Format := (PriLangID = LANG_JAPANESE)
  816. or
  817. (PriLangID = LANG_KOREAN)
  818. or
  819. ((PriLangID = LANG_CHINESE)
  820. and
  821. (SubLangID = SUBLANG_CHINESE_TRADITIONAL)
  822. );
  823. isEnable_G_Format := (PriLangID = LANG_JAPANESE)
  824. or
  825. ((PriLangID = LANG_CHINESE)
  826. and
  827. (SubLangID = SUBLANG_CHINESE_TRADITIONAL)
  828. );
  829. eastasiainited :=true;
  830. end;
  831. {$endif win32 or win64}
  832. procedure StoreStr(Str: PChar; Len: Integer);
  833. begin
  834. if ResultLen + Len < SizeOf(ResultBuffer) then
  835. begin
  836. StrMove(ResultCurrent, Str, Len);
  837. ResultCurrent := ResultCurrent + Len;
  838. ResultLen := ResultLen + Len;
  839. end;
  840. end;
  841. procedure StoreString(const Str: string);
  842. var Len: integer;
  843. begin
  844. Len := Length(Str);
  845. if ResultLen + Len < SizeOf(ResultBuffer) then
  846. begin
  847. StrMove(ResultCurrent, pchar(Str), Len);
  848. ResultCurrent := ResultCurrent + Len;
  849. ResultLen := ResultLen + Len;
  850. end;
  851. end;
  852. procedure StoreInt(Value, Digits: Integer);
  853. var
  854. S: string[16];
  855. Len: integer;
  856. begin
  857. System.Str(Value:Digits, S);
  858. for Len := 1 to Length(S) do
  859. begin
  860. if S[Len] = ' ' then
  861. S[Len] := '0'
  862. else
  863. Break;
  864. end;
  865. StoreStr(pchar(@S[1]), Length(S));
  866. end ;
  867. var
  868. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  869. function FullDays(ADateTime: TDateTime): Integer;
  870. begin
  871. if ADateTime < 0 then ADateTime := -ADateTime;
  872. Result := trunc(ADateTime);
  873. if (frac(ADateTime) > 0.9) and (Hour = 0) and (Minute = 0) and (Second = 0) and (Millisecond = 0) then
  874. inc(Result);
  875. end;
  876. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  877. var
  878. Token, lastformattoken, prevlasttoken: char;
  879. FormatCurrent: pchar;
  880. FormatEnd: pchar;
  881. Count: integer;
  882. Clock12: boolean;
  883. P: pchar;
  884. tmp: integer;
  885. isInterval: Boolean;
  886. begin
  887. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  888. Exit;
  889. FormatCurrent := PChar(FormatStr);
  890. FormatEnd := FormatCurrent + Length(FormatStr);
  891. Clock12 := false;
  892. isInterval := false;
  893. P := FormatCurrent;
  894. // look for unquoted 12-hour clock token
  895. while P < FormatEnd do
  896. begin
  897. Token := P^;
  898. case Token of
  899. '''', '"':
  900. begin
  901. Inc(P);
  902. while (P < FormatEnd) and (P^ <> Token) do
  903. Inc(P);
  904. end;
  905. 'A', 'a':
  906. begin
  907. if (StrLIComp(P, 'A/P', 3) = 0) or
  908. (StrLIComp(P, 'AMPM', 4) = 0) or
  909. (StrLIComp(P, 'AM/PM', 5) = 0) then
  910. begin
  911. Clock12 := true;
  912. break;
  913. end;
  914. end;
  915. end; // case
  916. Inc(P);
  917. end ;
  918. token := #255;
  919. lastformattoken := ' ';
  920. prevlasttoken := 'H';
  921. while FormatCurrent < FormatEnd do
  922. begin
  923. Token := UpCase(FormatCurrent^);
  924. Count := 1;
  925. P := FormatCurrent + 1;
  926. case Token of
  927. '''', '"':
  928. begin
  929. while (P < FormatEnd) and (p^ <> Token) do
  930. Inc(P);
  931. Inc(P);
  932. Count := P - FormatCurrent;
  933. StoreStr(FormatCurrent + 1, Count - 2);
  934. end ;
  935. 'A':
  936. begin
  937. if StrLIComp(FormatCurrent, 'AMPM', 4) = 0 then
  938. begin
  939. Count := 4;
  940. if Hour < 12 then
  941. StoreString(FormatSettings.TimeAMString)
  942. else
  943. StoreString(FormatSettings.TimePMString);
  944. end
  945. else if StrLIComp(FormatCurrent, 'AM/PM', 5) = 0 then
  946. begin
  947. Count := 5;
  948. if Hour < 12 then StoreStr(FormatCurrent, 2)
  949. else StoreStr(FormatCurrent+3, 2);
  950. end
  951. else if StrLIComp(FormatCurrent, 'A/P', 3) = 0 then
  952. begin
  953. Count := 3;
  954. if Hour < 12 then StoreStr(FormatCurrent, 1)
  955. else StoreStr(FormatCurrent+2, 1);
  956. end
  957. else
  958. raise EConvertError.Create('Illegal character in format string');
  959. end ;
  960. '/': if FormatSettings.DateSeparator<>#0 then StoreStr(@FormatSettings.DateSeparator, 1);
  961. ':': if FormatSettings.TimeSeparator<>#0 then StoreStr(@FormatSettings.TimeSeparator, 1);
  962. '[': if (fdoInterval in Options) then isInterval := true else StoreStr(FormatCurrent, 1);
  963. ']': if (fdoInterval in Options) then isInterval := false else StoreStr(FormatCurrent, 1);
  964. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' {$IFDEF MSWindows}, 'G', 'E'{$ENDIF MSWindows} :
  965. begin
  966. while (P < FormatEnd) and (UpCase(P^) = Token) do
  967. Inc(P);
  968. Count := P - FormatCurrent;
  969. case Token of
  970. ' ': StoreStr(FormatCurrent, Count);
  971. 'Y': begin
  972. if Count > 2 then
  973. StoreInt(Year, 4)
  974. else
  975. StoreInt(Year mod 100, 2);
  976. end;
  977. 'M': begin
  978. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  979. StoreInt(Minute + (Hour + FullDays(DateTime)*24)*60, 0)
  980. else
  981. if (lastformattoken = 'H') or TimeFlag then
  982. begin
  983. if Count = 1 then
  984. StoreInt(Minute, 0)
  985. else
  986. StoreInt(Minute, 2);
  987. end
  988. else
  989. begin
  990. case Count of
  991. 1: StoreInt(Month, 0);
  992. 2: StoreInt(Month, 2);
  993. 3: StoreString(FormatSettings.ShortMonthNames[Month]);
  994. else
  995. StoreString(FormatSettings.LongMonthNames[Month]);
  996. end;
  997. end;
  998. end;
  999. 'D': begin
  1000. case Count of
  1001. 1: StoreInt(Day, 0);
  1002. 2: StoreInt(Day, 2);
  1003. 3: StoreString(FormatSettings.ShortDayNames[DayOfWeek]);
  1004. 4: StoreString(FormatSettings.LongDayNames[DayOfWeek]);
  1005. 5: StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  1006. else
  1007. StoreFormat(FormatSettings.LongDateFormat, Nesting+1, False);
  1008. end ;
  1009. end ;
  1010. 'H':
  1011. if isInterval then
  1012. StoreInt(Hour + FullDays(DateTime)*24, Count)
  1013. else
  1014. if Clock12 then
  1015. begin
  1016. tmp := hour mod 12;
  1017. if tmp=0 then tmp:=12;
  1018. if Count = 1 then
  1019. StoreInt(tmp, 0)
  1020. else
  1021. StoreInt(tmp, 2);
  1022. end
  1023. else begin
  1024. if Count = 1 then
  1025. StoreInt(Hour, 0)
  1026. else
  1027. StoreInt(Hour, 2);
  1028. end;
  1029. 'N': if isInterval then
  1030. StoreInt(Minute + (Hour + FullDays(DateTime)*24)*60, Count)
  1031. else
  1032. if Count = 1 then
  1033. StoreInt(Minute, 0)
  1034. else
  1035. StoreInt(Minute, 2);
  1036. 'S': if isInterval then
  1037. StoreInt(Second + (Minute + (Hour + FullDays(DateTime)*24)*60)*60, Count)
  1038. else
  1039. if Count = 1 then
  1040. StoreInt(Second, 0)
  1041. else
  1042. StoreInt(Second, 2);
  1043. 'Z': if Count = 1 then
  1044. StoreInt(MilliSecond, 0)
  1045. else
  1046. StoreInt(MilliSecond, 3);
  1047. 'T': if Count = 1 then
  1048. StoreFormat(FormatSettings.ShortTimeFormat, Nesting+1, True)
  1049. else
  1050. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1051. 'C': begin
  1052. StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  1053. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  1054. begin
  1055. StoreString(' ');
  1056. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1057. end;
  1058. end;
  1059. 'F': begin
  1060. StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  1061. StoreString(' ');
  1062. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1063. end;
  1064. {$if defined(win32) or defined(win64)}
  1065. 'E':
  1066. begin
  1067. if not Eastasiainited then InitEastAsia;
  1068. if Not(isEnable_E_Format) then StoreStr(FormatCurrent, 1)
  1069. else
  1070. begin
  1071. while (P < FormatEnd) and (UpCase(P^) = Token) do
  1072. P := P + 1;
  1073. Count := P - FormatCurrent;
  1074. StoreString(ConvertEraYearString(Count,Year,Month,Day));
  1075. end;
  1076. prevlasttoken := lastformattoken;
  1077. lastformattoken:=token;
  1078. end;
  1079. 'G':
  1080. begin
  1081. if not Eastasiainited then InitEastAsia;
  1082. if Not(isEnable_G_Format) then StoreStr(FormatCurrent, 1)
  1083. else
  1084. begin
  1085. while (P < FormatEnd) and (UpCase(P^) = Token) do
  1086. P := P + 1;
  1087. Count := P - FormatCurrent;
  1088. StoreString(ConvertEraString(Count,Year,Month,Day));
  1089. end;
  1090. prevlasttoken := lastformattoken;
  1091. lastformattoken:=token;
  1092. end;
  1093. {$endif win32 or win64}
  1094. end;
  1095. prevlasttoken := lastformattoken;
  1096. lastformattoken := token;
  1097. end;
  1098. else
  1099. StoreStr(@Token, 1);
  1100. end ;
  1101. Inc(FormatCurrent, Count);
  1102. end;
  1103. end;
  1104. begin
  1105. {$if defined(win32) or defined(win64)}
  1106. eastasiainited:=false;
  1107. {$endif win32 or win64}
  1108. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  1109. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  1110. ResultLen := 0;
  1111. ResultCurrent := @ResultBuffer[0];
  1112. if FormatStr <> '' then
  1113. StoreFormat(FormatStr, 0, False)
  1114. else
  1115. StoreFormat('C', 0, False);
  1116. ResultBuffer[ResultLen] := #0;
  1117. result := StrPas(@ResultBuffer[0]);
  1118. if (DateTime < 0) and (fdoInterval in Options) then
  1119. result := '-' + result;
  1120. end ;
  1121. Function DateTimeToFileDate(DateTime : TDateTime) : Int64;
  1122. Var YY,MM,DD,H,m,s,msec : Word;
  1123. begin
  1124. Decodedate (DateTime,YY,MM,DD);
  1125. DecodeTime (DateTime,h,m,s,msec);
  1126. {$ifndef unix}
  1127. If (YY<1980) or (YY>2099) then
  1128. Result:=0
  1129. else
  1130. begin
  1131. Result:=(s shr 1) or (m shl 5) or (h shl 11);
  1132. Result:=Result or longint(DD shl 16 or (MM shl 21) or (word(YY-1980) shl 25));
  1133. end;
  1134. {$else unix}
  1135. Result:=LocalToEpoch(yy,mm,dd,h,m,s);
  1136. {$endif unix}
  1137. end;
  1138. function CurrentYear: Word;
  1139. var
  1140. SysTime: TSystemTime;
  1141. begin
  1142. GetLocalTime(SysTime);
  1143. Result := SysTime.Year;
  1144. end;
  1145. Function FileDateToDateTime (Filedate : Int64) : TDateTime;
  1146. {$ifndef unix}
  1147. Var Date,Time : Word;
  1148. begin
  1149. Date:=FileDate shr 16;
  1150. Time:=FileDate and $ffff;
  1151. Result:=ComposeDateTime(EncodeDate((Date shr 9) + 1980,(Date shr 5) and 15, Date and 31),
  1152. EncodeTime(Time shr 11, (Time shr 5) and 63, (Time and 31) shl 1,0));
  1153. end;
  1154. {$else unix}
  1155. var
  1156. y, mon, d, h, min, s: word;
  1157. begin
  1158. EpochToLocal(FileDate,y,mon,d,h,min,s);
  1159. Result:=ComposeDateTime(EncodeDate(y,mon,d),EncodeTime(h,min,s,0));
  1160. end;
  1161. {$endif unix}
  1162. Function FileDateToUTC (Filedate : Int64) : TDateTime;
  1163. {$ifndef unix}
  1164. begin
  1165. Result := LocalTimeToUniversal(FileDateToDateTime(Filedate));
  1166. end;
  1167. {$else unix}
  1168. var
  1169. y, mon, d, h, min, s: word;
  1170. begin
  1171. EpochToUniversal(FileDate,y,mon,d,h,min,s);
  1172. Result:=ComposeDateTime(EncodeDate(y,mon,d),EncodeTime(h,min,s,0));
  1173. end;
  1174. {$endif unix}
  1175. function TryStrToDate(const S: ShortString; out Value: TDateTime): Boolean;
  1176. begin
  1177. result := TryStrToDate(S, Value, #0);
  1178. end;
  1179. function TryStrToDate(const S: ShortString; out Value: TDateTime;
  1180. const useformat : string; separator : char = #0): Boolean;
  1181. Var
  1182. Msg : Ansistring;
  1183. begin
  1184. // S[1] always exists for shortstring. Length 0 will trigger an error.
  1185. Value:=IntStrToDate(Msg,@S[1],Length(S),useformat,defaultformatsettings,separator);
  1186. Result:=(Msg='');
  1187. end;
  1188. function TryStrToDate(const S: AnsiString; out Value: TDateTime;
  1189. const useformat : string; separator : char = #0): Boolean;
  1190. Var
  1191. Msg : Ansistring;
  1192. begin
  1193. Result:=Length(S)<>0;
  1194. If Result then
  1195. begin
  1196. Value:=IntStrToDate(Msg,PChar(S),Length(S),useformat,DefaultFormatSettings,Separator);
  1197. Result:=(Msg='');
  1198. end;
  1199. end;
  1200. function TryStrToDate(const S: ShortString; out Value: TDateTime; separator : char): Boolean;
  1201. begin
  1202. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,Separator);
  1203. end;
  1204. function TryStrToDate(const S: AnsiString; out Value: TDateTime): Boolean;
  1205. begin
  1206. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,#0);
  1207. end;
  1208. function TryStrToDate(const S: AnsiString; out Value: TDateTime; separator : char): Boolean;
  1209. begin
  1210. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,Separator);
  1211. end;
  1212. function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1213. Var
  1214. Msg : Ansistring;
  1215. begin
  1216. Result:=Length(S)<>0;
  1217. If Result then
  1218. begin
  1219. Value:=IntStrToDate(Msg,PChar(S),Length(S),FormatSettings.ShortDateFormat,FormatSettings,#0);
  1220. Result:=(Msg='');
  1221. end;
  1222. end;
  1223. function TryStrToTime(const S: ShortString; out Value: TDateTime; separator : char): Boolean;
  1224. Var
  1225. Msg : AnsiString;
  1226. begin
  1227. // S[1] always exists for shortstring. Length 0 will trigger an error.
  1228. Value:=IntStrToTime(Msg,@S[1],Length(S),DefaultFormatSettings,Separator);
  1229. result:=(Msg='');
  1230. end;
  1231. function TryStrToTime(const S: ShortString; out Value: TDateTime): Boolean;
  1232. begin
  1233. Result := TryStrToTime(S,Value,#0);
  1234. end;
  1235. function TryStrToTime(const S: AnsiString; out Value: TDateTime; separator : char): Boolean;
  1236. Var
  1237. Msg : AnsiString;
  1238. begin
  1239. Result:=Length(S)<>0;
  1240. If Result then
  1241. begin
  1242. Value:=IntStrToTime(Msg,PChar(S),Length(S),DefaultFormatSettings,Separator);
  1243. Result:=(Msg='');
  1244. end;
  1245. end;
  1246. function TryStrToTime(const S: AnsiString; out Value: TDateTime): Boolean;
  1247. begin
  1248. result := TryStrToTime(S,Value,#0);
  1249. end;
  1250. function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1251. Var msg : AnsiString;
  1252. begin
  1253. Result:=Length(S)<>0;
  1254. If Result then
  1255. begin
  1256. Value:=IntStrToTime(Msg,PChar(S),Length(S),FormatSettings,#0);
  1257. Result:=(Msg='');
  1258. end;
  1259. end;
  1260. function TryStrToDateTime(const S: ShortString; out Value: TDateTime): Boolean;
  1261. begin
  1262. result := TryStrToDateTime(S, Value, DefaultFormatSettings);
  1263. end;
  1264. function TryStrToDateTime(const S: AnsiString; out Value: TDateTime): Boolean;
  1265. begin
  1266. result := TryStrToDateTime(S, Value, DefaultFormatSettings);
  1267. end;
  1268. function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1269. var
  1270. I: integer;
  1271. dtdate, dttime :TDateTime;
  1272. begin
  1273. result:=false;
  1274. I:=Pos(FormatSettings.TimeSeparator,S);
  1275. If (I>0) then
  1276. begin
  1277. While (I>0) and (S[I]<>' ') do
  1278. Dec(I);
  1279. If I>0 then
  1280. begin
  1281. if not TryStrToDate(Copy(S,1,I-1),dtdate,Formatsettings) then
  1282. exit;
  1283. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime,Formatsettings) then
  1284. exit;
  1285. Value:=ComposeDateTime(dtdate,dttime);
  1286. result:=true;
  1287. end
  1288. else
  1289. result:=TryStrToTime(s,Value,Formatsettings);
  1290. end
  1291. else
  1292. result:=TryStrToDate(s,Value,Formatsettings);
  1293. end;
  1294. function StrToDateDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1295. begin
  1296. result := StrToDateDef(S,DefValue,#0);
  1297. end;
  1298. function StrToTimeDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1299. begin
  1300. result := StrToTimeDef(S,DefValue,#0);
  1301. end;
  1302. function StrToDateTimeDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1303. begin
  1304. Result:=StrToDateTimeDef(S,DefValue,DefaultFormatSettings);
  1305. end;
  1306. function StrToDateTimeDef(const S: AnsiString; const Defvalue : TDateTime; const FormatSettings: TFormatSettings): TDateTime;
  1307. begin
  1308. if not TryStrToDateTime(s,Result,FormatSettings) Then
  1309. result:=defvalue;
  1310. end;
  1311. function StrToDateDef(const S: ShortString; const Defvalue : TDateTime; separator : char): TDateTime;
  1312. begin
  1313. if not TryStrToDate(s,Result, separator) Then
  1314. result:=defvalue;
  1315. end;
  1316. function StrToTimeDef(const S: ShortString; const Defvalue : TDateTime; separator : char): TDateTime;
  1317. begin
  1318. if not TryStrToTime(s,Result, separator) Then
  1319. result:=defvalue;
  1320. end;
  1321. function StrToDateDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1322. begin
  1323. result := StrToDateDef(S,DefValue,#0);
  1324. end;
  1325. function StrToTimeDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1326. begin
  1327. result := StrToTimeDef(S,DefValue,#0);
  1328. end;
  1329. function StrToDateTimeDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1330. begin
  1331. if not TryStrToDateTime(s,Result) Then
  1332. result:=defvalue;
  1333. end;
  1334. function StrToDateDef(const S: AnsiString; const Defvalue : TDateTime; separator : char): TDateTime;
  1335. begin
  1336. if not TryStrToDate(s,Result, separator) Then
  1337. result:=defvalue;
  1338. end;
  1339. function StrToTimeDef(const S: AnsiString; const Defvalue : TDateTime; separator : char): TDateTime;
  1340. begin
  1341. if not TryStrToTime(s,Result, separator) Then
  1342. result:=defvalue;
  1343. end;
  1344. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);inline;
  1345. begin
  1346. dati:= ComposeDateTime(dati, newtime);
  1347. end;
  1348. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime); inline;
  1349. var
  1350. tmp : TDateTime;
  1351. begin
  1352. tmp:=NewDate;
  1353. ReplaceTime(tmp,DateTime);
  1354. DateTime:=tmp;
  1355. end;
  1356. {$IFNDEF HAS_LOCALTIMEZONEOFFSET}
  1357. Function GetLocalTimeOffset : Integer;
  1358. begin
  1359. Result:=0;
  1360. end;
  1361. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean; out Offset: Integer): Boolean;
  1362. begin
  1363. Result:=False;
  1364. end;
  1365. {$ENDIF}
  1366. function GetLocalTimeOffset(const DateTime: TDateTime; const InputIsUTC: Boolean): Integer;
  1367. begin
  1368. if not GetLocalTimeOffset(DateTime, InputIsUTC, Result) then
  1369. Result:=GetLocalTimeOffset();
  1370. end;
  1371. { Conversion of UTC to local time and vice versa }
  1372. function UniversalTimeToLocal(UT: TDateTime): TDateTime;
  1373. begin
  1374. Result:=UniversalTimeToLocal(UT,-GetLocalTimeOffset(UT, True));
  1375. end;
  1376. function UniversalTimeToLocal(UT: TDateTime; TZOffset : Integer): TDateTime;
  1377. begin
  1378. if (TZOffset > 0) then
  1379. Result := UT + EncodeTime(TZOffset div 60, TZOffset mod 60, 0, 0)
  1380. else if (TZOffset < 0) then
  1381. Result := UT - EncodeTime(Abs(TZOffset) div 60, Abs(TZOffset) mod 60, 0, 0)
  1382. else
  1383. Result := UT;
  1384. end;
  1385. Function LocalTimeToUniversal(LT: TDateTime): TDateTime;
  1386. begin
  1387. Result:=LocalTimeToUniversal(LT,-GetLocalTimeOffset(LT, False));
  1388. end;
  1389. Function LocalTimeToUniversal(LT: TDateTime;TZOffset: Integer): TDateTime;
  1390. begin
  1391. if (TZOffset > 0) then
  1392. Result := LT - EncodeTime(TZOffset div 60, TZOffset mod 60, 0, 0)
  1393. else if (TZOffset < 0) then
  1394. Result := LT + EncodeTime(Abs(TZOffset) div 60, Abs(TZOffset) mod 60, 0, 0)
  1395. else
  1396. Result := LT;
  1397. end;