dati.inc 45 KB

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