dati.inc 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511
  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. {$if defined(win32) or defined(win64)}
  796. isEnable_E_Format : Boolean;
  797. isEnable_G_Format : Boolean;
  798. eastasiainited : boolean;
  799. procedure InitEastAsia;
  800. var ALCID : LCID;
  801. PriLangID , SubLangID : Word;
  802. begin
  803. ALCID := GetThreadLocale;
  804. PriLangID := ALCID and $3FF;
  805. if (PriLangID>0) then
  806. SubLangID := (ALCID and $FFFF) shr 10
  807. else
  808. begin
  809. PriLangID := SysLocale.PriLangID;
  810. SubLangID := SysLocale.SubLangID;
  811. end;
  812. isEnable_E_Format := (PriLangID = LANG_JAPANESE)
  813. or
  814. (PriLangID = LANG_KOREAN)
  815. or
  816. ((PriLangID = LANG_CHINESE)
  817. and
  818. (SubLangID = SUBLANG_CHINESE_TRADITIONAL)
  819. );
  820. isEnable_G_Format := (PriLangID = LANG_JAPANESE)
  821. or
  822. ((PriLangID = LANG_CHINESE)
  823. and
  824. (SubLangID = SUBLANG_CHINESE_TRADITIONAL)
  825. );
  826. eastasiainited :=true;
  827. end;
  828. {$endif win32 or win64}
  829. procedure StoreStr(Str: PChar; Len: Integer);
  830. begin
  831. if ResultLen + Len < SizeOf(ResultBuffer) then
  832. begin
  833. StrMove(ResultCurrent, Str, Len);
  834. ResultCurrent := ResultCurrent + Len;
  835. ResultLen := ResultLen + Len;
  836. end;
  837. end;
  838. procedure StoreString(const Str: string);
  839. var Len: integer;
  840. begin
  841. Len := Length(Str);
  842. if ResultLen + Len < SizeOf(ResultBuffer) then
  843. begin
  844. StrMove(ResultCurrent, pchar(Str), Len);
  845. ResultCurrent := ResultCurrent + Len;
  846. ResultLen := ResultLen + Len;
  847. end;
  848. end;
  849. procedure StoreInt(Value, Digits: Integer);
  850. var
  851. S: string[16];
  852. Len: integer;
  853. begin
  854. System.Str(Value:Digits, S);
  855. for Len := 1 to Length(S) do
  856. begin
  857. if S[Len] = ' ' then
  858. S[Len] := '0'
  859. else
  860. Break;
  861. end;
  862. StoreStr(pchar(@S[1]), Length(S));
  863. end ;
  864. var
  865. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  866. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  867. var
  868. Token, lastformattoken, prevlasttoken: char;
  869. FormatCurrent: pchar;
  870. FormatEnd: pchar;
  871. Count: integer;
  872. Clock12: boolean;
  873. P: pchar;
  874. tmp: integer;
  875. isInterval: Boolean;
  876. begin
  877. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  878. Exit;
  879. FormatCurrent := PChar(FormatStr);
  880. FormatEnd := FormatCurrent + Length(FormatStr);
  881. Clock12 := false;
  882. isInterval := false;
  883. P := FormatCurrent;
  884. // look for unquoted 12-hour clock token
  885. while P < FormatEnd do
  886. begin
  887. Token := P^;
  888. case Token of
  889. '''', '"':
  890. begin
  891. Inc(P);
  892. while (P < FormatEnd) and (P^ <> Token) do
  893. Inc(P);
  894. end;
  895. 'A', 'a':
  896. begin
  897. if (StrLIComp(P, 'A/P', 3) = 0) or
  898. (StrLIComp(P, 'AMPM', 4) = 0) or
  899. (StrLIComp(P, 'AM/PM', 5) = 0) then
  900. begin
  901. Clock12 := true;
  902. break;
  903. end;
  904. end;
  905. end; // case
  906. Inc(P);
  907. end ;
  908. token := #255;
  909. lastformattoken := ' ';
  910. prevlasttoken := 'H';
  911. while FormatCurrent < FormatEnd do
  912. begin
  913. Token := UpCase(FormatCurrent^);
  914. Count := 1;
  915. P := FormatCurrent + 1;
  916. case Token of
  917. '''', '"':
  918. begin
  919. while (P < FormatEnd) and (p^ <> Token) do
  920. Inc(P);
  921. Inc(P);
  922. Count := P - FormatCurrent;
  923. StoreStr(FormatCurrent + 1, Count - 2);
  924. end ;
  925. 'A':
  926. begin
  927. if StrLIComp(FormatCurrent, 'AMPM', 4) = 0 then
  928. begin
  929. Count := 4;
  930. if Hour < 12 then
  931. StoreString(FormatSettings.TimeAMString)
  932. else
  933. StoreString(FormatSettings.TimePMString);
  934. end
  935. else if StrLIComp(FormatCurrent, 'AM/PM', 5) = 0 then
  936. begin
  937. Count := 5;
  938. if Hour < 12 then StoreStr(FormatCurrent, 2)
  939. else StoreStr(FormatCurrent+3, 2);
  940. end
  941. else if StrLIComp(FormatCurrent, 'A/P', 3) = 0 then
  942. begin
  943. Count := 3;
  944. if Hour < 12 then StoreStr(FormatCurrent, 1)
  945. else StoreStr(FormatCurrent+2, 1);
  946. end
  947. else
  948. raise EConvertError.Create('Illegal character in format string');
  949. end ;
  950. '/': StoreStr(@FormatSettings.DateSeparator, 1);
  951. ':': StoreStr(@FormatSettings.TimeSeparator, 1);
  952. '[': if (fdoInterval in Options) then isInterval := true else StoreStr(FormatCurrent, 1);
  953. ']': if (fdoInterval in Options) then isInterval := false else StoreStr(FormatCurrent, 1);
  954. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' {$IFDEF MSWindows}, 'G', 'E'{$ENDIF MSWindows} :
  955. begin
  956. while (P < FormatEnd) and (UpCase(P^) = Token) do
  957. Inc(P);
  958. Count := P - FormatCurrent;
  959. case Token of
  960. ' ': StoreStr(FormatCurrent, Count);
  961. 'Y': begin
  962. if Count > 2 then
  963. StoreInt(Year, 4)
  964. else
  965. StoreInt(Year mod 100, 2);
  966. end;
  967. 'M': begin
  968. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  969. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  970. else
  971. if (lastformattoken = 'H') or TimeFlag then
  972. begin
  973. if Count = 1 then
  974. StoreInt(Minute, 0)
  975. else
  976. StoreInt(Minute, 2);
  977. end
  978. else
  979. begin
  980. case Count of
  981. 1: StoreInt(Month, 0);
  982. 2: StoreInt(Month, 2);
  983. 3: StoreString(FormatSettings.ShortMonthNames[Month]);
  984. else
  985. StoreString(FormatSettings.LongMonthNames[Month]);
  986. end;
  987. end;
  988. end;
  989. 'D': begin
  990. case Count of
  991. 1: StoreInt(Day, 0);
  992. 2: StoreInt(Day, 2);
  993. 3: StoreString(FormatSettings.ShortDayNames[DayOfWeek]);
  994. 4: StoreString(FormatSettings.LongDayNames[DayOfWeek]);
  995. 5: StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  996. else
  997. StoreFormat(FormatSettings.LongDateFormat, Nesting+1, False);
  998. end ;
  999. end ;
  1000. 'H':
  1001. if isInterval then
  1002. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  1003. else
  1004. if Clock12 then
  1005. begin
  1006. tmp := hour mod 12;
  1007. if tmp=0 then tmp:=12;
  1008. if Count = 1 then
  1009. StoreInt(tmp, 0)
  1010. else
  1011. StoreInt(tmp, 2);
  1012. end
  1013. else begin
  1014. if Count = 1 then
  1015. StoreInt(Hour, 0)
  1016. else
  1017. StoreInt(Hour, 2);
  1018. end;
  1019. 'N': if isInterval then
  1020. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  1021. else
  1022. if Count = 1 then
  1023. StoreInt(Minute, 0)
  1024. else
  1025. StoreInt(Minute, 2);
  1026. 'S': if isInterval then
  1027. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  1028. else
  1029. if Count = 1 then
  1030. StoreInt(Second, 0)
  1031. else
  1032. StoreInt(Second, 2);
  1033. 'Z': if Count = 1 then
  1034. StoreInt(MilliSecond, 0)
  1035. else
  1036. StoreInt(MilliSecond, 3);
  1037. 'T': if Count = 1 then
  1038. StoreFormat(FormatSettings.ShortTimeFormat, Nesting+1, True)
  1039. else
  1040. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1041. 'C': begin
  1042. StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  1043. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  1044. begin
  1045. StoreString(' ');
  1046. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1047. end;
  1048. end;
  1049. 'F': begin
  1050. StoreFormat(FormatSettings.ShortDateFormat, Nesting+1, False);
  1051. StoreString(' ');
  1052. StoreFormat(FormatSettings.LongTimeFormat, Nesting+1, True);
  1053. end;
  1054. {$if defined(win32) or defined(win64)}
  1055. 'E':
  1056. begin
  1057. if not Eastasiainited then InitEastAsia;
  1058. if Not(isEnable_E_Format) then StoreStr(FormatCurrent, 1)
  1059. else
  1060. begin
  1061. while (P < FormatEnd) and (UpCase(P^) = Token) do
  1062. P := P + 1;
  1063. Count := P - FormatCurrent;
  1064. StoreString(ConvertEraYearString(Count,Year,Month,Day));
  1065. end;
  1066. prevlasttoken := lastformattoken;
  1067. lastformattoken:=token;
  1068. end;
  1069. 'G':
  1070. begin
  1071. if not Eastasiainited then InitEastAsia;
  1072. if Not(isEnable_G_Format) then StoreStr(FormatCurrent, 1)
  1073. else
  1074. begin
  1075. while (P < FormatEnd) and (UpCase(P^) = Token) do
  1076. P := P + 1;
  1077. Count := P - FormatCurrent;
  1078. StoreString(ConvertEraString(Count,Year,Month,Day));
  1079. end;
  1080. prevlasttoken := lastformattoken;
  1081. lastformattoken:=token;
  1082. end;
  1083. {$endif win32 or win64}
  1084. end;
  1085. prevlasttoken := lastformattoken;
  1086. lastformattoken := token;
  1087. end;
  1088. else
  1089. StoreStr(@Token, 1);
  1090. end ;
  1091. Inc(FormatCurrent, Count);
  1092. end;
  1093. end;
  1094. begin
  1095. {$if defined(win32) or defined(win64)}
  1096. eastasiainited:=false;
  1097. {$endif win32 or win64}
  1098. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  1099. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  1100. ResultLen := 0;
  1101. ResultCurrent := @ResultBuffer[0];
  1102. if FormatStr <> '' then
  1103. StoreFormat(FormatStr, 0, False)
  1104. else
  1105. StoreFormat('C', 0, False);
  1106. ResultBuffer[ResultLen] := #0;
  1107. result := StrPas(@ResultBuffer[0]);
  1108. end ;
  1109. Function DateTimeToFileDate(DateTime : TDateTime) : Longint;
  1110. Var YY,MM,DD,H,m,s,msec : Word;
  1111. begin
  1112. Decodedate (DateTime,YY,MM,DD);
  1113. DecodeTime (DateTime,h,m,s,msec);
  1114. {$ifndef unix}
  1115. If (YY<1980) or (YY>2099) then
  1116. Result:=0
  1117. else
  1118. begin
  1119. Result:=(s shr 1) or (m shl 5) or (h shl 11);
  1120. Result:=Result or longint(DD shl 16 or (MM shl 21) or (word(YY-1980) shl 25));
  1121. end;
  1122. {$else unix}
  1123. Result:=LocalToEpoch(yy,mm,dd,h,m,s);
  1124. {$endif unix}
  1125. end;
  1126. function CurrentYear: Word;
  1127. var
  1128. SysTime: TSystemTime;
  1129. begin
  1130. GetLocalTime(SysTime);
  1131. Result := SysTime.Year;
  1132. end;
  1133. Function FileDateToDateTime (Filedate : Longint) : TDateTime;
  1134. {$ifndef unix}
  1135. Var Date,Time : Word;
  1136. begin
  1137. Date:=FileDate shr 16;
  1138. Time:=FileDate and $ffff;
  1139. Result:=ComposeDateTime(EncodeDate((Date shr 9) + 1980,(Date shr 5) and 15, Date and 31),
  1140. EncodeTime(Time shr 11, (Time shr 5) and 63, (Time and 31) shl 1,0));
  1141. end;
  1142. {$else unix}
  1143. var
  1144. y, mon, d, h, min, s: word;
  1145. begin
  1146. EpochToLocal(FileDate,y,mon,d,h,min,s);
  1147. Result:=ComposeDateTime(EncodeDate(y,mon,d),EncodeTime(h,min,s,0));
  1148. end;
  1149. {$endif unix}
  1150. function TryStrToDate(const S: ShortString; out Value: TDateTime): Boolean;
  1151. begin
  1152. result := TryStrToDate(S, Value, #0);
  1153. end;
  1154. function TryStrToDate(const S: ShortString; out Value: TDateTime;
  1155. const useformat : string; separator : char = #0): Boolean;
  1156. Var
  1157. Msg : Ansistring;
  1158. begin
  1159. // S[1] always exists for shortstring. Length 0 will trigger an error.
  1160. Value:=IntStrToDate(Msg,@S[1],Length(S),useformat,defaultformatsettings,separator);
  1161. Result:=(Msg='');
  1162. end;
  1163. function TryStrToDate(const S: AnsiString; out Value: TDateTime;
  1164. const useformat : string; separator : char = #0): Boolean;
  1165. Var
  1166. Msg : Ansistring;
  1167. begin
  1168. Result:=Length(S)<>0;
  1169. If Result then
  1170. begin
  1171. Value:=IntStrToDate(Msg,PChar(S),Length(S),useformat,DefaultFormatSettings,Separator);
  1172. Result:=(Msg='');
  1173. end;
  1174. end;
  1175. function TryStrToDate(const S: ShortString; out Value: TDateTime; separator : char): Boolean;
  1176. begin
  1177. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,Separator);
  1178. end;
  1179. function TryStrToDate(const S: AnsiString; out Value: TDateTime): Boolean;
  1180. begin
  1181. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,#0);
  1182. end;
  1183. function TryStrToDate(const S: AnsiString; out Value: TDateTime; separator : char): Boolean;
  1184. begin
  1185. Result:=TryStrToDate(S,Value,DefaultFormatSettings.ShortDateFormat,Separator);
  1186. end;
  1187. function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1188. Var
  1189. Msg : Ansistring;
  1190. begin
  1191. Result:=Length(S)<>0;
  1192. If Result then
  1193. begin
  1194. Value:=IntStrToDate(Msg,PChar(S),Length(S),FormatSettings.ShortDateFormat,FormatSettings,#0);
  1195. Result:=(Msg='');
  1196. end;
  1197. end;
  1198. function TryStrToTime(const S: ShortString; out Value: TDateTime; separator : char): Boolean;
  1199. Var
  1200. Msg : AnsiString;
  1201. begin
  1202. // S[1] always exists for shortstring. Length 0 will trigger an error.
  1203. Value:=IntStrToTime(Msg,@S[1],Length(S),DefaultFormatSettings,Separator);
  1204. result:=(Msg='');
  1205. end;
  1206. function TryStrToTime(const S: ShortString; out Value: TDateTime): Boolean;
  1207. begin
  1208. Result := TryStrToTime(S,Value,#0);
  1209. end;
  1210. function TryStrToTime(const S: AnsiString; out Value: TDateTime; separator : char): Boolean;
  1211. Var
  1212. Msg : AnsiString;
  1213. begin
  1214. Result:=Length(S)<>0;
  1215. If Result then
  1216. begin
  1217. Value:=IntStrToTime(Msg,PChar(S),Length(S),DefaultFormatSettings,Separator);
  1218. Result:=(Msg='');
  1219. end;
  1220. end;
  1221. function TryStrToTime(const S: AnsiString; out Value: TDateTime): Boolean;
  1222. begin
  1223. result := TryStrToTime(S,Value,#0);
  1224. end;
  1225. function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1226. Var msg : AnsiString;
  1227. begin
  1228. Result:=Length(S)<>0;
  1229. If Result then
  1230. begin
  1231. Value:=IntStrToTime(Msg,PChar(S),Length(S),FormatSettings,#0);
  1232. Result:=(Msg='');
  1233. end;
  1234. end;
  1235. function TryStrToDateTime(const S: ShortString; out Value: TDateTime): Boolean;
  1236. begin
  1237. result := TryStrToDateTime(S, Value, DefaultFormatSettings);
  1238. end;
  1239. function TryStrToDateTime(const S: AnsiString; out Value: TDateTime): Boolean;
  1240. begin
  1241. result := TryStrToDateTime(S, Value, DefaultFormatSettings);
  1242. end;
  1243. function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  1244. var
  1245. I: integer;
  1246. dtdate, dttime :TDateTime;
  1247. begin
  1248. result:=false;
  1249. I:=Pos(FormatSettings.TimeSeparator,S);
  1250. If (I>0) then
  1251. begin
  1252. While (I>0) and (S[I]<>' ') do
  1253. Dec(I);
  1254. If I>0 then
  1255. begin
  1256. if not TryStrToDate(Copy(S,1,I-1),dtdate,Formatsettings) then
  1257. exit;
  1258. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime,Formatsettings) then
  1259. exit;
  1260. Value:=ComposeDateTime(dtdate,dttime);
  1261. result:=true;
  1262. end
  1263. else
  1264. result:=TryStrToTime(s,Value,Formatsettings);
  1265. end
  1266. else
  1267. result:=TryStrToDate(s,Value,Formatsettings);
  1268. end;
  1269. function StrToDateDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1270. begin
  1271. result := StrToDateDef(S,DefValue,#0);
  1272. end;
  1273. function StrToTimeDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1274. begin
  1275. result := StrToTimeDef(S,DefValue,#0);
  1276. end;
  1277. function StrToDateTimeDef(const S: ShortString; const Defvalue : TDateTime): TDateTime;
  1278. begin
  1279. Result:=StrToDateTimeDef(S,DefValue,DefaultFormatSettings);
  1280. end;
  1281. function StrToDateTimeDef(const S: AnsiString; const Defvalue : TDateTime; const FormatSettings: TFormatSettings): TDateTime;
  1282. begin
  1283. if not TryStrToDateTime(s,Result,FormatSettings) Then
  1284. result:=defvalue;
  1285. end;
  1286. function StrToDateDef(const S: ShortString; const Defvalue : TDateTime; separator : char): TDateTime;
  1287. begin
  1288. if not TryStrToDate(s,Result, separator) Then
  1289. result:=defvalue;
  1290. end;
  1291. function StrToTimeDef(const S: ShortString; const Defvalue : TDateTime; separator : char): TDateTime;
  1292. begin
  1293. if not TryStrToTime(s,Result, separator) Then
  1294. result:=defvalue;
  1295. end;
  1296. function StrToDateDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1297. begin
  1298. result := StrToDateDef(S,DefValue,#0);
  1299. end;
  1300. function StrToTimeDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1301. begin
  1302. result := StrToTimeDef(S,DefValue,#0);
  1303. end;
  1304. function StrToDateTimeDef(const S: AnsiString; const Defvalue : TDateTime): TDateTime;
  1305. begin
  1306. if not TryStrToDateTime(s,Result) Then
  1307. result:=defvalue;
  1308. end;
  1309. function StrToDateDef(const S: AnsiString; const Defvalue : TDateTime; separator : char): TDateTime;
  1310. begin
  1311. if not TryStrToDate(s,Result, separator) Then
  1312. result:=defvalue;
  1313. end;
  1314. function StrToTimeDef(const S: AnsiString; const Defvalue : TDateTime; separator : char): TDateTime;
  1315. begin
  1316. if not TryStrToTime(s,Result, separator) Then
  1317. result:=defvalue;
  1318. end;
  1319. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);inline;
  1320. begin
  1321. dati:= ComposeDateTime(dati, newtime);
  1322. end;
  1323. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime); inline;
  1324. var
  1325. tmp : TDateTime;
  1326. begin
  1327. tmp:=NewDate;
  1328. ReplaceTime(tmp,DateTime);
  1329. DateTime:=tmp;
  1330. end;
  1331. {$IFNDEF HAS_LOCALTIMEZONEOFFSET}
  1332. Function GetLocalTimeOffset : Integer;
  1333. begin
  1334. Result:=0;
  1335. end;
  1336. {$ENDIF}