sysutils.pas 92 KB

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