sysutils.pas 100 KB

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