sysutils.pas 102 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819
  1. {
  2. This file is part of the Pas2JS run time library.
  3. Copyright (c) 2017 by Mattias Gaertner
  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. unit SysUtils;
  11. {$mode objfpc}
  12. interface
  13. uses
  14. RTLConsts, js;
  15. procedure FreeAndNil(var Obj);
  16. type
  17. TProcedure = procedure;
  18. {*****************************************************************************
  19. Various types
  20. *****************************************************************************}
  21. type
  22. { TFloatRec }
  23. TFloatRec = Record
  24. Exponent: Integer;
  25. Negative: Boolean;
  26. Digits: Array Of Char;
  27. End;
  28. TEndian = (Little,Big);
  29. TFileName = String;
  30. TByteArray = array [0..32767] of Byte;
  31. TWordArray = array [0..16383] of Word;
  32. TBytes = Array of byte;
  33. TStringArray = array of string;
  34. TMonthNameArray = array [1..12] of string;
  35. TDayTable = array [1..12] of Word;
  36. TWeekNameArray = array [1..7] of string;
  37. TMonthNames = TMonthNameArray;
  38. TDayNames = array[0..6] of string;
  39. {*****************************************************************************
  40. Exception handling
  41. *****************************************************************************}
  42. { Exception }
  43. Exception = class(TObject)
  44. private
  45. fMessage: String;
  46. fHelpContext: Integer;
  47. public
  48. constructor Create(const Msg: String); reintroduce;
  49. constructor CreateFmt(const Msg: string; const Args: array of jsvalue);
  50. constructor CreateHelp(const Msg: String; AHelpContext: Integer);
  51. constructor CreateFmtHelp(const Msg: string; const Args: array of jsvalue; AHelpContext: Integer);
  52. function ToString: String; override;
  53. property HelpContext: Integer read fHelpContext write fHelpContext;
  54. property Message: String read fMessage write fMessage;
  55. end;
  56. ExceptClass = class of Exception;
  57. EExternal = class(Exception);
  58. { General math errors }
  59. EMathError = class(EExternal);
  60. EInvalidOp = class(EMathError);
  61. EZeroDivide = class(EMathError);
  62. EOverflow = class(EMathError);
  63. EUnderflow = class(EMathError);
  64. EAbort = class(Exception);
  65. EInvalidCast = class(Exception);
  66. EAssertionFailed = class(Exception);
  67. EObjectCheck = class(Exception);
  68. { String conversion errors }
  69. EConvertError = class(Exception);
  70. EFormatError = class(Exception);
  71. { integer math exceptions }
  72. EIntError = Class(EExternal);
  73. EDivByZero = Class(EIntError);
  74. ERangeError = Class(EIntError);
  75. EIntOverflow = Class(EIntError);
  76. { General math errors }
  77. { Run-time and I/O Errors }
  78. EInOutError = class(Exception)
  79. public
  80. ErrorCode : Integer;
  81. end;
  82. EHeapMemoryError = class(Exception);
  83. EHeapException = EHeapMemoryError;
  84. EExternalException = class(EExternal);
  85. EInvalidPointer = Class(EHeapMemoryError);
  86. EOutOfMemory = Class(EHeapMemoryError);
  87. { EVariantError }
  88. EVariantError = Class(Exception)
  89. ErrCode : longint;
  90. Constructor CreateCode(Code : Longint);
  91. end;
  92. EAccessViolation = Class(EExternal);
  93. EBusError = Class(EAccessViolation);
  94. EPrivilege = class(EExternal);
  95. EStackOverflow = class(EExternal);
  96. EControlC = class(EExternal);
  97. { String conversion errors }
  98. { Other errors }
  99. EAbstractError = Class(Exception);
  100. EPropReadOnly = class(Exception);
  101. EPropWriteOnly = class(Exception);
  102. EIntfCastError = class(Exception);
  103. EInvalidContainer = class(Exception);
  104. EInvalidInsert = class(Exception);
  105. EPackageError = class(Exception);
  106. EOSError = class(Exception)
  107. public
  108. ErrorCode: Longint;
  109. end;
  110. ESafecallException = class(Exception);
  111. ENoThreadSupport = Class(Exception);
  112. ENoWideStringSupport = Class(Exception);
  113. ENotImplemented = class(Exception);
  114. EArgumentException = class(Exception);
  115. EArgumentOutOfRangeException = class(EArgumentException);
  116. EArgumentNilException = class(EArgumentException);
  117. EPathTooLongException = class(Exception);
  118. ENotSupportedException = class(Exception);
  119. EDirectoryNotFoundException = class(Exception);
  120. EFileNotFoundException = class(Exception);
  121. EPathNotFoundException = class(Exception);
  122. ENoConstructException = class(Exception);
  123. //function GetTickCount: Integer;
  124. {*****************************************************************************
  125. String function
  126. *****************************************************************************}
  127. Const
  128. EmptyStr = '';
  129. EmptyWideStr = ''; // No difference here.
  130. HexDisplayPrefix: string = '$';
  131. LeadBytes = [] unimplemented;
  132. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  133. function LeftStr(const S: string; Count: Integer): String; assembler;
  134. function RightStr(const S: string; Count: Integer): String; assembler;
  135. function Trim(const S: String): String; assembler;
  136. function TrimLeft(const S: String): String; assembler;
  137. function TrimRight(const S: String): String; assembler;
  138. function UpperCase(const s: String): String; assembler; overload;
  139. function LowerCase(const s: String): String; assembler; overload;
  140. function CompareStr(const s1, s2: String): Integer; assembler;
  141. function SameStr(const s1, s2: String): Boolean; assembler;
  142. function CompareText(const s1, s2: String): Integer; assembler;
  143. function SameText(const s1, s2: String): Boolean; assembler;
  144. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  145. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  146. function AnsiCompareStr(const s1, s2: String): Integer;
  147. procedure AppendStr(var Dest: String; const S: string);
  148. function Format(const Fmt: String; const Args: array of JSValue): String;
  149. // JavaScript built-in functions
  150. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler; overload;
  151. function NormalizeStr(const S: String; const Norm: String = 'NFC'): String; assembler; overload; // not in IE
  152. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  153. Type
  154. TStringReplaceFlag = (rfReplaceAll, rfIgnoreCase);
  155. TReplaceFlag = TStringReplaceFlag;
  156. TStringReplaceFlags = set of TStringReplaceFlag;
  157. TReplaceFlags = TStringReplaceFlags;
  158. function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  159. function QuoteString(aOriginal : String; AQuote : Char) : String;
  160. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  161. function AdjustLineBreaks(const S: string): string;
  162. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  163. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  164. function WrapText(const Line: string; MaxCol: Integer): string;
  165. { *****************************************************************************
  166. Integer conversions
  167. *****************************************************************************}
  168. function IntToStr(const Value: Integer): string;
  169. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  170. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  171. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  172. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  173. Function StrToInt(const S : String) : Integer;
  174. Function StrToNativeInt(const S : String) : NativeInt;
  175. // For compatibility
  176. Function StrToInt64(const S : String) : NativeLargeInt;
  177. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  178. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  179. Function StrToQWord(const S : String) : NativeLargeUInt;
  180. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  181. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  182. Function StrToUInt64(const S : String) : NativeLargeUInt;
  183. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  184. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  185. Function StrToDWord(const S : String) : DWord;
  186. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  187. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  188. function IntToHex(Value: NativeInt; Digits: integer): string;
  189. { *****************************************************************************
  190. Float conversions
  191. *****************************************************************************}
  192. const
  193. MaxCurrency {: Currency } = 922337203685477.0000;
  194. MinCurrency {: Currency } = -922337203685477.0000;
  195. Type
  196. TFloatFormat = (ffFixed,ffGeneral,ffExponent,ffNumber);
  197. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  198. Function FloatToStr(Value: Double): String;
  199. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  200. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  201. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  202. Function StrToFloat(const S : String) : Double;
  203. Function FormatFloat (Fmt : String; aValue : Double) : String;
  204. { *****************************************************************************
  205. Boolean conversions
  206. *****************************************************************************}
  207. Var
  208. TrueBoolStrs, FalseBoolStrs : Array of String;
  209. function StrToBool(const S: String): Boolean;
  210. function BoolToStr(B: Boolean; UseBoolStrs:Boolean=False): string;
  211. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  212. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  213. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  214. {*****************************************************************************
  215. OS/Environment
  216. *****************************************************************************}
  217. Const
  218. ConfigExtension : String = '.cfg';
  219. SysConfigDir : String = '';
  220. type
  221. TOnGetEnvironmentVariable = function(Const EnvVar: String): String;
  222. TOnGetEnvironmentString = function(Index: Integer): String;
  223. TOnGetEnvironmentVariableCount = function: Integer;
  224. var
  225. OnGetEnvironmentVariable: TOnGetEnvironmentVariable;
  226. OnGetEnvironmentString: TOnGetEnvironmentString;
  227. OnGetEnvironmentVariableCount: TOnGetEnvironmentVariableCount;
  228. function GetEnvironmentVariable(Const EnvVar: String): String;
  229. function GetEnvironmentVariableCount: Integer;
  230. function GetEnvironmentString(Index: Integer): String;
  231. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  232. Procedure Abort;
  233. {*****************************************************************************
  234. Events
  235. *****************************************************************************}
  236. Type
  237. TEventType = (etCustom,etInfo,etWarning,etError,etDebug);
  238. TEventTypes = Set of TEventType;
  239. {*****************************************************************************
  240. Date and time
  241. *****************************************************************************}
  242. Type
  243. TDateTime = double;
  244. TTime = TDateTime;
  245. TDate = TDateTime;
  246. TSystemTime = record
  247. Year, Month, Day, DayOfWeek: word;
  248. Hour, Minute, Second, MilliSecond: word;
  249. end ;
  250. TTimeStamp = record
  251. Time: longint; { Number of milliseconds since midnight }
  252. Date: longint; { One plus number of days since 1/1/0001 }
  253. end ;
  254. Var
  255. TimeSeparator : char = ':';
  256. DateSeparator : char = '-';
  257. ShortDateFormat : string = 'yyyy-mm-dd';
  258. LongDateFormat : string = 'ddd, yyyy-mm-dd';
  259. ShortTimeFormat : string = 'hh:nn';
  260. LongTimeFormat : string = 'hh:nn:ss';
  261. DecimalSeparator : string = '.';
  262. ThousandSeparator : string;
  263. TimeAMString : string = 'AM';
  264. TimePMString : string = 'PM';
  265. const
  266. HoursPerDay = 24;
  267. MinsPerHour = 60;
  268. SecsPerMin = 60;
  269. MSecsPerSec = 1000;
  270. MinsPerDay = HoursPerDay * MinsPerHour;
  271. SecsPerDay = MinsPerDay * SecsPerMin;
  272. MSecsPerDay = SecsPerDay * MSecsPerSec;
  273. MaxDateTime: TDateTime = 2958465.99999999;
  274. MinDateTime: TDateTime = -693593.99999999;
  275. JulianEpoch = TDateTime(-2415018.5);
  276. UnixEpoch = JulianEpoch + TDateTime(2440587.5);
  277. DateDelta = 693594; // Days between 1/1/0001 and 12/31/1899
  278. UnixDateDelta = 25569;
  279. { True=Leapyear }
  280. Var
  281. MonthDays : array [Boolean] of TDayTable =
  282. ((31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31),
  283. (31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31));
  284. ShortMonthNames : TMonthNames = (
  285. 'Jan',
  286. 'Feb',
  287. 'Mar',
  288. 'Apr',
  289. 'May',
  290. 'Jun',
  291. 'Jul',
  292. 'Aug',
  293. 'Sep',
  294. 'Oct',
  295. 'Nov',
  296. 'Dec');
  297. LongMonthNames : TMonthNames = (
  298. 'January',
  299. 'February',
  300. 'March',
  301. 'April',
  302. 'May',
  303. 'June',
  304. 'July',
  305. 'August',
  306. 'September',
  307. 'October',
  308. 'November',
  309. 'December');
  310. ShortDayNames : TDayNames = (
  311. 'Sun',
  312. 'Mon',
  313. 'Tue',
  314. 'Wed',
  315. 'Thu',
  316. 'Fri',
  317. 'Sat');
  318. LongDayNames : TDayNames = (
  319. 'Sunday',
  320. 'Monday',
  321. 'Tuesday',
  322. 'Wednesday',
  323. 'Thursday',
  324. 'Friday',
  325. 'Saturday');
  326. type
  327. // Stub, for easier porting of FPC/Delphi code.
  328. // Reading/Writing the properties will actually set the global variables
  329. { TFormatSettings }
  330. TFormatSettings = class(TObject)
  331. private
  332. function GetDateSeparator: char;
  333. function GetDecimalSeparator: string;
  334. function GetLongDateFormat: string;
  335. function GetLongDayNames: TDayNames;
  336. function GetLongMonthNames: TMonthNames;
  337. function GetLongTimeFormat: string;
  338. function GetShortDateFormat: string;
  339. function GetShortDayNames: TDayNames;
  340. function GetShortMonthNames: TMonthNames;
  341. function GetShortTimeFormat: string;
  342. function GetThousandSeparator: string;
  343. function GetTimeAMString: string;
  344. function GetTimePMString: string;
  345. function GetTimeSeparator: char;
  346. procedure SetDateSeparator(const Value: char);
  347. procedure SetDecimalSeparator(const Value: string);
  348. procedure SetLongDateFormat(const Value: string);
  349. procedure SetLongDayNames(AValue: TDayNames);
  350. procedure SetLongMonthNames(AValue: TMonthNames);
  351. procedure SetLongTimeFormat(const Value: string);
  352. procedure SetShortDateFormat(const Value: string);
  353. procedure SetShortDayNames(AValue: TDayNames);
  354. procedure SetShortMonthNames(AValue: TMonthNames);
  355. procedure SetShortTimeFormat(const Value: string);
  356. procedure SetThousandSeparator(const Value: string);
  357. procedure SetTimeAMString(const Value: string);
  358. procedure SetTimePMString(const Value: string);
  359. procedure SetTimeSeparator(const Value: char);
  360. public
  361. Property ShortMonthNames : TMonthNames Read GetShortMonthNames Write SetShortMonthNames;
  362. Property LongMonthNames : TMonthNames Read GetLongMonthNames Write SetLongMonthNames;
  363. Property ShortDayNames : TDayNames Read GetShortDayNames Write SetShortDayNames;
  364. Property LongDayNames : TDayNames Read GetLongDayNames Write SetLongDayNames;
  365. property TimeSeparator : char read GetTimeSeparator write SetTimeSeparator;
  366. property DateSeparator : char read GetDateSeparator write SetDateSeparator;
  367. property ShortDateFormat : string read GetShortDateFormat write SetShortDateFormat;
  368. property LongDateFormat : string read GetLongDateFormat write SetLongDateFormat;
  369. property ShortTimeFormat : string read GetShortTimeFormat write SetShortTimeFormat;
  370. property LongTimeFormat : string read GetLongTimeFormat write SetLongTimeFormat;
  371. property DecimalSeparator : string read GetDecimalSeparator write SetDecimalSeparator;
  372. property ThousandSeparator : string read GetThousandSeparator write SetThousandSeparator;
  373. property TimeAMString : string read GetTimeAMString write SetTimeAMString;
  374. property TimePMString : string read GetTimePMString write SetTimePMString;
  375. end;
  376. Var
  377. FormatSettings: TFormatSettings;
  378. TwoDigitYearCenturyWindow : word = 50;
  379. { Threshold to be subtracted from year before age-detection.}
  380. function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  381. function JSDateToDateTime(aDate : TJSDate) : TDateTime;
  382. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  383. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  384. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  385. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  386. function TryEncodeDate(Year, Month, Day: Word; out Date: TDateTime): Boolean;
  387. function TryEncodeTime(Hour, Min, Sec, MSec: Word; out Time: TDateTime): Boolean;
  388. function EncodeDate(Year, Month, Day :word): TDateTime;
  389. function EncodeTime(Hour, Minute, Second, MilliSecond:word): TDateTime;
  390. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  391. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  392. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  393. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  394. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  395. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  396. function DayOfWeek(DateTime: TDateTime): integer;
  397. function Date: TDateTime;
  398. function Time: TDateTime;
  399. function Now: TDateTime;
  400. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  401. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  402. function IsLeapYear(Year: Word): boolean;
  403. function DateToStr(Date: TDateTime): string;
  404. // function DateToStr(Date: TDateTime; const FormatSettings: TFormatSettings): string;
  405. function TimeToStr(Time: TDateTime): string;
  406. // function TimeToStr(Time: TDateTime; const FormatSettings: TFormatSettings): string;
  407. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  408. // function DateTimeToStr(DateTime: TDateTime; const FormatSettings: TFormatSettings; ForceTimeIfZero : Boolean = False): string;
  409. function StrToDate(const S: String): TDateTime;
  410. function StrToDate(const S: String; separator : char): TDateTime;
  411. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  412. //function StrToDate(const S: string; FormatSettings : TFormatSettings): TDateTime;
  413. function StrToTime(const S: String): TDateTime;
  414. function StrToTime(const S: String; separator : char): TDateTime;
  415. // function StrToTime(const S: string; FormatSettings : TFormatSettings): TDateTime;
  416. function StrToDateTime(const S: String): TDateTime;
  417. //function StrToDateTime(const s: ShortString; const FormatSettings : TFormatSettings): TDateTime;
  418. function FormatDateTime(const FormatStr: string; const DateTime: TDateTime): string;
  419. // function FormatDateTime(const FormatStr: string; DateTime: TDateTime; const FormatSettings: TFormatSettings; Options : TFormatDateTimeOptions = []): string;
  420. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  421. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  422. function TryStrToDate(const S: String; out Value: TDateTime; const useformat : string; separator : char): Boolean;
  423. // function TryStrToDate(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  424. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  425. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  426. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  427. // function TryStrToTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  428. // function TryStrToDateTime(const S: string; out Value: TDateTime; const FormatSettings: TFormatSettings): Boolean;
  429. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  430. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  431. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  432. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  433. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  434. function CurrentYear:Word;
  435. procedure ReplaceTime(var dati: TDateTime; NewTime : TDateTime);
  436. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  437. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  438. {*****************************************************************************
  439. File Paths
  440. *****************************************************************************}
  441. type
  442. PathStr = String;
  443. //function ExtractFilePath(const FileName: PathStr): PathStr;
  444. {*****************************************************************************
  445. Interfaces
  446. *****************************************************************************}
  447. const
  448. GUID_NULL: TGuid = '{00000000-0000-0000-0000-000000000000}';
  449. function Supports(const Instance: IInterface; const AClass: TClass; out Obj): Boolean; overload;
  450. function Supports(const Instance: IInterface; const IID: TGuid; out Intf): Boolean; overload;
  451. function Supports(const Instance: TObject; const IID: TGuid; out Intf): Boolean; overload;
  452. function Supports(const Instance: TObject; const IID: TGuidString; out Intf): Boolean; overload;
  453. function Supports(const Instance: IInterface; const AClass: TClass): Boolean; overload;
  454. function Supports(const Instance: IInterface; const IID: TGuid): Boolean; overload;
  455. function Supports(const Instance: TObject; const IID: TGuid): Boolean; overload;
  456. function Supports(const Instance: TObject; const IID: TGuidString): Boolean; overload;
  457. function Supports(const AClass: TClass; const IID: TGuid): Boolean; overload;
  458. function Supports(const AClass: TClass; const IID: TGuidString): Boolean; overload;
  459. function TryStringToGUID(const s: string; out Guid: TGuid): Boolean;
  460. function StringToGUID(const S: string): TGuid;
  461. function GUIDToString(const guid: TGuid): string;
  462. function IsEqualGUID(const guid1, guid2: TGuid): Boolean;
  463. function GuidCase(const guid: TGuid; const List: array of TGuid): Integer;
  464. implementation
  465. procedure ShowException(ExceptObject: TObject; ExceptAddr: Pointer);
  466. Var
  467. S : String;
  468. begin
  469. S:='Application raised an exception '+ExceptObject.ClassName;
  470. if ExceptObject is Exception then
  471. S:=S+' : '+Exception(ExceptObject).Message;
  472. {$IFDEF BROWSER}
  473. asm
  474. window.alert(S);
  475. end;
  476. {$ENDIF}
  477. {$IFDEF NODEJS}
  478. Writeln(S);
  479. {$ENDIF}
  480. if ExceptAddr=nil then;
  481. end;
  482. Const
  483. SAbortError = 'Operation aborted';
  484. procedure Abort;
  485. begin
  486. Raise EAbort.Create(SAbortError);
  487. end;
  488. Function CharInSet(Ch: Char;Const CSet : array of char) : Boolean;
  489. Var
  490. I : integer;
  491. begin
  492. Result:=False;
  493. I:=Length(CSet)-1;
  494. While (Not Result) and (I>=0) do
  495. begin
  496. Result:=(Ch=CSet[i]);
  497. Dec(I);
  498. end;
  499. end;
  500. function LeftStr(const S: string; Count: Integer): String; assembler;
  501. asm
  502. return (Count>0) ? S.substr(0,Count) : "";
  503. end;
  504. function RightStr(const S: string; Count: Integer): String; assembler;
  505. asm
  506. var l = S.length;
  507. return (Count<1) ? "" : ( Count>=l ? S : S.substr(l-Count));
  508. end;
  509. function Trim(const S: String): String; assembler;
  510. asm
  511. return S.trim();
  512. end;
  513. function TrimLeft(const S: String): String; assembler;
  514. asm
  515. return S.replace(/^[\s\uFEFF\xA0\x00-\x1f]+/,'');
  516. end;
  517. function TrimRight(const S: String): String; assembler;
  518. asm
  519. return S.replace(/[\s\uFEFF\xA0\x00-\x1f]+$/,'');
  520. end;
  521. function IntToStr(const Value: Integer): string;
  522. begin
  523. Result:=str(Value);
  524. end;
  525. Function FloatToDecimal(Value : double; Precision, Decimals : integer) : TFloatRec;
  526. Const
  527. Rounds = '234567890';
  528. var
  529. Buffer: String; //Though str func returns only 25 chars, this might change in the future
  530. InfNan: string;
  531. Error, N, L, Start, C: Integer;
  532. GotNonZeroBeforeDot, BeforeDot : boolean;
  533. begin
  534. if Value=0 then ;
  535. SetLength(Result.Digits,19);
  536. asm
  537. Buffer=Value.toPrecision(21); // Double precision
  538. end;
  539. N := 1;
  540. L := Length(Buffer);
  541. while Buffer[N]=' ' do
  542. Inc(N);
  543. Result.Negative := (Buffer[N] = '-');
  544. if Result.Negative then
  545. Inc(N)
  546. else if (Buffer[N] = '+') then
  547. inc(N);
  548. { special cases for Inf and Nan }
  549. if (L>=N+2) then
  550. begin
  551. InfNan:=copy(Buffer,N,3);
  552. if (InfNan='Inf') then
  553. begin
  554. Result.Digits[0]:=#0;
  555. Result.Exponent:=32767;
  556. exit
  557. end;
  558. if (InfNan='Nan') then
  559. begin
  560. Result.Digits[0]:=#0;
  561. Result.Exponent:=-32768;
  562. exit
  563. end;
  564. end;
  565. Start := N; //Start of digits
  566. Result.Exponent := 0; BeforeDot := true;
  567. GotNonZeroBeforeDot := false;
  568. while (L>=N) and (Buffer[N]<>'E') do
  569. begin
  570. if Buffer[N]='.' then
  571. BeforeDot := false
  572. else
  573. begin
  574. if BeforeDot then
  575. begin // Currently this is always 1 char
  576. Inc(Result.Exponent);
  577. Result.Digits[N-Start] := Buffer[N];
  578. if Buffer[N] <> '0' then
  579. GotNonZeroBeforeDot := true;
  580. end
  581. else
  582. Result.Digits[N-Start-1] := Buffer[N]
  583. end;
  584. Inc(N);
  585. end;
  586. Inc(N); // Pass through 'E'
  587. if N<=L then
  588. begin
  589. Val(Copy(Buffer, N, L-N+1), C, Error); // Get exponent after 'E'
  590. Inc(Result.Exponent, C);
  591. end;
  592. // Calculate number of digits we have from str
  593. if BeforeDot then
  594. N := N - Start - 1
  595. else
  596. N := N - Start - 2;
  597. L := Length(Result.Digits);
  598. if N<L then
  599. Result.Digits[N]:='0'; //Zero remaining space
  600. if Decimals + Result.Exponent < Precision Then //After this it is the same as in FloatToDecimal
  601. N := Decimals + Result.Exponent
  602. Else
  603. N := Precision;
  604. if N >= L Then
  605. N := L-1;
  606. if N = 0 Then
  607. begin
  608. if Result.Digits[0] >= '5' Then
  609. begin
  610. Result.Digits[0] := '1';
  611. Result.Digits[1] := #0;
  612. Inc(Result.Exponent);
  613. end
  614. Else
  615. Result.Digits[0] := #0;
  616. end //N=0
  617. Else if N > 0 Then
  618. begin
  619. if Result.Digits[N] >= '5' Then
  620. begin
  621. Repeat
  622. Result.Digits[N] := #0;
  623. Dec(N);
  624. // Writeln(N,': ',Result.Digits[N],', Rounding to : ',Rounds[StrToInt(Result.Digits[N])]);
  625. Result.Digits[N]:=Rounds[StrToInt(Result.Digits[N])];
  626. Until (N = 0) Or (Result.Digits[N] < ':');
  627. If Result.Digits[0] = ':' Then
  628. begin
  629. Result.Digits[0] := '1';
  630. Inc(Result.Exponent);
  631. end;
  632. end
  633. Else
  634. begin
  635. Result.Digits[N] := '0';
  636. While (N > -1) And (Result.Digits[N] = '0') Do
  637. begin
  638. Result.Digits[N] := #0;
  639. Dec(N);
  640. end;
  641. end;
  642. end //N>0
  643. Else
  644. Result.Digits[0] := #0;
  645. if (Result.Digits[0] = #0) and
  646. not GotNonZeroBeforeDot then
  647. begin
  648. Result.Exponent := 0;
  649. Result.Negative := False;
  650. end;
  651. end;
  652. function FloatToStr(Value: Double): String;
  653. begin
  654. Result:=FloatToStrF(Value,ffGeneral,15,0);
  655. end;
  656. Function TryStrToFloat(const S : String; Out res : Double) : Boolean;
  657. Var
  658. J : JSValue;
  659. N : String;
  660. begin
  661. N:=S;
  662. // Delocalize
  663. if (ThousandSeparator <>'') then
  664. N:=StringReplace(N,ThousandSeparator,'',[rfReplaceAll]);
  665. if (DecimalSeparator<>'.') then
  666. N:=StringReplace(N,DecimalSeparator,'.',[]);
  667. J:=parseFloat(N);
  668. Result:=Not jsIsNaN(J);
  669. if Result then
  670. Res:=Double(J);
  671. end;
  672. Function StrToFloatDef(const S : String; Const aDef : Double) : Double;
  673. begin
  674. if not TryStrToFloat(S,Result) then
  675. Result:=aDef;
  676. end;
  677. Function StrToFloat(const S : String) : Double;
  678. begin
  679. if not TryStrToFloat(S,Result) then
  680. Raise EConvertError.CreateFmt(SErrInvalidFloat,[S]);
  681. end;
  682. function FormatFloat(Fmt: String; aValue: Double): String;
  683. Type
  684. TPosArray = Array of Integer;
  685. const
  686. MaxPrecision = 18; // Extended precision
  687. var
  688. // Input in usable format
  689. E : Extended; // Value as extended.
  690. FV: TFloatRec; // Value as floatrec.
  691. Section : String; // Format can contain 3 sections, semicolon separated: Pos;Neg;Zero. This is the one to use.
  692. SectionLength : Integer; // Length of section.
  693. // Calculated based on section. Static during output
  694. ThousandSep: Boolean; // Thousands separator detected in format ?
  695. IsScientific: Boolean; // Use Scientific notation ? (E detected in format)
  696. DecimalPos: Integer; // Position of decimal point in pattern.
  697. FirstDigit: Integer; // First actual digit in input (# or 0), relative to decimal point
  698. LastDigit: Integer; // Last required (0) digit, relative to decimal point
  699. RequestedDigits: Integer; // Number of requested digits, # and 0 alike
  700. ExpSize : Integer; // Number of digits in exponent
  701. Available: Integer; // Available digits in FV.
  702. // These change during output loop
  703. Current: Integer; // Current digit in available digits
  704. PadZeroes: Integer; // Difference in requested digits before comma and exponent, needs to be padded with zeroes.
  705. DistToDecimal: Integer; // Place of current digit, relative to decimal point taking in account PadZeroes!
  706. Procedure InitVars;
  707. begin
  708. E:=aValue;
  709. Section:='';
  710. SectionLength:=0;
  711. ThousandSep:=false;
  712. IsScientific:=false;
  713. DecimalPos:=0;
  714. FirstDigit:=MaxInt;
  715. LastDigit:=0;
  716. RequestedDigits:=0;
  717. ExpSize:=0;
  718. Available:=-1;
  719. end;
  720. procedure ToResult(const AChar: Char);
  721. begin
  722. Result:=Result+AChar;
  723. end;
  724. procedure AddToResult(const AStr: String);
  725. begin
  726. Result:=Result+AStr;
  727. end;
  728. procedure WriteDigit(ADigit: Char);
  729. // Write a digit to result, prepend with decimalseparator or append with 1000 separator
  730. begin
  731. if ADigit=#0 then exit;
  732. // Writeln('WriteDigit: ',ADigit,', DistToDecimal: ',DistToDecimal);
  733. Dec(DistToDecimal);
  734. // -1 -> we've arrived behind the decimal
  735. if (DistToDecimal=-1) then
  736. begin
  737. AddToResult(DecimalSeparator);
  738. ToResult(ADigit);
  739. end
  740. else
  741. begin
  742. // We're still before the decimal.
  743. ToResult(ADigit);
  744. if ThousandSep and ((DistToDecimal mod 3)=0) and (DistToDecimal>1) then
  745. AddToResult(ThousandSeparator);
  746. end;
  747. end;
  748. Function GetDigit : Char;
  749. // Return next digit from available digits.
  750. // May return #0 if none available.
  751. // Will return '0' if applicable.
  752. begin
  753. // Writeln(' DistToDecimal <= LastDigit : ',DistToDecimal,' < ',LastDigit,' have digit: ',Current<=Available, '(',Current,')');
  754. Result:=#0;
  755. if (Current<=Available) then
  756. begin
  757. Result:=FV.Digits[Current];
  758. Inc(Current);
  759. end
  760. else if (DistToDecimal <= LastDigit) then
  761. Dec(DistToDecimal)
  762. else
  763. Result:='0';
  764. // Writeln('GetDigit ->: ',Result);
  765. end;
  766. procedure CopyDigit;
  767. // Copy a digit (#, 0) to the output with the correct value
  768. begin
  769. // Writeln('CopyDigit ');
  770. if (PadZeroes=0) then
  771. WriteDigit(GetDigit) // No shift needed, just copy what is available.
  772. else if (PadZeroes<0) then
  773. begin
  774. // We must prepend zeroes
  775. Inc(PadZeroes);
  776. if (DistToDecimal<=FirstDigit) then
  777. WriteDigit('0')
  778. else
  779. Dec(DistToDecimal);
  780. end
  781. else
  782. begin
  783. // We must append zeroes
  784. while PadZeroes > 0 do
  785. begin
  786. WriteDigit(GetDigit);
  787. Dec(PadZeroes);
  788. end;
  789. WriteDigit(GetDigit);
  790. end;
  791. end;
  792. Function GetSections(Var SP : TPosArray) : Integer;
  793. var
  794. FL : Integer;
  795. i : Integer;
  796. C,Q : Char;
  797. inQuote : Boolean;
  798. begin
  799. Result:=1;
  800. SP[1]:=-1;
  801. SP[2]:=-1;
  802. SP[3]:=-1;
  803. inQuote:=False;
  804. Q:=#0;
  805. I:=1;
  806. FL:=Length(Fmt);
  807. while (I<=FL) do
  808. begin
  809. C:=Fmt[I];
  810. case C of
  811. ';':
  812. begin
  813. if not InQuote then
  814. begin
  815. if Result>3 then
  816. Raise Exception.Create('Invalid float format');
  817. SP[Result]:=I+1;
  818. Inc(Result);
  819. end;
  820. end;
  821. '"','''':
  822. begin
  823. if InQuote then
  824. InQuote:=C<>Q
  825. else
  826. begin
  827. InQuote:=True;
  828. Q:=C;
  829. end;
  830. end;
  831. end;
  832. Inc(I);
  833. end;
  834. if SP[Result]=-1 then
  835. SP[Result]:=FL+1;
  836. end;
  837. Procedure AnalyzeFormat;
  838. var
  839. I,Len: Integer;
  840. Q,C: Char;
  841. InQuote : Boolean;
  842. begin
  843. Len:=Length(Section);
  844. I:=1;
  845. InQuote:=False;
  846. Q:=#0;
  847. while (I<=Len) do
  848. begin
  849. C:=Section[i];
  850. if C in ['"',''''] then
  851. begin
  852. if InQuote then
  853. InQuote:=C<>Q
  854. else
  855. begin
  856. InQuote:=True;
  857. Q:=C;
  858. end;
  859. end
  860. else if not InQuote then
  861. case C of
  862. '.':
  863. if (DecimalPos=0) then
  864. DecimalPos:=RequestedDigits+1;
  865. ',':
  866. ThousandSep:=ThousandSeparator<>#0;
  867. 'e', 'E':
  868. begin
  869. Inc(I);
  870. if (I<Len) then
  871. begin
  872. C:=Section[i];
  873. IsScientific:=C in ['-','+'];
  874. if IsScientific then
  875. while (I<Len) and (Section[i+1]='0') do
  876. begin
  877. Inc(ExpSize);
  878. Inc(I);
  879. end;
  880. if ExpSize>4 then
  881. ExpSize:=4;
  882. end;
  883. end;
  884. '#':
  885. Inc(RequestedDigits);
  886. '0':
  887. begin
  888. if RequestedDigits<FirstDigit then
  889. FirstDigit:=RequestedDigits+1;
  890. Inc(RequestedDigits);
  891. LastDigit:=RequestedDigits+1;
  892. end;
  893. end;
  894. Inc(I);
  895. end;
  896. if DecimalPos=0 then
  897. DecimalPos:=RequestedDigits+1;
  898. // Writeln('LastDigit: ',DecimalPos,'-',LastDigit);
  899. LastDigit:=DecimalPos-LastDigit;
  900. if LastDigit>0 then
  901. LastDigit:=0;
  902. // Writeln('FirstDigit: ',DecimalPos,'-',FirstDigit);
  903. FirstDigit:=DecimalPos-FirstDigit;
  904. if FirstDigit<0 then
  905. FirstDigit:=0;
  906. end;
  907. Function ValueOutSideScope : Boolean;
  908. begin
  909. With FV do
  910. Result:=((Exponent >= 18) and (not IsScientific)) or (Exponent = $7FF) or (Exponent = $800)
  911. end;
  912. Procedure CalcRunVars;
  913. Var
  914. D,P: Integer;
  915. begin
  916. if IsScientific then
  917. begin
  918. P:=RequestedDigits;
  919. D:=9999;
  920. end
  921. else
  922. begin
  923. P:=MaxPrecision;
  924. D:=RequestedDigits-DecimalPos+1;
  925. end;
  926. FV:=FloatToDecimal(aValue,P,D);
  927. DistToDecimal:=DecimalPos-1;
  928. if IsScientific then
  929. PadZeroes:=0 // No padding.
  930. else
  931. begin
  932. PadZeroes:=FV.Exponent-(DecimalPos-1);
  933. if (PadZeroes>=0) then
  934. DistToDecimal:=FV.Exponent
  935. end;
  936. // Writeln('PadZeroes : ',PadZeroes, ', DistToDecimal : ',DistToDecimal);
  937. Available:=-1;
  938. while (Available<High(FV.Digits)) and (FV.Digits[Available+1]<>#0) do
  939. Inc(Available);
  940. // Writeln('Available: ',Available);
  941. end;
  942. Function FormatExponent(ASign: Char; aExponent: Integer) : String;
  943. begin
  944. Result:=IntToStr(aExponent);
  945. Result:=StringOfChar('0',ExpSize-Length(Result))+Result;
  946. if (aExponent<0) then
  947. Result:='-'+Result
  948. else if (aExponent>0) and (aSign='+') then
  949. Result:=aSign+Result;
  950. end;
  951. var
  952. I,S : Integer;
  953. C,Q : Char;
  954. PA : TPosArray;
  955. InLiteral : Boolean;
  956. begin
  957. SetLength(PA,4);
  958. Result:='';
  959. Initvars;
  960. // What section to use ?
  961. if (E>0) then
  962. S:=1
  963. else if (E<0) then
  964. S:=2
  965. else
  966. S:=3;
  967. PA[0]:=0;
  968. I:=GetSections(PA);
  969. if (I<S) or (PA[S]-PA[S-1]=0) then
  970. S:=1;
  971. // Extract correct section
  972. SectionLength:=PA[S]-PA[S-1]-1;
  973. Section:=Copy(Fmt,PA[S-1]+1,SectionLength);
  974. SetLength(Section,SectionLength);
  975. // Writeln('Section ',I,' : "',Section,'" ',SectionLength);
  976. AnalyzeFormat;
  977. // Writeln('RequestedDigits: ',RequestedDigits,', DecimalPos : ',DecimalPos,', LastDigit: ',LastDigit,', FirstDigit: ',FirstDigit);
  978. CalcRunVars;
  979. // If we cannot process value using current settings, fallback
  980. if (SectionLength=0) or ValueOutSideScope then
  981. begin
  982. asm
  983. Section=E.toPrecision(15);
  984. end;
  985. Result:=Section;
  986. end;
  987. // Get Started
  988. I:=1;
  989. Current:=0;
  990. Q:=' ';
  991. InLiteral:=False;
  992. if (FV.Negative) and (S=1) then
  993. ToResult('-');
  994. while (I<=SectionLength) do
  995. begin
  996. C:=Section[i];
  997. // Writeln('Analyzing pos ',I,': "',C,'"');
  998. If (C in ['"', '''']) then
  999. begin
  1000. if InLiteral then
  1001. InLiteral:=C<>Q
  1002. else
  1003. begin
  1004. inLiteral:=True;
  1005. Q:=C;
  1006. end;
  1007. end
  1008. else if InLiteral then
  1009. ToResult(C)
  1010. else
  1011. case C of
  1012. '0', '#':
  1013. CopyDigit;
  1014. '.', ',':
  1015. ; // Do nothing, handled by CopyDigit
  1016. 'e', 'E':
  1017. begin
  1018. ToResult(C); // Always needed
  1019. Inc(I);
  1020. if I<=Length(Section) then
  1021. begin
  1022. C:=Section[I];
  1023. if (C in ['+','-']) then
  1024. begin
  1025. AddToResult(FormatExponent(C,FV.Exponent-DecimalPos+1));
  1026. // Skip rest
  1027. while (I<SectionLength) and (Section[i+1]='0') do
  1028. Inc(I);
  1029. end;
  1030. end;
  1031. end;
  1032. else
  1033. ToResult(C);
  1034. end;
  1035. Inc(i);
  1036. end;
  1037. end;
  1038. function StrToBool(const S: String): Boolean;
  1039. begin
  1040. if not(TryStrToBool(S,Result)) then
  1041. raise EConvertError.CreateFmt(SInvalidBoolean,[S]);
  1042. end;
  1043. procedure CheckBoolStrs;
  1044. begin
  1045. if Length(TrueBoolStrs)=0 then
  1046. begin
  1047. SetLength(TrueBoolStrs,1);
  1048. TrueBoolStrs[0]:='True';
  1049. end;
  1050. if Length(FalseBoolStrs)=0 then
  1051. begin
  1052. SetLength(FalseBoolStrs,1);
  1053. FalseBoolStrs[0]:='False';
  1054. end;
  1055. end;
  1056. function BoolToStr(B: Boolean; UseBoolStrs: Boolean): string;
  1057. begin
  1058. if UseBoolStrs Then
  1059. begin
  1060. CheckBoolStrs;
  1061. if B then
  1062. Result:=TrueBoolStrs[0]
  1063. else
  1064. Result:=FalseBoolStrs[0];
  1065. end else
  1066. if B then
  1067. Result:='-1'
  1068. else
  1069. Result:='0';
  1070. end;
  1071. function BoolToStr(B: Boolean; const TrueS, FalseS: String): string;
  1072. begin
  1073. if B then Result:=TrueS else Result:=FalseS;
  1074. end;
  1075. function StrToBoolDef(const S: String; Default: Boolean): Boolean;
  1076. begin
  1077. if not TryStrToBool(S,Result) then
  1078. Result:=Default;
  1079. end;
  1080. function TryStrToBool(const S: String; out Value: Boolean): Boolean;
  1081. Var
  1082. Temp : String;
  1083. I : Longint;
  1084. D : Double;
  1085. Code: integer;
  1086. begin
  1087. Temp:=uppercase(S);
  1088. Val(Temp,D,code);
  1089. Result:=true;
  1090. If Code=0 then
  1091. Value:=(D<>0.0)
  1092. else
  1093. begin
  1094. CheckBoolStrs;
  1095. for I:=low(TrueBoolStrs) to High(TrueBoolStrs) do
  1096. if Temp=uppercase(TrueBoolStrs[I]) then
  1097. begin
  1098. Value:=true;
  1099. exit;
  1100. end;
  1101. for I:=low(FalseBoolStrs) to High(FalseBoolStrs) do
  1102. if Temp=uppercase(FalseBoolStrs[I]) then
  1103. begin
  1104. Value:=false;
  1105. exit;
  1106. end;
  1107. Result:=false;
  1108. end;
  1109. end;
  1110. function UpperCase(const s: String): String; assembler;
  1111. asm
  1112. return s.toUpperCase();
  1113. end;
  1114. function LowerCase(const s: String): String; assembler;
  1115. asm
  1116. return s.toLowerCase();
  1117. end;
  1118. function CompareStr(const s1, s2: String): Integer; assembler;
  1119. asm
  1120. var l1 = s1.length;
  1121. var l2 = s2.length;
  1122. if (l1<=l2){
  1123. var s = s2.substr(0,l1);
  1124. if (s1<s){ return -1;
  1125. } else if (s1>s){ return 1;
  1126. } else { return l1<l2 ? -1 : 0; };
  1127. } else {
  1128. var s = s1.substr(0,l2);
  1129. if (s<s2){ return -1;
  1130. } else { return 1; };
  1131. };
  1132. end;
  1133. function SameStr(const s1, s2: String): Boolean; assembler;
  1134. asm
  1135. return s1 == s2;
  1136. end;
  1137. function CompareText(const s1, s2: String): Integer; assembler;
  1138. asm
  1139. var l1 = s1.toLowerCase();
  1140. var l2 = s2.toLowerCase();
  1141. if (l1>l2){ return 1;
  1142. } else if (l1<l2){ return -1;
  1143. } else { return 0; }
  1144. end;
  1145. function SameText(const s1, s2: String): Boolean; assembler;
  1146. asm
  1147. return s1.toLowerCase() == s2.toLowerCase();
  1148. end;
  1149. function AnsiCompareText(const s1, s2: String): Integer; assembler;
  1150. asm
  1151. return s1.localeCompare(s2);
  1152. end;
  1153. function AnsiSameText(const s1, s2: String): Boolean; assembler;
  1154. asm
  1155. return s1.localeCompare(s2) == 0;
  1156. end;
  1157. function AnsiCompareStr(const s1, s2: String): Integer;
  1158. begin
  1159. {$IFDEF ECMAScript6}
  1160. Result:=CompareText(TJSString(s1).normalize(),TJSString(s1).normalize());
  1161. {$ELSE}
  1162. Result:=CompareText(s1,s2);
  1163. {$ENDIF}
  1164. end;
  1165. procedure AppendStr(var Dest: String; const S: string);
  1166. begin
  1167. Dest:=Dest+S;
  1168. end;
  1169. Const
  1170. feInvalidFormat = 1;
  1171. feMissingArgument = 2;
  1172. feInvalidArgIndex = 3;
  1173. Procedure DoFormatError (ErrCode : Longint;const fmt: String);
  1174. begin
  1175. //!! must be changed to contain format string...
  1176. Case ErrCode of
  1177. feInvalidFormat : raise EConvertError.Createfmt(SInvalidFormat,[Fmt]);
  1178. feMissingArgument : raise EConvertError.Createfmt(SArgumentMissing,[Fmt]);
  1179. feInvalidArgIndex : raise EConvertError.Createfmt(SInvalidArgIndex,[Fmt]);
  1180. end;
  1181. end;
  1182. Const
  1183. maxdigits = 15;
  1184. Function ReplaceDecimalSep(S: String; Const DS : string) : string;
  1185. Var
  1186. P : Integer;
  1187. begin
  1188. P:=Pos('.',S);
  1189. if P>0 then
  1190. Result:=Copy(S,1,P-1)+DS+Copy(S,P+1,Length(S)-P)
  1191. else
  1192. Result:=S;
  1193. end;
  1194. function FormatGeneralFloat(Value : double; Precision : Integer; DS : String) : string;
  1195. Var
  1196. P, PE, Q, Exponent: Integer;
  1197. Begin
  1198. If (Precision = -1) Or (Precision > maxdigits) Then
  1199. Precision := maxdigits;
  1200. { First convert to scientific format, with correct precision }
  1201. Str(Value:precision+7, Result);
  1202. { Delete leading spaces }
  1203. Result:=TrimLeft(Result);
  1204. P:=Pos('.',Result);
  1205. if P=0 then
  1206. exit;
  1207. { Consider removing exponent }
  1208. PE:=Pos('E',Result);
  1209. if PE=0 then
  1210. begin
  1211. Result:=ReplaceDecimalSep(Result,DS);
  1212. exit;
  1213. end;
  1214. { Read exponent }
  1215. Q:=PE+2;
  1216. Exponent := 0;
  1217. while (Q <= Length(Result)) do
  1218. begin
  1219. Exponent := Exponent*10 + Ord(Result[Q])-Ord('0');
  1220. Inc(Q);
  1221. end;
  1222. if Result[PE+1] = '-' then
  1223. Exponent := -Exponent;
  1224. if (P+Exponent < PE) and (Exponent > -6) then
  1225. begin
  1226. { OK to remove exponent }
  1227. SetLength(Result,PE-1); { Trim exponent }
  1228. if Exponent >= 0 then
  1229. begin
  1230. { Shift point to right }
  1231. for Q := 0 to Exponent-1 do
  1232. begin
  1233. Result[P] := Result[P+1];
  1234. Inc(P);
  1235. end;
  1236. Result[P] := '.';
  1237. P := 1;
  1238. if Result[P] = '-' then
  1239. Inc(P);
  1240. while (Result[P] = '0') and (P < Length(Result)) and (Copy(Result,P+1,Length(DS))<>DS) do
  1241. { Trim leading zeros; conversion above should not give any, but occasionally does
  1242. because of rounding }
  1243. System.Delete(Result,P,1);
  1244. end
  1245. else
  1246. begin
  1247. { Add zeros at start }
  1248. Insert(Copy('00000',1,-Exponent),Result,P-1);
  1249. Result[P-Exponent] := Result[P-Exponent-1]; { Copy leading digit }
  1250. Result[P] := '.';
  1251. if Exponent <> -1 then
  1252. Result[P-Exponent-1] := '0';
  1253. end;
  1254. { Remove trailing zeros }
  1255. Q := Length(Result);
  1256. while (Q > 0) and (Result[Q] = '0') do
  1257. Dec(Q);
  1258. if Result[Q] = '.' then
  1259. Dec(Q); { Remove trailing decimal point }
  1260. if (Q = 0) or ((Q=1) and (Result[1] = '-')) then
  1261. Result := '0'
  1262. else
  1263. SetLength(Result,Q);
  1264. end
  1265. else
  1266. begin
  1267. { Need exponent, but remove superfluous characters }
  1268. { Delete trailing zeros }
  1269. while Result[PE-1] = '0' do
  1270. begin
  1271. System.Delete(Result,PE-1,1);
  1272. Dec(PE);
  1273. end;
  1274. { If number ends in decimal point, remove it }
  1275. if Result[PE-1] = DS then
  1276. begin
  1277. System.Delete(Result,PE-1,1);
  1278. Dec(PE);
  1279. end;
  1280. { delete superfluous + in exponent }
  1281. if Result[PE+1]='+' then
  1282. System.Delete(Result,PE+1,1)
  1283. else
  1284. Inc(PE);
  1285. while Result[PE+1] = '0' do
  1286. { Delete leading zeros in exponent }
  1287. System.Delete(Result,PE+1,1)
  1288. end;
  1289. Result:=ReplaceDecimalSep(Result,DS)
  1290. end;
  1291. function FormatExponentFloat(Value : double; Precision,Digits : Integer;DS : String) : string;
  1292. Var
  1293. P: Integer;
  1294. Begin
  1295. DS:=DecimalSeparator;
  1296. If (Precision = -1) Or (Precision > maxdigits) Then
  1297. Precision := maxdigits;
  1298. Str(Value:Precision+7, Result);
  1299. { Delete leading spaces }
  1300. while Result[1] = ' ' do
  1301. System.Delete(Result, 1, 1);
  1302. P:=Pos('E',Result);
  1303. if P=0 then
  1304. begin
  1305. Result:=ReplaceDecimalSep(Result,DS);
  1306. exit;
  1307. end;
  1308. Inc(P, 2);
  1309. if Digits > 4 then
  1310. Digits:=4;
  1311. Digits:=Length(Result) - P - Digits + 1;
  1312. if Digits < 0 then
  1313. insert(copy('0000',1,-Digits),Result,P)
  1314. else
  1315. while (Digits > 0) and (Result[P] = '0') do
  1316. begin
  1317. System.Delete(Result, P, 1);
  1318. if P > Length(Result) then
  1319. begin
  1320. System.Delete(Result, P - 2, 2);
  1321. break;
  1322. end;
  1323. Dec(Digits);
  1324. end;
  1325. Result:=ReplaceDecimalSep(Result,DS);
  1326. End;
  1327. function FormatFixedFloat(Value : double; Digits : Integer; DS : String) : string;
  1328. Begin
  1329. If Digits = -1 Then
  1330. Digits := 2
  1331. Else If Digits > 18 Then
  1332. Digits := 18;
  1333. Str(Value:0:Digits, Result);
  1334. if (Result<>'') and (Result[1]=' ') then
  1335. Delete(Result,1,1);
  1336. Result:=ReplaceDecimalSep(Result,DS);
  1337. end;
  1338. function FormatNumberFloat(Value : double; Digits : Integer; DS,TS : String) : string;
  1339. Var
  1340. P : integer;
  1341. Begin
  1342. If Digits = -1 Then
  1343. Digits := 2
  1344. else If Digits > maxdigits Then
  1345. Digits := maxdigits;
  1346. Str(Value:0:Digits, Result);
  1347. if (Result<>'') and (Result[1]=' ') then
  1348. Delete(Result,1,1);
  1349. P:=Pos('.',Result);
  1350. Result:=ReplaceDecimalSep(Result,DS);
  1351. Dec(P,3);
  1352. if (TS<>'') and (TS<>#0) then
  1353. While (P>1) Do
  1354. Begin
  1355. If (Result[P-1] <> '-') Then
  1356. Insert(TS, Result, P);
  1357. Dec(P, 3);
  1358. End;
  1359. End;
  1360. Function FloatToStrF(const Value : double; format: TFloatFormat; Precision, Digits: Integer): String;
  1361. Var
  1362. DS: string;
  1363. function RemoveLeadingNegativeSign(var AValue: String): Boolean;
  1364. // removes negative sign in case when result is zero eg. -0.00
  1365. var
  1366. i: PtrInt;
  1367. TS: String;
  1368. StartPos: PtrInt;
  1369. begin
  1370. Result:=False;
  1371. StartPos := 2;
  1372. TS := ThousandSeparator;
  1373. for i :=StartPos to length(AValue) do
  1374. begin
  1375. Result := (AValue[i] in ['0', DS, 'E', '+']) or (aValue=TS);
  1376. if not Result then
  1377. break;
  1378. end;
  1379. if (Result) then
  1380. Delete(AValue, 1, 1);
  1381. end;
  1382. Begin
  1383. DS:=DecimalSeparator;
  1384. Case format Of
  1385. ffGeneral:
  1386. Result:=FormatGeneralFloat(Value,Precision,DS);
  1387. ffExponent:
  1388. Result:=FormatExponentFloat(Value,Precision,Digits,DS);
  1389. ffFixed:
  1390. Result:=FormatFixedFloat(Value,Digits,DS);
  1391. ffNumber:
  1392. Result:=FormatNumberFloat(Value,Digits,DS,ThousandSeparator);
  1393. // ffCurrency: not supported
  1394. end;
  1395. if (length(Result)>1) and (Result[1]='-') then
  1396. RemoveLeadingNegativeSign(Result);
  1397. end;
  1398. function Format (const Fmt: String; const Args: array of jsvalue): String;
  1399. Var ChPos,OldPos,ArgPos,DoArg,Len : SizeInt;
  1400. Hs,ToAdd : String;
  1401. Index : SizeInt;
  1402. Width,Prec : Longint;
  1403. Left : Boolean;
  1404. Fchar : char;
  1405. vq : nativeint;
  1406. {
  1407. ReadFormat reads the format string. It returns the type character in
  1408. uppercase, and sets index, Width, Prec to their correct values,
  1409. or -1 if not set. It sets Left to true if left alignment was requested.
  1410. In case of an error, DoFormatError is called.
  1411. }
  1412. Function ReadFormat : Char;
  1413. Var Value : NativeInt;
  1414. Procedure ReadInteger;
  1415. var
  1416. Code: integer;
  1417. ArgN: SizeInt;
  1418. begin
  1419. If Value<>-1 then exit; // Was already read.
  1420. OldPos:=ChPos;
  1421. While (ChPos<=Len) and
  1422. (Fmt[ChPos]<='9') and (Fmt[ChPos]>='0') do inc(ChPos);
  1423. If ChPos>len then
  1424. DoFormatError(feInvalidFormat,Fmt);
  1425. If Fmt[ChPos]='*' then
  1426. begin
  1427. if Index=-1 then
  1428. ArgN:=Argpos
  1429. else
  1430. begin
  1431. ArgN:=Index;
  1432. Inc(Index);
  1433. end;
  1434. If (ChPos>OldPos) or (ArgN>High(Args)) then
  1435. DoFormatError(feInvalidFormat,Fmt);
  1436. ArgPos:=ArgN+1;
  1437. if IsNumber(Args[ArgN]) and IsInteger(Args[ArgN]) then
  1438. Value:=Integer(Args[ArgN])
  1439. else
  1440. DoFormatError(feInvalidFormat,Fmt);
  1441. Inc(ChPos);
  1442. end
  1443. else
  1444. begin
  1445. If (OldPos<ChPos) Then
  1446. begin
  1447. Val (Copy(Fmt,OldPos,ChPos-OldPos),value,code);
  1448. // This should never happen !!
  1449. If Code>0 then DoFormatError (feInvalidFormat,Fmt);
  1450. end
  1451. else
  1452. Value:=-1;
  1453. end;
  1454. end;
  1455. Procedure ReadIndex;
  1456. begin
  1457. If Fmt[ChPos]<>':' then
  1458. ReadInteger
  1459. else
  1460. value:=0; // Delphi undocumented behaviour, assume 0, #11099
  1461. If Fmt[ChPos]=':' then
  1462. begin
  1463. If Value=-1 then DoFormatError(feMissingArgument,Fmt);
  1464. Index:=Value;
  1465. Value:=-1;
  1466. Inc(ChPos);
  1467. end;
  1468. end;
  1469. Procedure ReadLeft;
  1470. begin
  1471. If Fmt[ChPos]='-' then
  1472. begin
  1473. left:=True;
  1474. Inc(ChPos);
  1475. end
  1476. else
  1477. Left:=False;
  1478. end;
  1479. Procedure ReadWidth;
  1480. begin
  1481. ReadInteger;
  1482. If Value<>-1 then
  1483. begin
  1484. Width:=Value;
  1485. Value:=-1;
  1486. end;
  1487. end;
  1488. Procedure ReadPrec;
  1489. begin
  1490. If Fmt[ChPos]='.' then
  1491. begin
  1492. inc(ChPos);
  1493. ReadInteger;
  1494. If Value=-1 then
  1495. Value:=0;
  1496. prec:=Value;
  1497. end;
  1498. end;
  1499. begin
  1500. Index:=-1;
  1501. Width:=-1;
  1502. Prec:=-1;
  1503. Value:=-1;
  1504. inc(ChPos);
  1505. If Fmt[ChPos]='%' then
  1506. begin
  1507. Result:='%';
  1508. exit; // VP fix
  1509. end;
  1510. ReadIndex;
  1511. ReadLeft;
  1512. ReadWidth;
  1513. ReadPrec;
  1514. Result:=Upcase(Fmt[ChPos]);
  1515. end;
  1516. function Checkarg (AT : TJSValueType; err:boolean):boolean;
  1517. {
  1518. Check if argument INDEX is of correct type (AT)
  1519. If Index=-1, ArgPos is used, and argpos is augmented with 1
  1520. DoArg is set to the argument that must be used.
  1521. }
  1522. begin
  1523. result:=false;
  1524. if Index=-1 then
  1525. DoArg:=Argpos
  1526. else
  1527. DoArg:=Index;
  1528. ArgPos:=DoArg+1;
  1529. If (Doarg>High(Args)) or (GetValueTYpe(Args[Doarg])<>AT) then
  1530. begin
  1531. if err then
  1532. DoFormatError(feInvalidArgindex,Fmt);
  1533. dec(ArgPos);
  1534. exit;
  1535. end;
  1536. result:=true;
  1537. end;
  1538. begin
  1539. Result:='';
  1540. Len:=Length(Fmt);
  1541. ChPos:=1;
  1542. OldPos:=1;
  1543. ArgPos:=0;
  1544. While ChPos<=len do
  1545. begin
  1546. While (ChPos<=Len) and (Fmt[ChPos]<>'%') do
  1547. inc(ChPos);
  1548. If ChPos>OldPos Then
  1549. Result:=Result+Copy(Fmt,OldPos,ChPos-Oldpos);
  1550. If ChPos<Len then
  1551. begin
  1552. FChar:=ReadFormat;
  1553. {$ifdef fmtdebug}
  1554. DumpFormat(FCHar);
  1555. {$endif}
  1556. Case FChar of
  1557. 'D' : begin
  1558. Checkarg(jvtinteger,true);
  1559. toAdd:=IntToStr(NativeInt(Args[DoArg]));
  1560. Width:=Abs(width);
  1561. Index:=Prec-Length(ToAdd);
  1562. If ToAdd[1]<>'-' then
  1563. ToAdd:=StringOfChar('0',Index)+ToAdd
  1564. else
  1565. // + 1 to accomodate for - sign in length !!
  1566. Insert(StringOfChar('0',Index+1),toadd,2);
  1567. end;
  1568. 'U' : begin
  1569. Checkarg(jvtinteger,True);
  1570. if NativeInt(Args[Doarg])<0 then
  1571. DoFormatError(feInvalidArgindex,Fmt);
  1572. Toadd:=IntToStr(NativeInt(Args[Doarg]));
  1573. Width:=Abs(width);
  1574. Index:=Prec-Length(ToAdd);
  1575. ToAdd:=StringOfChar('0',Index)+ToAdd
  1576. end;
  1577. 'E' : begin
  1578. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1579. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1580. end;
  1581. 'F' : begin
  1582. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1583. ToAdd:=FloatToStrF(Double(Args[doarg]),ffFixed,9999,Prec);
  1584. end;
  1585. 'G' : begin
  1586. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1587. ToAdd:=FloatToStrF(Double(Args[doarg]),ffGeneral,Prec,3);
  1588. end;
  1589. 'N' : begin
  1590. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1591. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  1592. end;
  1593. 'M' : begin
  1594. if CheckArg(jvtFloat,false) or CheckArg(jvtInteger,True) then
  1595. ToAdd:=FloatToStrF(Double(Args[doarg]),ffNumber,9999,Prec);
  1596. end;
  1597. 'S' : begin
  1598. CheckArg(jvtString,true);
  1599. hs:=String(Args[doarg]);
  1600. Index:=Length(hs);
  1601. If (Prec<>-1) and (Index>Prec) then
  1602. Index:=Prec;
  1603. ToAdd:=Copy(hs,1,Index);
  1604. end;
  1605. 'P' : Begin
  1606. CheckArg(jvtInteger,true);
  1607. ToAdd:=IntToHex(NativeInt(Args[DoArg]),31);
  1608. end;
  1609. 'X' : begin
  1610. Checkarg(jvtinteger,true);
  1611. vq:=nativeInt(Args[Doarg]);
  1612. index:=31; // May need to adjust to NativeInt
  1613. If Prec>index then
  1614. ToAdd:=IntToHex(vq,index)
  1615. else
  1616. begin
  1617. // determine minimum needed number of hex digits.
  1618. Index:=1;
  1619. While (NativeInt(1) shl (Index*4)<=vq) and (index<16) do
  1620. inc(Index);
  1621. If Index>Prec then
  1622. Prec:=Index;
  1623. ToAdd:=IntToHex(vq,Prec);
  1624. end;
  1625. end;
  1626. '%': ToAdd:='%';
  1627. end;
  1628. If Width<>-1 then
  1629. If Length(ToAdd)<Width then
  1630. If not Left then
  1631. ToAdd:=StringOfChar(' ',Width-Length(ToAdd))+ToAdd
  1632. else
  1633. ToAdd:=ToAdd+StringOfChar(' ',Width-Length(ToAdd));
  1634. Result:=Result+ToAdd;
  1635. end;
  1636. inc(ChPos);
  1637. Oldpos:=ChPos;
  1638. end;
  1639. end;
  1640. function LocaleCompare(const s1, s2, locales: String): Boolean; assembler;
  1641. asm
  1642. return s1.localeCompare(s2,locales) == 0;
  1643. end;
  1644. function NormalizeStr(const S: String; const Norm: String): String; assembler;
  1645. asm
  1646. return S.normalize(Norm);
  1647. end;
  1648. function IsValidIdent(const Ident: string; AllowDots: Boolean = False; StrictDots: Boolean = False): Boolean;
  1649. const
  1650. Alpha = ['A'..'Z', 'a'..'z', '_'];
  1651. AlphaNum = Alpha + ['0'..'9'];
  1652. Dot = '.';
  1653. var
  1654. First: Boolean;
  1655. I, Len: Integer;
  1656. begin
  1657. Len := Length(Ident);
  1658. if Len < 1 then
  1659. Exit(False);
  1660. First := True;
  1661. Result:=false;
  1662. I:=1;
  1663. While I<=len do
  1664. begin
  1665. if First then
  1666. begin
  1667. if not (Ident[I] in Alpha) then exit;
  1668. First := False;
  1669. end
  1670. else if AllowDots and (Ident[I] = Dot) then
  1671. begin
  1672. if StrictDots then
  1673. begin
  1674. if I >= Len then exit;
  1675. First := True;
  1676. end;
  1677. end
  1678. else
  1679. if not (Ident[I] in AlphaNum) then exit;
  1680. I:=I+1;
  1681. end;
  1682. Result:=true;
  1683. end;
  1684. procedure FreeAndNil(var Obj);
  1685. var
  1686. o: TObject;
  1687. begin
  1688. o:=TObject(Obj);
  1689. if o=nil then exit;
  1690. TObject(Obj):=nil;
  1691. o.Destroy;
  1692. end;
  1693. { EVariantError }
  1694. constructor EVariantError.CreateCode(Code: Longint);
  1695. begin
  1696. ErrCode:=Code;
  1697. end;
  1698. { Exception }
  1699. constructor Exception.Create(const Msg: String);
  1700. begin
  1701. fMessage:=Msg;
  1702. end;
  1703. constructor Exception.CreateFmt(const Msg: string; const Args: array of JSValue);
  1704. begin
  1705. //writeln('Exception.CreateFmt START ',ClassName,' "',Msg,'" Args=',Args);
  1706. fMessage:=Format(Msg,Args);
  1707. //writeln('Exception.CreateFmt END ',ClassName,' "',Msg,'" fMessage=',fMessage);
  1708. end;
  1709. constructor Exception.CreateHelp(const Msg: String; AHelpContext: Integer);
  1710. begin
  1711. fMessage:=Msg;
  1712. fHelpContext:=AHelpContext;
  1713. end;
  1714. constructor Exception.CreateFmtHelp(const Msg: string;
  1715. const Args: array of JSValue; AHelpContext: Integer);
  1716. begin
  1717. fMessage:=Format(Msg,Args);
  1718. fHelpContext:=AHelpContext;
  1719. end;
  1720. function Exception.ToString: String;
  1721. begin
  1722. Result:=ClassName+': '+Message;
  1723. end;
  1724. Const
  1725. RESpecials = '([\[\]\(\)\\\.\*])';
  1726. Function StringReplace(aOriginal, aSearch, aReplace : string; Flags : TStringReplaceFlags) : String;
  1727. Var
  1728. REFlags : String;
  1729. REString : String;
  1730. begin
  1731. REFlags:='';
  1732. if rfReplaceAll in flags then
  1733. ReFlags:='g';
  1734. if rfIgnoreCase in flags then
  1735. ReFlags:=ReFlags+'i';
  1736. REString:=TJSString(aSearch).replace(TJSRegexp.new(RESpecials,'g'),'\$1');
  1737. Result:=TJSString(aOriginal).replace(TJSRegexp.new(REString,REFlags),aReplace);
  1738. end;
  1739. Function QuoteString(aOriginal : String; AQuote : Char) : String;
  1740. Var
  1741. REString : String;
  1742. begin
  1743. REString:=TJSString(aQuote).replace(TJSRegexp.new(aOriginal,'g'),'\\$1');
  1744. Result:=AQuote+TJSString(aOriginal).replace(TJSRegexp.new(REString,'g'),'$1\$1')+AQuote;
  1745. end;
  1746. function IsDelimiter(const Delimiters, S: string; Index: Integer): Boolean;
  1747. begin
  1748. Result:=False;
  1749. if (Index>0) and (Index<=Length(S)) then
  1750. Result:=Pos(S[Index],Delimiters)<>0; // Note we don't do MBCS yet
  1751. end;
  1752. function AdjustLineBreaks(const S: string): string;
  1753. begin
  1754. Result:=AdjustLineBreaks(S,DefaultTextLineBreakStyle);
  1755. end;
  1756. function AdjustLineBreaks(const S: string; Style: TTextLineBreakStyle): string;
  1757. var
  1758. I,L: Longint;
  1759. Res : String;
  1760. Procedure Add(C : Char);
  1761. begin
  1762. Res:=Res+C;
  1763. end;
  1764. begin
  1765. I:=0;
  1766. L:=Length(S);
  1767. Result:='';
  1768. While (I<=L) do
  1769. case S[I] of
  1770. #10: begin
  1771. if Style in [tlbsCRLF,tlbsCR] then
  1772. Add(#13);
  1773. if Style=tlbsCRLF then
  1774. Add(#10);
  1775. Inc(I);
  1776. end;
  1777. #13: begin
  1778. if Style=tlbsCRLF then
  1779. Add(#13);
  1780. Add(#10);
  1781. Inc(I);
  1782. if S[I]=#10 then
  1783. Inc(I);
  1784. end;
  1785. else
  1786. Add(S[i]);
  1787. Inc(I);
  1788. end;
  1789. Result:=Res;
  1790. end;
  1791. function WrapText(const Line, BreakStr: string; const BreakChars: Array of char; MaxCol: Integer): string;
  1792. const
  1793. Quotes = ['''', '"'];
  1794. Var
  1795. L : String;
  1796. C,LQ,BC : Char;
  1797. P,BLen,Len : Integer;
  1798. HB,IBC : Boolean;
  1799. begin
  1800. Result:='';
  1801. L:=Line;
  1802. Blen:=Length(BreakStr);
  1803. If (BLen>0) then
  1804. BC:=BreakStr[1]
  1805. else
  1806. BC:=#0;
  1807. Len:=Length(L);
  1808. While (Len>0) do
  1809. begin
  1810. P:=1;
  1811. LQ:=#0;
  1812. HB:=False;
  1813. IBC:=False;
  1814. While ((P<=Len) and ((P<=MaxCol) or not IBC)) and ((LQ<>#0) or Not HB) do
  1815. begin
  1816. C:=L[P];
  1817. If (C=LQ) then
  1818. LQ:=#0
  1819. else If (C in Quotes) then
  1820. LQ:=C;
  1821. If (LQ<>#0) then
  1822. Inc(P)
  1823. else
  1824. begin
  1825. HB:=((C=BC) and (BreakStr=Copy(L,P,BLen)));
  1826. If HB then
  1827. Inc(P,Blen)
  1828. else
  1829. begin
  1830. If (P>=MaxCol) then
  1831. IBC:=CharInSet(C,BreakChars);
  1832. Inc(P);
  1833. end;
  1834. end;
  1835. // Writeln('"',C,'" : IBC : ',IBC,' HB : ',HB,' LQ : ',LQ,' P>MaxCol : ',P>MaxCol);
  1836. end;
  1837. Result:=Result+Copy(L,1,P-1);
  1838. Delete(L,1,P-1);
  1839. Len:=Length(L);
  1840. If (Len>0) and Not HB then
  1841. Result:=Result+BreakStr;
  1842. end;
  1843. end;
  1844. function WrapText(const Line: string; MaxCol: Integer): string;
  1845. begin
  1846. Result:=WrapText(Line,sLineBreak, [' ', '-', #9], MaxCol);
  1847. end;
  1848. function GetEnvironmentVariable(const EnvVar: String): String;
  1849. begin
  1850. if Assigned(OnGetEnvironmentVariable) then
  1851. Result:=OnGetEnvironmentVariable(EnvVar)
  1852. else
  1853. Result:='';
  1854. end;
  1855. function GetEnvironmentVariableCount: Integer;
  1856. begin
  1857. if Assigned(OnGetEnvironmentVariableCount) then
  1858. Result:=OnGetEnvironmentVariableCount()
  1859. else
  1860. Result:=0;
  1861. end;
  1862. function GetEnvironmentString(Index: Integer): String;
  1863. begin
  1864. if Assigned(OnGetEnvironmentString) then
  1865. Result:=OnGetEnvironmentString(Index)
  1866. else
  1867. Result:='';
  1868. end;
  1869. { Date/Time routines}
  1870. Function DoEncodeDate(Year, Month, Day: Word): longint;
  1871. Var
  1872. D : TDateTime;
  1873. begin
  1874. If TryEncodeDate(Year,Month,Day,D) then
  1875. Result:=Trunc(D)
  1876. else
  1877. Result:=0;
  1878. end;
  1879. function DoEncodeTime(Hour, Minute, Second, MilliSecond: word): TDateTime;
  1880. begin
  1881. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  1882. Result:=0;
  1883. end;
  1884. Function DateTimeToJSDate(aDateTime : TDateTime) : TJSDate;
  1885. Var
  1886. Y,M,D,h,n,s,z : Word;
  1887. begin
  1888. DecodeDate(Trunc(aDateTime),Y,M,D);
  1889. DecodeTime(Frac(aDateTime),H,N,S,Z);
  1890. Result:=TJSDate.New(Y,M,D,h,n,s,z);
  1891. end;
  1892. Function JSDatetoDateTime(ADate: TJSDate) : TDateTime;
  1893. begin
  1894. Result:=EncodeDate(ADate.FullYear,ADate.Month+1,ADate.Date) +
  1895. EncodeTime(ADate.Hours,ADate.Minutes,ADate.Seconds,ADate.Milliseconds);
  1896. end;
  1897. { ComposeDateTime converts a Date and a Time into one TDateTime }
  1898. function ComposeDateTime(Date,Time : TDateTime) : TDateTime;
  1899. begin
  1900. if Date < 0 then
  1901. Result := trunc(Date) - Abs(frac(Time))
  1902. else
  1903. Result := trunc(Date) + Abs(frac(Time));
  1904. end;
  1905. Function TryEncodeDate(Year,Month,Day : Word; Out Date : TDateTime) : Boolean;
  1906. var
  1907. c, ya: LongWord;
  1908. begin
  1909. Result:=(Year>0) and (Year<10000) and
  1910. (Month >= 1) and (Month<=12) and
  1911. (Day>0) and (Day<=MonthDays[IsleapYear(Year),Month]);
  1912. If Result then
  1913. begin
  1914. if month > 2 then
  1915. Dec(Month,3)
  1916. else
  1917. begin
  1918. Inc(Month,9);
  1919. Dec(Year);
  1920. end;
  1921. c:= Year DIV 100;
  1922. ya:= Year - 100*c;
  1923. Date := (146097*c) SHR 2 + (1461*ya) SHR 2 + (153*LongWord(Month)+2) DIV 5 + LongWord(Day);
  1924. // Note that this line can't be part of the line above, since TDateTime is
  1925. // signed and c and ya are not
  1926. Date := Date - 693900;
  1927. end
  1928. end;
  1929. function TryEncodeTime(Hour, Min, Sec, MSec:word; Out Time : TDateTime) : boolean;
  1930. begin
  1931. Result:=(Hour<24) and (Min<60) and (Sec<60) and (MSec<1000);
  1932. If Result then
  1933. Time:=TDateTime(LongWord(Hour)*3600000+LongWord(Min)*60000+LongWord(Sec)*1000+MSec)/MSecsPerDay;
  1934. end;
  1935. { EncodeDate packs three variables Year, Month and Day into a
  1936. TDateTime value the result is the number of days since 12/30/1899 }
  1937. function EncodeDate(Year, Month, Day: word): TDateTime;
  1938. begin
  1939. If Not TryEncodeDate(Year,Month,Day,Result) then
  1940. Raise EConvertError.CreateFmt('%s-%s-%s is not a valid date specification',
  1941. [IntToStr(Year),IntToStr(Month),IntToStr(Day)]);
  1942. end;
  1943. { EncodeTime packs four variables Hour, Minute, Second and MilliSecond into
  1944. a TDateTime value }
  1945. function EncodeTime(Hour, Minute, Second, MilliSecond:word):TDateTime;
  1946. begin
  1947. If not TryEncodeTime(Hour,Minute,Second,MilliSecond,Result) then
  1948. Raise EConvertError.CreateFmt('%s:%s:%s.%s is not a valid time specification',
  1949. [IntToStr(Hour),IntToStr(Minute),IntToStr(Second),IntToStr(MilliSecond)]);
  1950. end;
  1951. { DecodeDate unpacks the value Date into three values:
  1952. Year, Month and Day }
  1953. procedure DecodeDate(Date: TDateTime; out Year, Month, Day: word);
  1954. var
  1955. ly,ld,lm,j : LongWord;
  1956. begin
  1957. if Date <= -datedelta then // If Date is before 1-1-1 then return 0-0-0
  1958. begin
  1959. Year := 0;
  1960. Month := 0;
  1961. Day := 0;
  1962. end
  1963. else
  1964. begin
  1965. if Date>0 then
  1966. Date:=(Date+(1/(msecsperday*2)))
  1967. else
  1968. Date:=Date-(1/(msecsperday*2));
  1969. if Date>MaxDateTime then
  1970. Date:=MaxDateTime;
  1971. // Raise EConvertError.CreateFmt('%f is not a valid TDatetime encoding, maximum value is %f.',[Date,MaxDateTime]);
  1972. j := ((Trunc(Date) + 693900) SHL 2)-1;
  1973. ly:= j DIV 146097;
  1974. j:= j - 146097 * LongWord(ly);
  1975. ld := j SHR 2;
  1976. j:=(ld SHL 2 + 3) DIV 1461;
  1977. ld:= ((ld SHL 2) + 7 - 1461*j) SHR 2;
  1978. lm:=(5 * ld-3) DIV 153;
  1979. ld:= (5 * ld +2 - 153*lm) DIV 5;
  1980. ly:= 100 * LongWord(ly) + j;
  1981. if lm < 10 then
  1982. inc(lm,3)
  1983. else
  1984. begin
  1985. dec(lm,9);
  1986. inc(ly);
  1987. end;
  1988. year:=ly;
  1989. month:=lm;
  1990. day:=ld;
  1991. end;
  1992. end;
  1993. function DecodeDateFully(const DateTime: TDateTime; out Year, Month, Day, DOW: Word): Boolean;
  1994. begin
  1995. DecodeDate(DateTime,Year,Month,Day);
  1996. DOW:=DayOfWeek(DateTime);
  1997. Result:=IsLeapYear(Year);
  1998. end;
  1999. { DateTimeToTimeStamp converts DateTime to a TTimeStamp }
  2000. function DateTimeToTimeStamp(DateTime: TDateTime): TTimeStamp;
  2001. Var
  2002. D : Double;
  2003. begin
  2004. D:=DateTime * Double(MSecsPerDay);
  2005. if D<0 then
  2006. D:=D-0.5
  2007. else
  2008. D:=D+0.5;
  2009. result.Time := Trunc(Abs(Trunc(D)) Mod MSecsPerDay);
  2010. result.Date := DateDelta + (Trunc(D) div MSecsPerDay);
  2011. end;
  2012. { TimeStampToDateTime converts TimeStamp to a TDateTime value }
  2013. function TimeStampToDateTime(const TimeStamp: TTimeStamp): TDateTime;
  2014. begin
  2015. Result := ComposeDateTime(TimeStamp.Date - DateDelta,TimeStamp.Time/MSecsPerDay)
  2016. end;
  2017. { MSecsToTimeStamp }
  2018. function MSecsToTimeStamp(MSecs: NativeInt): TTimeStamp;
  2019. begin
  2020. result.Date := Trunc(msecs/msecsperday);
  2021. msecs:= msecs-NativeInt(result.date)*msecsperday;
  2022. result.Time := Round(MSecs);
  2023. end;
  2024. function TimeStampToMSecs(const TimeStamp: TTimeStamp): NativeInt;
  2025. begin
  2026. result := TimeStamp.Time + (timestamp.date*msecsperday);
  2027. end ;
  2028. { DecodeTime unpacks Time into four values:
  2029. Hour, Minute, Second and MilliSecond }
  2030. procedure DecodeTime(Time: TDateTime; out Hour, Minute, Second, MilliSecond: word);
  2031. Var
  2032. l : LongWord;
  2033. begin
  2034. l := DateTimeToTimeStamp(Time).Time;
  2035. Hour := l div 3600000;
  2036. l := l mod 3600000;
  2037. Minute := l div 60000;
  2038. l := l mod 60000;
  2039. Second := l div 1000;
  2040. l := l mod 1000;
  2041. MilliSecond := l;
  2042. end;
  2043. { DateTimeToSystemTime converts DateTime value to SystemTime }
  2044. procedure DateTimeToSystemTime(DateTime: TDateTime; out SystemTime: TSystemTime);
  2045. begin
  2046. DecodeDateFully(DateTime, SystemTime.Year, SystemTime.Month, SystemTime.Day,SystemTime.DayOfWeek);
  2047. DecodeTime(DateTime, SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond);
  2048. Dec(SystemTime.DayOfWeek);
  2049. end ;
  2050. { SystemTimeToDateTime converts SystemTime to a TDateTime value }
  2051. function SystemTimeToDateTime(const SystemTime: TSystemTime): TDateTime;
  2052. begin
  2053. result := ComposeDateTime(DoEncodeDate(SystemTime.Year, SystemTime.Month, SystemTime.Day),
  2054. DoEncodeTime(SystemTime.Hour, SystemTime.Minute, SystemTime.Second, SystemTime.MilliSecond));
  2055. end ;
  2056. function DayOfWeek(DateTime: TDateTime): integer;
  2057. begin
  2058. Result := 1 + ((Trunc(DateTime) - 1) mod 7);
  2059. If (Result<=0) then
  2060. Inc(Result,7);
  2061. end;
  2062. function Now: TDateTime;
  2063. begin
  2064. Result:=JSDateToDateTime(TJSDate.New());
  2065. end;
  2066. function Date: TDateTime;
  2067. begin
  2068. Result:=Trunc(Now);
  2069. end;
  2070. function Time: TDateTime;
  2071. begin
  2072. Result:=Now-Date;
  2073. end ;
  2074. { IncMonth increments DateTime with NumberOfMonths months,
  2075. NumberOfMonths can be less than zero }
  2076. function IncMonth(const DateTime: TDateTime; NumberOfMonths: integer = 1 ): TDateTime;
  2077. var
  2078. Year, Month, Day : word;
  2079. begin
  2080. DecodeDate(DateTime, Year, Month, Day);
  2081. IncAMonth(Year, Month, Day, NumberOfMonths);
  2082. result := ComposeDateTime(DoEncodeDate(Year, Month, Day), DateTime);
  2083. end ;
  2084. { IncAMonth is the same as IncMonth, but operates on decoded date }
  2085. procedure IncAMonth(var Year, Month, Day: Word; NumberOfMonths: Integer = 1);
  2086. var
  2087. TempMonth, S: Integer;
  2088. begin
  2089. If NumberOfMonths>=0 then
  2090. s:=1
  2091. else
  2092. s:=-1;
  2093. inc(Year,(NumberOfMonths div 12));
  2094. TempMonth:=Month+(NumberOfMonths mod 12)-1;
  2095. if (TempMonth>11) or
  2096. (TempMonth<0) then
  2097. begin
  2098. Dec(TempMonth, S*12);
  2099. Inc(Year, S);
  2100. end;
  2101. Month:=TempMonth+1; { Months from 1 to 12 }
  2102. If (Day>MonthDays[IsLeapYear(Year)][Month]) then
  2103. Day:=MonthDays[IsLeapYear(Year)][Month];
  2104. end;
  2105. { IsLeapYear returns true if Year is a leap year }
  2106. function IsLeapYear(Year: Word): boolean;
  2107. begin
  2108. Result := (Year mod 4 = 0) and ((Year mod 100 <> 0) or (Year mod 400 = 0));
  2109. end;
  2110. { DateToStr returns a string representation of Date using ShortDateFormat }
  2111. function DateToStr(Date: TDateTime): string;
  2112. begin
  2113. Result:=FormatDateTime('ddddd', Date);
  2114. end ;
  2115. { TimeToStr returns a string representation of Time using LongTimeFormat }
  2116. function TimeToStr(Time: TDateTime): string;
  2117. begin
  2118. Result:=FormatDateTime('tt',Time);
  2119. end ;
  2120. { DateTimeToStr returns a string representation of DateTime using LongDateTimeFormat }
  2121. Var
  2122. DateTimeToStrFormat : Array[Boolean] of string = ('c','f');
  2123. function DateTimeToStr(DateTime: TDateTime; ForceTimeIfZero : Boolean = False): string;
  2124. begin
  2125. Result:=FormatDateTime(DateTimeToStrFormat[ForceTimeIfZero], DateTime)
  2126. end ;
  2127. { StrToDate converts the string S to a TDateTime value
  2128. if S does not represent a valid date value
  2129. an EConvertError will be raised }
  2130. function IntStrToDate(Out ErrorMsg : String; const S: String; const useformat : string; separator : char): TDateTime;
  2131. Const
  2132. WhiteSpace = ' '#8#9#10#12#13;
  2133. Digits = '0123456789';
  2134. procedure FixErrorMsg(const errmarg : String);
  2135. begin
  2136. ErrorMsg:=Format(SInvalidDateFormat,[errmarg]);
  2137. end;
  2138. var
  2139. df:string;
  2140. d,m,y,ly,ld,lm:word;
  2141. n,i,len:longint;
  2142. c: integer;
  2143. dp,mp,yp,which : Byte;
  2144. s1:string;
  2145. values: array of integer;
  2146. YearMoreThenTwoDigits : boolean;
  2147. begin
  2148. SetLength(values,4);
  2149. Result:=0;
  2150. Len:=Length(S);
  2151. ErrorMsg:='';
  2152. While (Len>0) and (Pos(S[Len],WhiteSpace)>0) do
  2153. Dec(len);
  2154. if (Len=0) then
  2155. begin
  2156. FixErrorMsg(S);
  2157. exit;
  2158. end;
  2159. YearMoreThenTwoDigits := False;
  2160. if separator = #0 then
  2161. if (DateSeparator<>#0) then
  2162. separator := DateSeparator
  2163. else
  2164. separator:='-';
  2165. // Writeln('Separator: ',Separator);
  2166. df := UpperCase(useFormat);
  2167. { Determine order of D,M,Y }
  2168. yp:=0;
  2169. mp:=0;
  2170. dp:=0;
  2171. Which:=0;
  2172. i:=0;
  2173. while (i<Length(df)) and (Which<3) do
  2174. begin
  2175. inc(i);
  2176. Case df[i] of
  2177. 'Y' :
  2178. if yp=0 then
  2179. begin
  2180. Inc(Which);
  2181. yp:=which;
  2182. end;
  2183. 'M' :
  2184. if mp=0 then
  2185. begin
  2186. Inc(Which);
  2187. mp:=which;
  2188. end;
  2189. 'D' :
  2190. if dp=0 then
  2191. begin
  2192. Inc(Which);
  2193. dp:=which;
  2194. end;
  2195. end;
  2196. end;
  2197. // Writeln('YP: ',Yp,', MP: ',Mp,', DP: ',DP);
  2198. for i := 1 to 3 do
  2199. values[i] := 0;
  2200. s1 := '';
  2201. n := 0;
  2202. for i := 1 to len do
  2203. begin
  2204. if Pos(s[i],Digits)>0 then
  2205. s1 := s1 + s[i];
  2206. { space can be part of the shortdateformat, and is defaultly in slovak
  2207. windows, therefor it shouldn't be taken as separator (unless so specified)
  2208. and ignored }
  2209. if (Separator <> ' ') and (s[i] = ' ') then
  2210. Continue;
  2211. if (s[i] = separator) or ((i = len) and (Pos(s[i],Digits)>0)) then
  2212. begin
  2213. inc(n);
  2214. if n>3 then
  2215. begin
  2216. // Writeln('More than 3 separators');
  2217. FixErrorMsg(S);
  2218. exit;
  2219. end;
  2220. // Check if the year has more then two digits (if n=yp, then we are evaluating the year.)
  2221. if (n=yp) and (length(s1)>2) then YearMoreThenTwoDigits := True;
  2222. val(s1, values[n], c);
  2223. if c<>0 then
  2224. begin
  2225. // Writeln('S1 not a number ',S1);
  2226. FixErrorMsg(s);
  2227. Exit;
  2228. end;
  2229. s1 := '';
  2230. end
  2231. else if (Pos(s[i],Digits)=0) then
  2232. begin
  2233. // Writeln('Not a number at pos ',I,' ',S[i]);
  2234. FixErrorMsg(s);
  2235. Exit;
  2236. end;
  2237. end ;
  2238. // Writeln('Which : ',Which,' N : ',N);
  2239. if (Which<3) and (N>Which) then
  2240. begin
  2241. FixErrorMsg(s);
  2242. Exit;
  2243. end;
  2244. // Fill in values.
  2245. DecodeDate(Date,Ly,LM,LD);
  2246. If N=3 then
  2247. begin
  2248. y:=values[yp];
  2249. m:=values[mp];
  2250. d:=values[dp];
  2251. end
  2252. Else
  2253. begin
  2254. Y:=ly;
  2255. If n<2 then
  2256. begin
  2257. d:=values[1];
  2258. m := LM;
  2259. end
  2260. else
  2261. If dp<mp then
  2262. begin
  2263. d:=values[1];
  2264. m:=values[2];
  2265. end
  2266. else
  2267. begin
  2268. d:=values[2];
  2269. m:=values[1];
  2270. end;
  2271. end;
  2272. if (y >= 0) and (y < 100) and not YearMoreThenTwoDigits then
  2273. begin
  2274. ly := ly - TwoDigitYearCenturyWindow;
  2275. Inc(Y, ly div 100 * 100);
  2276. if (TwoDigitYearCenturyWindow > 0) and (Y < ly) then
  2277. Inc(Y, 100);
  2278. end;
  2279. if not TryEncodeDate(y, m, d, result) then
  2280. errormsg:=SErrInvalidDate;
  2281. end;
  2282. function StrToDate(const S: String; const useformat : string; separator : char): TDateTime;
  2283. Var
  2284. MSg : String;
  2285. begin
  2286. Result:=IntStrToDate(Msg,S,useFormat,Separator);
  2287. If (Msg<>'') then
  2288. Raise EConvertError.Create(Msg);
  2289. end;
  2290. function StrToDate(const S: String; separator : char): TDateTime;
  2291. begin
  2292. result := StrToDate(S,ShortDateFormat,separator)
  2293. end;
  2294. function StrToDate(const S: String): TDateTime;
  2295. begin
  2296. result := StrToDate(S,ShortDateFormat,#0);
  2297. end;
  2298. { StrToTime converts the string S to a TDateTime value
  2299. if S does not represent a valid time value an
  2300. EConvertError will be raised }
  2301. function IntStrToTime(Out ErrorMsg : String; const S: String; Len : integer; separator : char): TDateTime;
  2302. const
  2303. AMPM_None = 0;
  2304. AMPM_AM = 1;
  2305. AMPM_PM = 2;
  2306. tiHour = 0;
  2307. tiMin = 1;
  2308. tiSec = 2;
  2309. tiMSec = 3;
  2310. type
  2311. TTimeValues = array of Word;
  2312. var
  2313. AmPm: integer;
  2314. TimeValues: TTimeValues;
  2315. function SplitElements(out TimeValues: TTimeValues; out AmPm: Integer): Boolean;
  2316. //Strict version. It does not allow #32 as Separator, it will treat it as whitespace always
  2317. const
  2318. Digits = '0123456789';
  2319. var
  2320. Cur, Offset, ElemLen, Err, TimeIndex, FirstSignificantDigit: Integer;
  2321. Value: Integer;
  2322. DigitPending, MSecPending: Boolean;
  2323. AmPmStr: String;
  2324. CurChar: Char;
  2325. I : Integer;
  2326. allowedchars : string;
  2327. begin
  2328. Result := False;
  2329. AmPm := AMPM_None; //No Am or PM in string found yet
  2330. MSecPending := False;
  2331. TimeIndex := 0; //indicating which TTimeValue must be filled next
  2332. For I:=tiHour to tiMSec do
  2333. TimeValues[i]:=0;
  2334. Cur := 1;
  2335. //skip leading blanks
  2336. While (Cur < Len) and (S[Cur] =#32) do Inc(Cur);
  2337. Offset := Cur;
  2338. //First non-blank cannot be Separator or DecimalSeparator
  2339. if (Cur > Len - 1) or (S[Cur] = Separator) or (S[Cur] = Decimalseparator) then
  2340. begin
  2341. // Writeln('Error in sep S[Cur]',S[Cur],' ',separator,' ',GetDecimalSeparator);
  2342. Exit;
  2343. end;
  2344. DigitPending := (Pos(S[Cur],Digits)>0);
  2345. While (Cur <= Len) do
  2346. begin
  2347. //writeln;
  2348. // writeln('Main While loop: Cur = ',Cur,' S[Cur] = "',S[Cur],'" Len = ',Len,' separator : ',Separator);
  2349. CurChar := S[Cur];
  2350. if Pos(CurChar,Digits)>0 then
  2351. begin//Digits
  2352. //HH, MM, SS, or Msec?
  2353. // writeln('Digit: ', CurChar);
  2354. //Digits are only allowed after starting Am/PM or at beginning of string or after Separator
  2355. //and TimeIndex must be <= tiMSec
  2356. //Uncomment "or (#32 = Separator)" and it will allllow #32 as separator
  2357. if (not (DigitPending {or (#32 = Separator)})) or (TimeIndex > tiMSec) then
  2358. begin
  2359. // Writeln('DigitPending',ElemLen);
  2360. Exit;
  2361. end;
  2362. OffSet := Cur;
  2363. if (CurChar <> '0') then FirstSignificantDigit := OffSet else FirstSignificantDigit := -1;
  2364. while (Cur < Len) and (Pos(S[Cur + 1],Digits)>0) do
  2365. begin
  2366. //Mark first Digit that is not '0'
  2367. if (FirstSignificantDigit = -1) and (S[Cur] <> '0') then FirstSignificantDigit := Cur;
  2368. Inc(Cur);
  2369. end;
  2370. if (FirstSignificantDigit = -1) then FirstSignificantDigit := Cur;
  2371. ElemLen := 1+ Cur - FirstSignificantDigit;
  2372. // writeln(' S[FirstSignificantDigit] = ',S[FirstSignificantDigit], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[Offset], ElemLen);
  2373. // writeln(' Cur = ',Cur);
  2374. //this way we know that Val() will never overflow Value !
  2375. if (ElemLen <= 2) or ((ElemLen <= 3) and (TimeIndex = tiMSec) ) then
  2376. begin
  2377. Val(Copy(S,FirstSignificantDigit, ElemLen), Value, Err);
  2378. // writeln(' Value = ',Value,' HH = ',TimeValues[0],' MM = ',TimeValues[1],' SS = ',TimeValues[2],' MSec = ',Timevalues[3]);
  2379. //This is safe now, because we know Value < High(Word)
  2380. TimeValues[TimeIndex] := Value;
  2381. Inc(TimeIndex);
  2382. DigitPending := False;
  2383. end
  2384. else
  2385. begin
  2386. // Writeln('Wrong elemlen: ',ElemLen, ' timeIndex: ',timeindex);
  2387. Exit; //Value to big, so it must be a wrong timestring
  2388. end;
  2389. end//Digits
  2390. else if (CurChar = #32) then
  2391. begin
  2392. //writeln('#32');
  2393. //just skip, but we must adress this, or it will be parsed by either AM/PM or Separator
  2394. end
  2395. else if (CurChar = Separator) then
  2396. begin
  2397. // writeln('Separator ',Separator);
  2398. if DigitPending or (TimeIndex > tiSec) then
  2399. begin
  2400. // Writeln ('DigitPending ',DigitPending,' or (TimeIndex',Timeindex,' > tiSec,', tiSec,')');
  2401. Exit;
  2402. end;
  2403. DigitPending := True;
  2404. MSecPending := False;
  2405. end
  2406. else if (CurChar = DecimalSeparator) then
  2407. begin
  2408. //writeln('DecimalSeparator');
  2409. if DigitPending or MSecPending or (TimeIndex <> tiMSec) then
  2410. begin
  2411. // Writeln('DigitPending ',DigitPending,' or MSecPending ',MSecPending,' (',TimeIndex,',Timeindex, >', tiMSec,' tiSec)');
  2412. Exit;
  2413. end;
  2414. DigitPending := True;
  2415. MSecPending := True;
  2416. end
  2417. else
  2418. begin//AM/PM?
  2419. //None of the above, so this char _must_ be the start of AM/PM string
  2420. //If we already have found AM/PM or we expect a digit then then timestring must be wrong at this point
  2421. //writeln('AM/PM?');
  2422. if (AmPm <> AMPM_None) or DigitPending then
  2423. begin
  2424. // Writeln('AmPm <> AMPM_None) or DigitPending');
  2425. Exit;
  2426. end;
  2427. OffSet := Cur;
  2428. allowedchars:=DecimalSeparator+' ';
  2429. if Separator<>#0 then
  2430. allowedchars:=allowedchars+Separator;
  2431. while (Cur < Len -1) and (Pos(S[Cur + 1],AllowedChars)=0)
  2432. and (Pos(S[Cur + 1],Digits)=0) do Inc(Cur);
  2433. ElemLen := 1 + Cur - OffSet;
  2434. // writeln(' S[Offset] = ',S[1+Offset], ' S[Cur] = ',S[Cur],' ElemLen = ',ElemLen,' -> ', S[1+Offset], ElemLen);
  2435. // writeln(' Cur = ',Cur, 'S =',S);
  2436. AmPmStr := Copy(S,1+OffSet, ElemLen);
  2437. // writeln('AmPmStr = ',ampmstr,' (',length(ampmstr),')');
  2438. //We must compare to TimeAMString before hardcoded 'AM' for delphi compatibility
  2439. //Also it is perfectly legal, though insane to have TimeAMString = 'PM' and vice versa
  2440. if (CompareText(AmPmStr, TimeAMString) = 0) then AmPm := AMPM_AM
  2441. else if (CompareText(AmPmStr, TimePMString) = 0) then AmPm := AMPM_PM
  2442. else if (CompareText(AmPmStr, 'AM') = 0) then AmPm := AMPM_AM
  2443. else if (CompareText(AmPmStr, 'PM') = 0) then AmPm := AMPM_PM
  2444. else
  2445. begin
  2446. // Writeln('No timestring ',AmPmStr);
  2447. Exit; //If text does not match any of these, timestring must be wrong;
  2448. end;
  2449. //if AM/PM is at beginning of string, then a digit is mandatory after it
  2450. if (TimeIndex = tiHour) then
  2451. begin
  2452. DigitPending := True;
  2453. end
  2454. //otherwise, no more TimeValues allowed after this
  2455. else
  2456. begin
  2457. TimeIndex := tiMSec + 1;
  2458. DigitPending := False;
  2459. end;
  2460. end;//AM/PM
  2461. Inc(Cur)
  2462. end;//while
  2463. //If we arrive here, parsing the elements has been successfull
  2464. //if not at least Hours specified then input is not valid
  2465. //when am/pm is specified Hour must be <= 12 and not 0
  2466. if (TimeIndex = tiHour) or ((AmPm <> AMPM_None) and ((TimeValues[tiHour] > 12) or (TimeValues[tiHour] = 0))) or DigitPending then
  2467. Exit;
  2468. Result := True;
  2469. end;
  2470. begin
  2471. setlength(timevalues,4);
  2472. if separator = #0 then
  2473. if (TimeSeparator<>#0) then
  2474. separator := TimeSeparator
  2475. else
  2476. separator:=':';
  2477. AmPm := AMPM_None;
  2478. if not SplitElements(TimeValues, AmPm) then
  2479. begin
  2480. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2481. Exit;
  2482. end;
  2483. if (AmPm=AMPM_PM) and (TimeValues[tiHour]<>12) then Inc(TimeValues[tiHour], 12)
  2484. else if (AmPm=AMPM_AM) and (TimeValues[tiHour]=12) then TimeValues[tiHour]:=0;
  2485. // Writeln( TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec]);
  2486. if not TryEncodeTime(TimeValues[tiHour], TimeValues[tiMin], TimeValues[tiSec], TimeValues[tiMSec], result) Then
  2487. ErrorMsg:=Format(SErrInvalidTimeFormat,[S]);
  2488. end ;
  2489. function StrToTime(const s: String; separator : char): TDateTime;
  2490. Var
  2491. Msg : String;
  2492. begin
  2493. Result:=IntStrToTime(Msg,S,Length(S),Separator);
  2494. If (Msg<>'') then
  2495. Raise EConvertError.Create(Msg);
  2496. end;
  2497. function StrToTime(const s: String): TDateTime;
  2498. begin
  2499. result:= StrToTime(s, TimeSeparator);
  2500. end;
  2501. { StrToDateTime converts the string S to a TDateTime value
  2502. if S does not represent a valid date and/or time value
  2503. an EConvertError will be raised }
  2504. function SplitDateTimeStr(DateTimeStr: String; out DateStr, TimeStr: String): Integer;
  2505. { Helper function for StrToDateTime
  2506. Pre-condition
  2507. Date is before Time
  2508. If either Date or Time is omitted then see what fits best, a time or a date (issue #0020522)
  2509. Date and Time are separated by whitespace (space Tab, Linefeed or carriage return)
  2510. FS.DateSeparator can be the same as FS.TimeSeparator (issue #0020522)
  2511. If they are both #32 and TrimWhite(DateTimeStr) contains a #32 a date is assumed.
  2512. Post-condition
  2513. DateStr holds date as string or is empty
  2514. TimeStr holds time as string or is empty
  2515. Result = number of strings returned, 0 = error
  2516. }
  2517. const
  2518. WhiteSpace = #9#10#13#32;
  2519. var
  2520. p: Integer;
  2521. DummyDT: TDateTime;
  2522. begin
  2523. Result := 0;
  2524. DateStr := '';
  2525. TimeStr := '';
  2526. DateTimeStr := Trim(DateTimeStr);
  2527. if Length(DateTimeStr) = 0 then exit;
  2528. if (DateSeparator = #32) and (TimeSeparator = #32) and (Pos(#32, DateTimeStr) > 0) then
  2529. begin
  2530. DateStr:=DateTimeStr;
  2531. {
  2532. Assume a date: dd [mm [yy]].
  2533. Really fancy would be counting the number of whitespace occurrences and decide
  2534. and split accordingly
  2535. }
  2536. Exit(1);
  2537. end;
  2538. p:=1;
  2539. //find separator
  2540. if (DateSeparator<>#32) then
  2541. begin
  2542. while (p<Length(DateTimeStr)) and (not (Pos(DateTimeStr[p+1],WhiteSpace)>0)) do
  2543. Inc(p);
  2544. end
  2545. else
  2546. begin
  2547. p:=Pos(TimeSeparator, DateTimeStr);
  2548. if (p<>0) then
  2549. repeat
  2550. Dec(p);
  2551. until (p=0) or (Pos(DateTimeStr[p],WhiteSpace)>0);
  2552. end;
  2553. //Always fill DateStr, it eases the algorithm later
  2554. if (p=0) then
  2555. p:=Length(DateTimeStr);
  2556. DateStr:=Copy(DateTimeStr,1,p);
  2557. TimeStr:=Trim(Copy(DateTimeStr,p+1,100));
  2558. if (Length(TimeStr)<>0) then
  2559. Result:=2
  2560. else
  2561. begin
  2562. Result:=1; //found 1 string
  2563. // 2 cases when DateTimeStr only contains a time:
  2564. // Date/time separator differ, and string contains a timeseparator
  2565. // Date/time separators are equal, but transformation to date fails.
  2566. if ((DateSeparator<>TimeSeparator) and (Pos(TimeSeparator,DateStr) > 0))
  2567. or ((DateSeparator=TimeSeparator) and (not TryStrToDate(DateStr, DummyDT))) then
  2568. begin
  2569. TimeStr := DateStr;
  2570. DateStr := '';
  2571. end;
  2572. end;
  2573. end;
  2574. function StrToDateTime(const s: String): TDateTime;
  2575. var
  2576. TimeStr, DateStr: String;
  2577. PartsFound: Integer;
  2578. begin
  2579. PartsFound := SplitDateTimeStr(S, DateStr, TimeStr);
  2580. case PartsFound of
  2581. 0: Result:=StrToDate('');
  2582. 1: if (Length(DateStr) > 0) then
  2583. Result := StrToDate(DateStr,ShortDateFormat,DateSeparator)
  2584. else
  2585. Result := StrToTime(TimeStr);
  2586. 2: Result := ComposeDateTime(StrTodate(DateStr,ShortDateFormat,DateSeparator),
  2587. StrToTime(TimeStr));
  2588. end;
  2589. end;
  2590. Function FormatDateTime(const FormatStr: string; const DateTime: TDateTime) : String;
  2591. procedure StoreStr(APos,Len: Integer);
  2592. begin
  2593. // Writeln('StoreStr: ',Result,'+',Copy(FormatStr,APos,Len));
  2594. Result:=Result+Copy(FormatStr,APos,Len);
  2595. end;
  2596. procedure StoreString(const AStr: string);
  2597. begin
  2598. // Writeln('StoreString: ',Result,'+',AStr);
  2599. Result:=Result+AStr;
  2600. end;
  2601. procedure StoreInt(Value, Digits: Integer);
  2602. var
  2603. S: string;
  2604. begin
  2605. S:=IntToStr(Value);
  2606. While (Length(S)<Digits) do
  2607. S:='0'+S;
  2608. StoreString(S);
  2609. end;
  2610. var
  2611. Year, Month, Day, DayOfWeek, Hour, Minute, Second, MilliSecond: word;
  2612. procedure StoreFormat(const FormatStr: string; Nesting: Integer; TimeFlag: Boolean);
  2613. var
  2614. Token, lastformattoken, prevlasttoken: char;
  2615. Count: integer;
  2616. Clock12: boolean;
  2617. tmp: integer;
  2618. isInterval: Boolean;
  2619. P,FormatCurrent,FormatEnd : Integer;
  2620. begin
  2621. if Nesting > 1 then // 0 is original string, 1 is included FormatString
  2622. Exit;
  2623. FormatCurrent := 1;
  2624. FormatEnd := Length(FormatStr);
  2625. Clock12 := false;
  2626. isInterval := false;
  2627. // look for unquoted 12-hour clock token
  2628. P:=1;
  2629. while P<=FormatEnd do
  2630. begin
  2631. Token := FormatStr[P];
  2632. case Token of
  2633. '''', '"':
  2634. begin
  2635. Inc(P);
  2636. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2637. Inc(P);
  2638. end;
  2639. 'A', 'a':
  2640. begin
  2641. if (CompareText(Copy(FormatStr,P,3),'A/P')=0) or
  2642. (CompareText(Copy(FormatStr,P,4),'AMPM')=0) or
  2643. (CompareText(Copy(FormatStr,P,5),'AM/PM')=0) then
  2644. begin
  2645. Clock12 := true;
  2646. break;
  2647. end;
  2648. end;
  2649. end; // case
  2650. Inc(P);
  2651. end ;
  2652. token := #255;
  2653. lastformattoken := ' ';
  2654. prevlasttoken := 'H';
  2655. while FormatCurrent <= FormatEnd do
  2656. begin
  2657. Token := UpperCase(FormatStr[FormatCurrent])[1];
  2658. // Writeln('Treating token at pos ',FormatCurrent,', : ',Token,' (',FormatStr,')');
  2659. Count := 1;
  2660. P := FormatCurrent + 1;
  2661. case Token of
  2662. '''', '"':
  2663. begin
  2664. while (P < FormatEnd) and (FormatStr[P]<>Token) do
  2665. Inc(P);
  2666. Inc(P);
  2667. Count := P - FormatCurrent;
  2668. StoreStr(FormatCurrent + 1, Count - 2);
  2669. end ;
  2670. 'A':
  2671. begin
  2672. if CompareText(Copy(FormatStr,FormatCurrent,4), 'AMPM') = 0 then
  2673. begin
  2674. Count := 4;
  2675. if Hour < 12 then
  2676. StoreString(TimeAMString)
  2677. else
  2678. StoreString(TimePMString);
  2679. end
  2680. else if CompareText(Copy(FormatStr,FormatCurrent,5), 'AM/PM') = 0 then
  2681. begin
  2682. Count := 5;
  2683. if Hour < 12 then StoreStr(FormatCurrent, 2)
  2684. else StoreStr(FormatCurrent+3, 2);
  2685. end
  2686. else if CompareText(Copy(FormatStr,FormatCurrent,3), 'A/P') = 0 then
  2687. begin
  2688. Count := 3;
  2689. if Hour < 12 then StoreStr(FormatCurrent, 1)
  2690. else StoreStr(FormatCurrent+2, 1);
  2691. end
  2692. else
  2693. raise EConvertError.Create('Illegal character in format string');
  2694. end ;
  2695. '/':
  2696. begin
  2697. // Writeln('Detected date separator');
  2698. StoreString(DateSeparator);
  2699. end;
  2700. ':': StoreString(TimeSeparator);
  2701. ' ', 'C', 'D', 'H', 'M', 'N', 'S', 'T', 'Y', 'Z', 'F' :
  2702. begin
  2703. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2704. while (P <= FormatEnd) and (UpperCase(FormatStr[P]) = Token) do
  2705. Inc(P);
  2706. Count := P - FormatCurrent;
  2707. // Writeln(FormatCurrent,' Special Token: ',Token,', Count: ',Count,', P: ',P);
  2708. case Token of
  2709. ' ': StoreStr(FormatCurrent, Count);
  2710. 'Y': begin
  2711. if Count > 2 then
  2712. StoreInt(Year, 4)
  2713. else
  2714. StoreInt(Year mod 100, 2);
  2715. end;
  2716. 'M': begin
  2717. if isInterval and ((prevlasttoken = 'H') or TimeFlag) then
  2718. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2719. else
  2720. if (lastformattoken = 'H') or TimeFlag then
  2721. begin
  2722. if Count = 1 then
  2723. StoreInt(Minute, 0)
  2724. else
  2725. StoreInt(Minute, 2);
  2726. end
  2727. else
  2728. begin
  2729. case Count of
  2730. 1: StoreInt(Month, 0);
  2731. 2: StoreInt(Month, 2);
  2732. 3: StoreString(ShortMonthNames[Month]);
  2733. else
  2734. StoreString(LongMonthNames[Month]);
  2735. end;
  2736. end;
  2737. end;
  2738. 'D': begin
  2739. case Count of
  2740. 1: StoreInt(Day, 0);
  2741. 2: StoreInt(Day, 2);
  2742. 3: StoreString(ShortDayNames[DayOfWeek]);
  2743. 4: StoreString(LongDayNames[DayOfWeek]);
  2744. 5: StoreFormat(ShortDateFormat, Nesting+1, False);
  2745. else
  2746. StoreFormat(LongDateFormat, Nesting+1, False);
  2747. end ;
  2748. end ;
  2749. 'H':
  2750. if isInterval then
  2751. StoreInt(Hour + trunc(abs(DateTime))*24, 0)
  2752. else
  2753. if Clock12 then
  2754. begin
  2755. tmp := hour mod 12;
  2756. if tmp=0 then tmp:=12;
  2757. if Count = 1 then
  2758. StoreInt(tmp, 0)
  2759. else
  2760. StoreInt(tmp, 2);
  2761. end
  2762. else begin
  2763. if Count = 1 then
  2764. StoreInt(Hour, 0)
  2765. else
  2766. StoreInt(Hour, 2);
  2767. end;
  2768. 'N': if isInterval then
  2769. StoreInt(Minute + (Hour + trunc(abs(DateTime))*24)*60, 0)
  2770. else
  2771. if Count = 1 then
  2772. StoreInt(Minute, 0)
  2773. else
  2774. StoreInt(Minute, 2);
  2775. 'S': if isInterval then
  2776. StoreInt(Second + (Minute + (Hour + trunc(abs(DateTime))*24)*60)*60, 0)
  2777. else
  2778. if Count = 1 then
  2779. StoreInt(Second, 0)
  2780. else
  2781. StoreInt(Second, 2);
  2782. 'Z': if Count = 1 then
  2783. StoreInt(MilliSecond, 0)
  2784. else
  2785. StoreInt(MilliSecond, 3);
  2786. 'T': if Count = 1 then
  2787. StoreFormat(ShortTimeFormat, Nesting+1, True)
  2788. else
  2789. StoreFormat(LongTimeFormat, Nesting+1, True);
  2790. 'C': begin
  2791. StoreFormat(ShortDateFormat, Nesting+1, False);
  2792. if (Hour<>0) or (Minute<>0) or (Second<>0) then
  2793. begin
  2794. StoreString(' ');
  2795. StoreFormat(LongTimeFormat, Nesting+1, True);
  2796. end;
  2797. end;
  2798. 'F': begin
  2799. StoreFormat(ShortDateFormat, Nesting+1, False);
  2800. StoreString(' ');
  2801. StoreFormat(LongTimeFormat, Nesting+1, True);
  2802. end;
  2803. end;
  2804. prevlasttoken := lastformattoken;
  2805. lastformattoken := token;
  2806. end;
  2807. else
  2808. StoreString(Token);
  2809. end ;
  2810. Inc(FormatCurrent, Count);
  2811. end;
  2812. end;
  2813. begin
  2814. DecodeDateFully(DateTime, Year, Month, Day, DayOfWeek);
  2815. DecodeTime(DateTime, Hour, Minute, Second, MilliSecond);
  2816. // Writeln(DateTime,'->',Year,',', Month, ',',Day, ',',DayOfWeek,',',Hour, ',',Minute, ',',Second, ',',MilliSecond);
  2817. if FormatStr <> '' then
  2818. StoreFormat(FormatStr, 0, False)
  2819. else
  2820. StoreFormat('C', 0, False);
  2821. end ;
  2822. function CurrentYear: Word;
  2823. begin
  2824. Result:=TJSDate.New().FullYear;
  2825. end;
  2826. function TryStrToDate(const S: String; out Value: TDateTime): Boolean;
  2827. begin
  2828. Result:=TryStrToDate(S,Value,ShortDateFormat,#0);
  2829. end;
  2830. function TryStrToDate(const S: String; out Value: TDateTime; separator : char): Boolean;
  2831. begin
  2832. Result:=TryStrToDate(S,Value,ShortDateFormat,Separator);
  2833. end;
  2834. function TryStrToDate(const S: String; out Value: TDateTime;
  2835. const useformat : string; separator : char = #0): Boolean;
  2836. Var
  2837. Msg : String;
  2838. begin
  2839. Result:=Length(S)<>0;
  2840. If Result then
  2841. begin
  2842. Value:=IntStrToDate(Msg,S,useformat,Separator);
  2843. Result:=(Msg='');
  2844. end;
  2845. end;
  2846. function TryStrToTime(const S: String; out Value: TDateTime; separator : char): Boolean;
  2847. Var
  2848. Msg : String;
  2849. begin
  2850. Result:=Length(S)<>0;
  2851. If Result then
  2852. begin
  2853. Value:=IntStrToTime(Msg,S,Length(S),Separator);
  2854. Result:=(Msg='');
  2855. end;
  2856. end;
  2857. function TryStrToTime(const S: String; out Value: TDateTime): Boolean;
  2858. begin
  2859. result:=TryStrToTime(S,Value,#0);
  2860. end;
  2861. function TryStrToDateTime(const S: String; out Value: TDateTime): Boolean;
  2862. var
  2863. I: integer;
  2864. dtdate, dttime :TDateTime;
  2865. begin
  2866. result:=false;
  2867. I:=Pos(TimeSeparator,S);
  2868. If (I>0) then
  2869. begin
  2870. While (I>0) and (S[I]<>' ') do
  2871. Dec(I);
  2872. If I>0 then
  2873. begin
  2874. if not TryStrToDate(Copy(S,1,I-1),dtdate) then
  2875. exit;
  2876. if not TryStrToTime(Copy(S,i+1, Length(S)-i),dttime) then
  2877. exit;
  2878. Value:=ComposeDateTime(dtdate,dttime);
  2879. result:=true;
  2880. end
  2881. else
  2882. result:=TryStrToTime(s,Value);
  2883. end
  2884. else
  2885. result:=TryStrToDate(s,Value);
  2886. end;
  2887. function StrToDateDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2888. begin
  2889. result := StrToDateDef(S,DefValue,#0);
  2890. end;
  2891. function StrToTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2892. begin
  2893. result := StrToTimeDef(S,DefValue,#0);
  2894. end;
  2895. function StrToDateTimeDef(const S: String; const Defvalue : TDateTime): TDateTime;
  2896. begin
  2897. if not TryStrToDateTime(s,Result) Then
  2898. result:=defvalue;
  2899. end;
  2900. function StrToDateDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  2901. begin
  2902. if not TryStrToDate(s,Result, separator) Then
  2903. result:=defvalue;
  2904. end;
  2905. function StrToTimeDef(const S: String; const Defvalue : TDateTime; separator : char): TDateTime;
  2906. begin
  2907. if not TryStrToTime(s,Result, separator) Then
  2908. result:=defvalue;
  2909. end;
  2910. procedure ReplaceTime(var dati:TDateTime; NewTime : TDateTime);
  2911. begin
  2912. dati:= ComposeDateTime(dati, newtime);
  2913. end;
  2914. procedure ReplaceDate(var DateTime: TDateTime; const NewDate: TDateTime);
  2915. var
  2916. tmp : TDateTime;
  2917. begin
  2918. tmp:=NewDate;
  2919. ReplaceTime(tmp,DateTime);
  2920. DateTime:=tmp;
  2921. end;
  2922. Function FloatToDateTime (Const Value : Extended) : TDateTime;
  2923. begin
  2924. If (Value<MinDateTime) or (Value>MaxDateTime) then
  2925. Raise EConvertError.CreateFmt (SInvalidDateTime,[FloatToStr(Value)]);
  2926. Result:=Value;
  2927. end;
  2928. { ---------------------------------------------------------------------
  2929. Interface related
  2930. ---------------------------------------------------------------------}
  2931. function Supports(const Instance: IInterface; const AClass: TClass; out Obj
  2932. ): Boolean;
  2933. begin
  2934. Result := (Instance<>nil) and (Instance.QueryInterface(IObjectInstance,Obj)=S_OK)
  2935. and (TObject(Obj).InheritsFrom(AClass));
  2936. end;
  2937. function Supports(const Instance: IInterface; const IID: TGUID; out Intf
  2938. ): Boolean;
  2939. begin
  2940. Result:=(Instance<>nil) and (Instance.QueryInterface(IID,Intf)=S_OK);
  2941. end;
  2942. function Supports(const Instance: TObject; const IID: TGUID; out Intf
  2943. ): Boolean;
  2944. begin
  2945. Result:=(Instance<>nil) and Instance.GetInterface(IID,Intf);
  2946. end;
  2947. function Supports(const Instance: TObject; const IID: TGuidString; out Intf
  2948. ): Boolean;
  2949. begin
  2950. Result:=(Instance<>nil) and Instance.GetInterfaceByStr(IID,Intf);
  2951. end;
  2952. function Supports(const Instance: IInterface; const AClass: TClass): Boolean;
  2953. var
  2954. Temp: TObject;
  2955. begin
  2956. Result:=Supports(Instance,AClass,Temp);
  2957. end;
  2958. function Supports(const Instance: IInterface; const IID: TGUID): Boolean;
  2959. var
  2960. Temp: IInterface;
  2961. begin
  2962. Result:=Supports(Instance,IID,Temp);
  2963. end;
  2964. function Supports(const Instance: TObject; const IID: TGUID): Boolean;
  2965. var
  2966. Temp: TJSObject;
  2967. begin
  2968. Result:=Supports(Instance,IID,Temp);
  2969. asm
  2970. if (Temp && Temp.$kind==='com') Temp._Release();
  2971. end;
  2972. end;
  2973. function Supports(const Instance: TObject; const IID: TGuidString): Boolean;
  2974. var
  2975. Temp: TJSObject;
  2976. begin
  2977. Result:=Supports(Instance,IID,Temp);
  2978. asm
  2979. if (Temp && Temp.$kind==='com') Temp._Release();
  2980. end;
  2981. end;
  2982. function Supports(const AClass: TClass; const IID: TGUID): Boolean;
  2983. var
  2984. maps: JSValue;
  2985. begin
  2986. if AClass=nil then exit(false);
  2987. maps := TJSObject(AClass)['$intfmaps'];
  2988. if not maps then exit(false);
  2989. if TJSObject(maps)[GUIDToString(IID)] then exit(true);
  2990. Result:=false;
  2991. end;
  2992. function Supports(const AClass: TClass; const IID: TGuidString): Boolean;
  2993. var
  2994. maps: JSValue;
  2995. begin
  2996. if AClass=nil then exit(false);
  2997. maps := TJSObject(AClass)['$intfmaps'];
  2998. if not maps then exit(false);
  2999. if TJSObject(maps)[uppercase(IID)] then exit(true);
  3000. Result:=false;
  3001. end;
  3002. function TryStringToGUID(const s: string; out Guid: TGUID): Boolean;
  3003. var
  3004. re: TJSRegexp;
  3005. begin
  3006. if Length(s)<>38 then Exit(False);
  3007. re:=TJSRegexp.new('^\{[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\}$');
  3008. Result:=re.test(s);
  3009. if not Result then
  3010. begin
  3011. Guid.D1:=0;
  3012. exit;
  3013. end;
  3014. asm
  3015. rtl.strToGUIDR(s,Guid.get());
  3016. end;
  3017. Result:=true;
  3018. end;
  3019. function StringToGUID(const S: string): TGUID;
  3020. begin
  3021. if not TryStringToGUID(S, Result) then
  3022. raise EConvertError.CreateFmt(SInvalidGUID, [S]);
  3023. end;
  3024. function GUIDToString(const guid: TGUID): string;
  3025. begin
  3026. Result:=System.GUIDToString(guid);
  3027. end;
  3028. function IsEqualGUID(const guid1, guid2: TGUID): Boolean;
  3029. var
  3030. i: integer;
  3031. begin
  3032. if (guid1.D1<>guid2.D1) or (guid1.D2<>guid2.D2) or (guid1.D3<>guid2.D3) then
  3033. exit(false);
  3034. for i:=0 to 7 do if guid1.D4[i]<>guid2.D4[i] then exit(false);
  3035. Result:=true;
  3036. end;
  3037. function GuidCase(const guid: TGUID; const List: array of TGuid): Integer;
  3038. begin
  3039. for Result := High(List) downto 0 do
  3040. if IsEqualGUID(guid, List[Result]) then
  3041. Exit;
  3042. Result := -1;
  3043. end;
  3044. { ---------------------------------------------------------------------
  3045. Integer/Ordinal related
  3046. ---------------------------------------------------------------------}
  3047. Function TryStrToInt(const S : String; Out res : Integer) : Boolean;
  3048. Var
  3049. NI : NativeInt;
  3050. begin
  3051. Result:=TryStrToInt(S,NI);
  3052. if Result then
  3053. res:=NI;
  3054. end;
  3055. Function TryStrToInt(const S : String; Out res : NativeInt) : Boolean;
  3056. Var
  3057. Radix : Integer = 10;
  3058. F,N : String;
  3059. J : JSValue;
  3060. begin
  3061. N:=S;
  3062. F:=Copy(N,1,1);
  3063. if (F='$') then
  3064. Radix:=16
  3065. else if (F='&') then
  3066. Radix:=8
  3067. else if (F='%') then
  3068. Radix:=2;
  3069. If Radix<>10 then
  3070. Delete(N,1,1);
  3071. J:=parseInt(N,Radix);
  3072. Result:=Not jsIsNan(j);
  3073. if Result then
  3074. res:=NativeInt(J);
  3075. end;
  3076. Function StrToIntDef(const S : String; Const aDef : Integer) : Integer;
  3077. Var
  3078. R : NativeInt;
  3079. begin
  3080. if TryStrToInt(S,R) then
  3081. Result:=R
  3082. else
  3083. Result:=aDef;
  3084. end;
  3085. Function StrToIntDef(const S : String; Const aDef : NativeInt) : NativeInt;
  3086. Var
  3087. R : NativeInt;
  3088. begin
  3089. if TryStrToInt(S,R) then
  3090. Result:=R
  3091. else
  3092. Result:=aDef;
  3093. end;
  3094. Function StrToInt(const S : String) : Integer;
  3095. Var
  3096. R : NativeInt;
  3097. begin
  3098. if not TryStrToInt(S,R) then
  3099. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3100. Result:=R;
  3101. end;
  3102. Function StrToNativeInt(const S : String) : NativeInt;
  3103. begin
  3104. if not TryStrToInt(S,Result) then
  3105. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3106. end;
  3107. Function StrToInt64(const S : String) : NativeLargeInt;
  3108. Var
  3109. N : NativeInt;
  3110. begin
  3111. if not TryStrToInt(S,N) then
  3112. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3113. Result:=N;
  3114. end;
  3115. Function TryStrToInt64(const S : String; Out res : NativeLargeInt) : Boolean;
  3116. Var
  3117. R : nativeint;
  3118. begin
  3119. Result:=TryStrToInt(S,R);
  3120. If Result then
  3121. Res:=R;
  3122. end;
  3123. Function StrToInt64Def(const S : String; ADefault : NativeLargeInt) : NativeLargeInt;
  3124. begin
  3125. if TryStrToInt64(S,Result) then
  3126. Result:=ADefault;
  3127. end;
  3128. Function StrToQWord(const S : String) : NativeLargeUInt;
  3129. Var
  3130. N : NativeInt;
  3131. begin
  3132. if (not TryStrToInt(S,N)) or (N<0) then
  3133. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3134. Result:=N;
  3135. end;
  3136. Function TryStrToQWord(const S : String; Out res : NativeLargeUInt) : Boolean;
  3137. Var
  3138. R : nativeint;
  3139. begin
  3140. Result:=TryStrToInt(S,R) and (R>=0);
  3141. If Result then
  3142. Res:=R;
  3143. end;
  3144. Function StrToQWordDef(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3145. begin
  3146. if Not TryStrToQword(S,Result) then
  3147. Result:=ADefault;
  3148. end;
  3149. Function StrToUInt64(const S : String) : NativeLargeUInt;
  3150. Var
  3151. N : NativeInt;
  3152. begin
  3153. if (not TryStrToInt(S,N)) or (N<0) then
  3154. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3155. Result:=N;
  3156. end;
  3157. Function TryStrToUInt64(const S : String; Out res : NativeLargeUInt) : Boolean;
  3158. Var
  3159. R : nativeint;
  3160. begin
  3161. Result:=TryStrToInt(S,R) and (R>=0);
  3162. If Result then
  3163. Res:=R;
  3164. end;
  3165. Function StrToUInt64Def(const S : String; ADefault : NativeLargeUInt) : NativeLargeUInt;
  3166. begin
  3167. if Not TryStrToUInt64(S,Result) then
  3168. Result:=ADefault;
  3169. end;
  3170. Function TryStrToDWord(const S : String; Out res : DWord) : Boolean;
  3171. Var
  3172. R : nativeint;
  3173. begin
  3174. Result:=TryStrToInt(S,R) and (R>=0) and (R<=DWord($FFFFFFFF));
  3175. If Result then
  3176. Res:=R;
  3177. end;
  3178. Function StrToDWord(const S : String) : DWord;
  3179. begin
  3180. if not TryStrToDWord(S,Result) then
  3181. Raise EConvertError.CreateFmt(SErrInvalidInteger,[S]);
  3182. end;
  3183. Function StrToDWordDef(const S : String; ADefault : DWord) : DWord;
  3184. begin
  3185. if Not TryStrToDWord(S,Result) then
  3186. Result:=ADefault;
  3187. end;
  3188. function IntToHex(Value: NativeInt; Digits: integer): string;
  3189. const
  3190. HexDigits = '0123456789ABCDEF';
  3191. begin
  3192. If Digits=0 then
  3193. Digits:=1;
  3194. Result:='';
  3195. While Value>0 do
  3196. begin
  3197. result:=HexDigits[(value and 15)+1]+Result;
  3198. value := value shr 4;
  3199. end ;
  3200. while (Length(Result)<Digits) do
  3201. Result:='0'+Result;
  3202. end;
  3203. { TFormatSettings }
  3204. function TFormatSettings.GetDateSeparator: char;
  3205. begin
  3206. Result := SysUtils.DateSeparator;
  3207. end;
  3208. function TFormatSettings.GetDecimalSeparator: string;
  3209. begin
  3210. Result := SysUtils.DecimalSeparator;
  3211. end;
  3212. function TFormatSettings.GetLongDateFormat: string;
  3213. begin
  3214. Result := SysUtils.LongDateFormat;
  3215. end;
  3216. function TFormatSettings.GetLongDayNames: TDayNames;
  3217. begin
  3218. Result:=Sysutils.LongDayNames;
  3219. end;
  3220. function TFormatSettings.GetLongMonthNames: TMonthNames;
  3221. begin
  3222. Result:=Sysutils.LongMonthNames;
  3223. end;
  3224. function TFormatSettings.GetLongTimeFormat: string;
  3225. begin
  3226. Result := SysUtils.LongTimeFormat;
  3227. end;
  3228. function TFormatSettings.GetShortDateFormat: string;
  3229. begin
  3230. Result := SysUtils.ShortDateFormat;
  3231. end;
  3232. function TFormatSettings.GetShortDayNames: TDayNames;
  3233. begin
  3234. Result:=Sysutils.ShortDayNames;
  3235. end;
  3236. function TFormatSettings.GetShortMonthNames: TMonthNames;
  3237. begin
  3238. Result:=Sysutils.ShortMonthNames;
  3239. end;
  3240. function TFormatSettings.GetShortTimeFormat: string;
  3241. begin
  3242. Result := SysUtils.ShortTimeFormat;
  3243. end;
  3244. function TFormatSettings.GetThousandSeparator: string;
  3245. begin
  3246. Result := SysUtils.ThousandSeparator;
  3247. end;
  3248. function TFormatSettings.GetTimeAMString: string;
  3249. begin
  3250. Result := SysUtils.TimeAMString;
  3251. end;
  3252. function TFormatSettings.GetTimePMString: string;
  3253. begin
  3254. Result := SysUtils.TimePMString;
  3255. end;
  3256. function TFormatSettings.GetTimeSeparator: char;
  3257. begin
  3258. Result := SysUtils.TimeSeparator;
  3259. end;
  3260. procedure TFormatSettings.SetDateSeparator(const Value: char);
  3261. begin
  3262. SysUtils.DateSeparator := Value;
  3263. end;
  3264. procedure TFormatSettings.SetDecimalSeparator(const Value: string);
  3265. begin
  3266. SysUtils.DecimalSeparator := Value;
  3267. end;
  3268. procedure TFormatSettings.SetLongDateFormat(const Value: string);
  3269. begin
  3270. SysUtils.LongDateFormat := Value;
  3271. end;
  3272. procedure TFormatSettings.SetLongDayNames(AValue: TDayNames);
  3273. begin
  3274. SysUtils.LongDayNames:=AValue;
  3275. end;
  3276. procedure TFormatSettings.SetLongMonthNames(AValue: TMonthNames);
  3277. begin
  3278. SysUtils.LongMonthNames:=AValue;
  3279. end;
  3280. procedure TFormatSettings.SetLongTimeFormat(const Value: string);
  3281. begin
  3282. SysUtils.LongTimeFormat := Value;
  3283. end;
  3284. procedure TFormatSettings.SetShortDateFormat(const Value: string);
  3285. begin
  3286. SysUtils.ShortDateFormat := Value;
  3287. end;
  3288. procedure TFormatSettings.SetShortDayNames(AValue: TDayNames);
  3289. begin
  3290. SysUtils.ShortDayNames:=AValue;
  3291. end;
  3292. procedure TFormatSettings.SetShortMonthNames(AValue: TMonthNames);
  3293. begin
  3294. SysUtils.ShortMonthNames:=AValue;
  3295. end;
  3296. procedure TFormatSettings.SetShortTimeFormat(const Value: string);
  3297. begin
  3298. SysUtils.ShortTimeFormat := Value;
  3299. end;
  3300. procedure TFormatSettings.SetThousandSeparator(const Value: string);
  3301. begin
  3302. SysUtils.ThousandSeparator := Value;
  3303. end;
  3304. procedure TFormatSettings.SetTimeAMString(const Value: string);
  3305. begin
  3306. SysUtils.TimeAMString := Value;
  3307. end;
  3308. procedure TFormatSettings.SetTimePMString(const Value: string);
  3309. begin
  3310. SysUtils.TimePMString := Value;
  3311. end;
  3312. procedure TFormatSettings.SetTimeSeparator(const Value: char);
  3313. begin
  3314. SysUtils.TimeSeparator := Value;
  3315. end;
  3316. initialization
  3317. FormatSettings := TFormatSettings.Create;
  3318. end.