dati.inc 44 KB

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