dati.inc 45 KB

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