sysutils.pas 98 KB

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