2
0

dati.inc 48 KB

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