Go to day home page Methods are initially capitalised. Properties are initially lower case. 'private' items are initially underscored.

DAYo.js

D/a/y object
signature 0..7
sign 0..1 (1=-ve)
yr 0..4095 (0=missing)
mo 0..12 (0=missing 1=Jan)
dy 0..31 (0=missing 1=first )
errorCode 0..7
whatWentWrongStr NOT PERSISTENT OR CLONED

DAYo

44constructorInitialiser
Instructions
Overall constructor
Creates a DAYo object with Intitaliser as the data
and an optional Instructions to tweak or command
In all cases the triksy grunt work is done by
methods with the name convention ._Read...()
Look at the documentation of those methods for details
Initialiser is a
string, number, Javascript Date, (see below)
a DAYo to clone or
an array [Signature,Sign,Y,M,D,Error code]
Instructions depend on type of Initialiser
number : DAYu.force32Bits ('32') default
DAYu.forceJulian ('J')
DAYu.forceTimestamp ('STAMP')
string : An array ..................... _ReadUsingTemplate
DAYu.forceYMD ('YMD') read just Y-M-D
DAYu.forceYMDHMS ('YMDHMS') read extended using time bits
DAYu.forceTilde ('~') read simple tilde format
default is do the best we can looking for common patterns
Date DAYu.forceYMDHMS ('YMDHMS') read extended using time bits
default is only use Y M D to make a fully specified DAY
1795AddDaysNoDays add (-ve = subtract) a given number of days from a specific CAL date
returns a new DAYo
NK,EOT,BOT return themselves
Anything else returns NV
AR1 When adding days alone to a SPECIFIC date:
Count according to the real calendar.
AR2 Use method a.
*** If AR2b is required use Tinterval method *** 'D'
@@@ INT routine needs attention
!@@@| Lots wrong with this routine
1846AddMonthsNoMonths add ( -ve = subtract ) specified number of months
return new DAYo
AR3:
When adding months alone to a date:
Convert the days part of the date into fractions of that month.
Then add the months, carrying base 12 as required.
Now convert the fraction back into days according
to the actual length of the new month.
May throw error if trying to add months to just a year but this
will be ignored if NoMonths is a multiple of 12
  • Can't add month to bare year in DAYo.AddMonths()
  • Can't add month to day-only float in DAYo.AddMonths()
1897AddYearsNoYears add ( -ve = subtract ) specified number of years
See .AddMonths()
1668AfterAday compares the logical values of the dates.
Returns true if THIS is AFTER the ARGUMENT
See Before()
1405AsDays Convert an interval into days
Result may be fractional and negative
1633BeforeAday Compares the logical values of the dates.
Returns true if THIS is DEFINITELY before ARGUMENT
Note there are many cases where this test doesn't
make sense or where the data cannot possibly be
interpreted. All of these will return false without
any error being raised. Therefore it is up to
the programmer to avoid propagating spurious FALSEs
by suitably guarding before calling.
1585CalendarType if this is a CAL then tell what type
0 .. fully specified DAYu.CALTYPE_YMD 000
1 .. no day DAYu.CALTYPE_YMX 001
3 .. just year DAYu.CALTYPE_YXX 011
7 .. not calendar DAYu.CALTYPE_ERR 111
These funny values are because we use them in various representations to mask
components we don't use. A 1 bit signifies unused
925ClearWWWS Clear .whatWentWrongStr
1714ContainsAday Return true if this date is the same as or encompasses
the argument. This must have the same or lower precision
than the argument.
Possible combinations for sensible testing
------------------------------------------
CAL
y m d - y m d
y m 0 - y m d
y 0 0 - y m d, y m 0
FLO
0 m 0 - 0 m d
Unsuitable values return false not an exception
1939CopyAday Copies all the argument's properties to this
Not the same as .MakeClone()
Always returns true
  • 'Copy' Needs a DAYo object]
1988DateToStringTemplate return a string representation of a CAL or FLO
The format string is a sequence of two-character tokens
that describe the elements to be included in the output
These may be interleaved with literal characters.
The Day(number) and Month elements will normally
automatically be exchanged to match the DM_ORDER parameter
in the appendix. (can be disabled with the -S flag)
CALENDAR DATE FORMATTING CODES
------------------------------
y1 ... year without any leading zeroes
y2 ... 2-digit year
y4 ... 4-digit year
m1 ... 1 or 2-digit month number
m2 ... 2-digit month number
M2 ... Month name tiny
M3 ... Month name short
M4 ... Month name long
d1 ... 1 or 2-digit day number
d2 ... 2-digit day number
D2 ... Day name tiny
D3 ... Day name short
D4 ... Day name long
BC ... BC indicator
FLAGS
------------------------------
-T ... Don't use 'Today'
-E ... Add extended NV and NVI reasons
-S ... Disable effect of DM_ORDER
1363Day return day value. 0 implies not set
1446DayOfWeek Day of week
No date-day returns 0. Monday ... Sunday returns 1 ... 7
1917DaysDifferenceAday How many days difference
1926DumpStr Return string version of internal state for debugging
1229FirstDay return first specific day
1605FloatType if this is floating then tell what type
6 .. Floating day DAYu.FLOTYPE_XXD 110
5 .. Floating month DAYu.FLOTYPE_XMX 101
4 .. Floating month-day DAYu.FLOTYPE_XMD 100
0 .. not floating DAYu.FLOTYPE_ERR 000
These funny values are because we use them in various representations to mask
components we don't use. A 1 bit signifies unused
1350FractionOfMonth How far through month are we?
Might throw error if year needed for February and not given
Only applicable to CALs of form y+m+d and m+d
928GetErrorCode what is the numerical value of the error
923GetWWWS Get .whatWentWrongStr
1089HasDay Return true if the day component is specified
1086HasMonth Return true if the month component is specified
1092HasYear Return true if the year component is specified
1095IsBC Return true if the sign component is negative
1025IsBoT Test for BoT signature
1062IsCalendar Is this a calendar day of the form Y or YM or YMD
1028IsEoT Test for EoT signature
1057IsErrorFree True if there is no error reported
1048IsFloating Test for a FLO signature
1035IsGiven Test for a signature indicating a workable date
ie. NK, BoT, Cal or EoT
1073IsGoodCalendarMonthRequired
DayRequired
Is it error-free and a calendar day with specified precision
MonthRequired and DayRequired are boolean flags
1031IsInterval Test for INT or NVI
1039IsKnown Test for signature indicating a 'known' date.
ie. BoT, Cal or EoT
1022IsNotKnown Test for NK signature
1052IsRealPeriod Test for a real date which could be Y or YM
ie. Day component is missing
832IsSameValueDAYobj
StrictFlag
See if two DAYs have the same value
If StrictFlag is truthy then errorCodes must match as well.
1043IsSpecific Is this a Cal that referrs to a specified day.
ie. Day, month and year components are all specified
1104IsToday Return true if this is today
1014IsValid Does DAYo have a valid signature
This does not mean free from errors
See IsErrorFree() and IsGoodCalendar()
1019IsValidDate Test for a valid DAYo signature
This does not mean free from errors
See IsErrorFree() and IsGoodCalendar()
1432Julian Julian() Return Julian day number
* VERY IMPORTANT FUNCTION *
Returns iNV if not a fully specified date
1232LastDay return last specific day
1243Middle Middle date of a range
1374Month return month value 0 implies not set
1911MonthsDifferenceAday How many months difference
1238Next return next Same sort of period
1235Previous return previous Same sort of period
592SetNVCode
Where
Desc
Set the signature of this object to NV
with error codes and what went wrong string
Always returns false
Code is a DAYu error code
Where is the routine that spotted the error
Desc is an optional txt message to go into what went wrong (See ._WWWS)
NOTE This operates on the object itself
1397Signature returns signature (integer)
1571SortsBeforeAday Does this DAYo sort before the DAYo in the argument
1471To32Bits To32Bits()
Returns an unsigned number
bits 31 - 29 Signature
bits 28 Sign 0:-ve 1:+ve
bits 27 - 16 Year 0 ... 4095
bits 15 - 12 Month 1:Jan ... 12:Dec 0 is legal
bits 11 - 7 Day of month 1 ... 31 0 is legal
bits 6 - 3 Day of week (Fully specified) 1:Mon ... 7:Sun 0:Undefined
Not valid reason code (NV) See table 7
bit 3 Not used
bit 2 Valid flag 1:Is validated
bit 1 Fully specified 1:Is fully specified
bit 0 Interval 1:Is interval
1559ToDate return a fully encoded Javascript Date
H, m and s are encoded
1278ToStringArg1
Arg2
ToString('Template','ExtendErrorCodeFlag')
Default string representation.
* Template (string) : See .DateToString() for template details and options
* Also may be '~' to return a tilde separated easy string
* ExtendErrorCodeFlag (boolean) : Missing/False->Number code True->String messages
1326ToTildeNumericFlag Return easy to read string that is part of a standard
The format is sig~sign~y~m~d~error
Normally the output will be easy to read mnemonics and no padding
but if NumericFlag is true then all values will be numeric and
padded where appropriate.
1502ToYmdhmsResultType ToYmdhms(ResultType)
Depending on the ResultType argument this can return
'ARRAY' an array encoded the form 'y,m,d,h,m,s'
'DATE' a javascript Date object with h,m,s encoded
'YMDHMS' a string formatted as yyyy-mm-dd hh:mm:ss
'YMDTHMSZ' a string formatted as yyyy-mm-ddThh:mm:ss.000Z
'STAMP' Unixy timestamp version of DATE (milliseconds since January 1, 1970, 00:00:00 UTC -ve for prior)
  • ToYmdhms() is unable to make a date. Original=
  • ToYmdhms has unknown ResultType("+ResultType+')
1384Year returns a signed year number or 0 if not set
1904YearsDifferenceAday How many years difference
1419_FloatingMetric Internal function that returns a simple
metric 'day count' 32 * days + months
Only applicable to floats
147_FromDayiDayi Given a DAYi object we convert into pure DAYo
2447_FromIntervalDayi Read an interval into this DAYo
  • '_FromInterval' Argument is not an interval
2141_LimitCharsNum
Padding
Turn a string into a number with 0,2 or 4 zeros padding
Padding should be 0, 2 or 4
815_MatchesArrayOfInnerValues _Matches
Tests internal structure against supplied array
'Signature,Sign,y,m,d,errorCode'
1117_RangeEndBegOrEnd Return the earliest or latest possible date for this Date
* BegOrEnd argument is one of DAYu.BoT or DAYu.EoT for beginning and end respectively
* Throws error if Arg is bad or unsuitable signature
  • Improper argument for _RangeEnd()
  • Improper signature for _RangeEnd()
  • Missing year for _RangeEnd()
881_Read32BitsUnsignedInt Read native 32-bit format
Sets DAY from number
bits 31 - 29 Signature
bits 28 Sign 0:-ve 1:+ve
bits 27 - 16 Year 0 ... 4095
bits 15 - 12 Month 1:Jan ... 12:Dec 0 is legal
bits 11 - 7 Day of month 1 ... 31 0 is legal
bits 6 - 3 Day of week (Fully specified) 1:Mon ... 7:Sun 0:Undefined
Not valid reason code (NV) See table 7
bit 3 Not used
bit 2 Valid flag 1:Is validated
bit 1 Fully specified 1:Is fully specified
bit 0 Interval 1:Is interval
Doesn't sanitize
184_ReadArrayAy Ay is of the form [Signature,Sign,Y,M,D,Error code]
230_ReadDateJsDate
UseTimeBits
Use a Javascript Date object to populate ourselves
JsDate is a Javascript Date object
UseTimeBits is a boolean flag to tell if the HMS
part is to be used for rich dates. This would be
false or missing for fully specified dates
(ie. where Y,M and D are all valid).
Note that if H,Mins,S are all 0 it is automatically
treated as a simple YMD case.
  • '_ReadDate' Javascript Date object needed
199_ReadJulianJulian Set ourselves from a Julian day number
Does not sanitize
2198_ReadStringStr
Patterns
Read a string according to one or more patterns
Returns false if the input is weird
Pattern tokens
--------------------------------------
Y2 two digit year ) Typically appear
Y4 Four digit year ) in combinations
YY Y2 or Y4 )
yy YY but may be missing )
M1 One or two digit month )
M2 Two digit month )
MN Month name (incl partials) )
D1 One or two digit day )
D2 Two digit day )
aa Alpha to be ignored )
TY Today shortcut ) Always appear
NV Not valid shortcut ) on their own
NK Not known shortcut ) as they're
nk Blank => Not known ) complete if
ET End of time/Not yet ) found
et Blank => End of time )
BT Beginning of time )
bt Blank => Beginning of time )
space optional space/punctuation ) All non alpha-numerics are treated as punctuation
_ required space/punctuation ) Multiple punctuation characters are treated as one
DEBUG Switches on diagnostics which will
be returned in .whatWentWrongStr
Combined pattern examples
--------------------------------------
For example
'D2M2Y2' exactly six digits with no spaces
'DD MN yy' 1/2 day digits, month name, 2/4 digit year or year guessed
'mm YX' requires a month name but the year will be substituted if not present
'Y4 M2 D2' yyyy mm dd (Would match 2017::::05???+-=23)
'D1_M1_yy' would match '1 2' and 01,02,2017 but not 01022017
We automatically pick-up if the last token is the BC indicator string
A special, complete on its own, pattern of DEBUG will switch-on pattern matching
failures to .whatWentWrongStr
  • string')throw "'_ReadString' Needs a string!
  • object'){throw "'_ReadString' Needs patterns"; // *don
  • '_ReadString' Needs an array of patterns
  • '_ReadString' Needs at least one pattern
  • string'){throw ''_ReadString' pattern '+patCount + ' is not a string.
  • '_ReadString' Code'"+V+"' is not a recognised template code
  • '_ReadString' Queer template '+pat+' gives d="+dmy.d+" m="+dmy.m+ "y=
289_ReadTextStr Read an ordinary human style text input
We'd use this as a catch-all interpreter when ._ReadString()
(which requires a sert of specified patterns) is not suitable.
This has wonderful interpretive and guessing adaptability, but
the trade-off for that is possible unintended results.
Return false if an error
166_ReadTildeStr String is in the form sig~sign~y~m~d~err
  • 'CreateFromTilde' Unable to read tilde format:
215_ReadTimestampUnixMilliseconds
UseTimeBits
UnixMilliseconds is a standard UNIX timestamp
Optional UseTimeBits is for when you can't use native 32-bit format
Really a wrapper for .FromDate()
610_ReadYMDHMSStr
UseTimeBits
The input is of the form YYYY-MM-DD with optional HH:MM:SS addition.
Typically this will return a fully specified date, but the time
elements may have been hacked to shoehorn a full DAYo object's data
into an existing database field etc. Time elements are ignored
unless optional UseTimeBits is true.
  • '_ReadYMDHMS' expected YMD part missing
  • '_ReadYMDHMS' expected HMS part missing
132_Reset Reset all internal values
.signature = NV
.sign = pos
.yr, .mo and .dy all set to 0
.errorCode = noError
.whatWentWrongStr = '' This is not persistent or cloned. Read using GetWWWS()
711_SanitizeWhereFrom _Sanitize
Private method to ensure internal values are safe
If any errors then sanitize them and set signature to NV
Return false if any errors found
Tell error to .whatWentWrongStr
WhereFrom is an optional string that tells the calling routine
which can go into .whatWentWrongStr
522_SetCalHelperY
M
D
We've got a d,m and y to process to finish
494_SetFloatHelperM
D
We've got a float, so finish it off.
The patterns are
(0,day),(month,0),(month,day)
974_SetFloatsPartialMask Zero any of the Y M D values in a Flo according to
The three-bit PartialMask
If PartialMask is invalid or not a Flo then return false
Typical use is when masking during an input conversion
Return false if an issue
938_SetPartialsPartialMask Zero any of the Y M D values in a Cal according to
The three-bit PartialMask
If PartialMask is invalid or not a Cal then return false
Typical use is when masking during an inout conversion
Return false if an issue
918_SetWWWSNewErrorStr Add error message to .whatWentWrongStr
NewErrorStr should be of the form: [current routine] message
Always returns false
853_SetYearYear Set Year and deal with negative values
1168_StepBegOrEnd Find the previous/next for dates eg 1957 ->1958, Aug 1957 -> Sep 1957, 13 Aug 1957 -> 14 Aug 1957
Returns a new DAYo
Technically allow floats also eg 13 Aug -> 14 Aug but leap years will be a potential disaster
so this IS NOT RECOMMENDED for use with floats.
NB DO NOT try to add 3 days with three calls to this function etc.
* BegOrEnd argument is one of DAYu.BoT or DAYu.EoT for beginning and end respectively
* Throws error if Arg is bad or unsuitable signature
  • Improper signature for _Step()
  • Improper argument for _Step()

DAYu.js

Utilities and constants
~~~~~~~~~~~~~~~~~~~~~~~
DAYu is a singleton, more for namespacing than anything

DAYu

50BADFROMFORMAT1, weird input to a .From...() method
51BADFROMVALUE2, some value to a .From...() method is unsuitable
24BoT5, beginning of time
128CALTYPE_ERR7, types of calendar dates
129CALTYPE_YMD0, fully specified ->>PRECISION_DAY->>3
130CALTYPE_YMX1, no day (M+Y) ->>PRECISION_MONTH->>2
131CALTYPE_YXX3, just year ->>PRECISION_YEAR-->1
102CONV_STATUS_INVALIDEXT1, Invalid extension found in t/stamp or date
103CONV_STATUS_NOT_FULL_DATE2, Conversion failure of some sort
25Cal6, Calendar date
814Convert2to4DigitYearYear,BlockFlag Given the supplied two digit year
convert it into a 4 digit year using the rules given
by the TWO_DIGIT_FIX setting.
0 = Disallow
20 = convert yy -> 20yy
50 = convert yy so that it lies between 50 years ago and 50 years ahead
If the argument <0 or TWO_DIGIT_FIX = 0 then return 0
If the argument is already 4 digits then leave it alone
Year can be a string (preferable) as this helps weed things like 0067 which is 0067 not 2067 etc
Optional BlockFlag returns the number without any conversion
To call from inside DAYo use (this.sign==DAYu.neg)
returns 0 if fail/disallow
153DAYSINMONTH30.4375, 365.25 / 12
62DFS_STATUS_ALPHANOTUNDERSTOOD3, alpha isn't shortcut or month name
65DFS_STATUS_CANTDECODEDDMMYY5, 2,4,6 or 8 digits only
57DFS_STATUS_EMPTYSTRING1, all whitespace
61DFS_STATUS_MORETHANONEALPHA2, only 1 alpha token allowed
60DFS_STATUS_NOTOKENS2, no alpha numerics in string
56DFS_STATUS_OK0,
58DFS_STATUS_TOOLONG1, sanity limit of 40 characters (far more than needed)
59DFS_STATUS_TOOMANYTOKENS2, max 6 tokens (far more than needed)
67DFS_STATUS_UNKNOWNERROR7, Sanitize failure
66DFS_STATUS_UNSUITABLENUMBER6, unsuitable numeric value somewhere
63DFS_STATUS_YEARMISSINGORBAD4, missing or bad year
64DFS_STATUS_YEARNOT2OR4DIGITS4 , year must be yy or yyyy
486DayCountToYmdIntArrayDayCount DayCount is a number of days (Not necessarily an integer)
Return an array of 'Y,M,D' after applying the necessary conversions
Uses the fractional conversion factor DAYu.DAYSINMONTH
470DayOfMonthToFractionY,M,D How far through the month is this d/m/y?
Can throw error if year is missing
554DaysDifferenceAday1,Aday2 Number of days between date1 and Date2
Example : If D1 is '1 Jan 2001' and D2 is '2 Jan 2001' then result is +1
Uses Julian day subtraction
445DaysInGivenMonthM,Y How many days in given month?
If m is 2 then use (optional) y to tell us if it is a leap year
If y is 0 then it is not a leap year
Illegal m argument or m=2 and y=undefined throws an error
711EarliestFinishArrayOfCals, IgnoreUnsuitable What is the earliest finish of these dates?
Only Cals are suitable values for the array.
NVI,INT,NV,FLO will throw an exception
NK,BoT,EoT will NORMALLY throw an excepton
UNLESS the optional 2nd arg is set true when NK->NK,EoT->EoT and BoT ignored
Zero-length array throws an exception
675EarliestStartArrayOfCals, IgnoreUnsuitable What is the earliest start date of these dates?
Only Cals are suitable values for the array.
NVI,INT,NV,FLO will throw an exception
NK,BoT,EoT will NORMALLY throw an excepton
UNLESS the optional 2nd arg is set true when NK->NK,BoT->BoT and EoT ignored
Zero-length array throws an exception
26EoT7, End of time
22FLO3, floating date
125FLOTYPE_ERR2, error
124FLOTYPE_XMD4, month and day only
123FLOTYPE_XMX5, month only
122FLOTYPE_XXD6, types of floating date
99FTS_STATUS_INVALIDSIG1, Error codes for FromTimestamp & date
477FractionToDayOfMonthY,M,Fraction Inverse of DayOfMonthToFraction()
375GetDefaultYear return the default year
Use IMPLIED_YEAR to tell us what to do
return iNV if missing years are not allowed
IMPLIED_YEAR ... Return
0 ........ iNV Do not allow inputs that miss out year part. Return iNV
-1 ........ yyyy Use the current year
-2 ........ 0 Allow floating date input
nnnn ........ nnnn Use the specified year
Possible returns are iNV,0,yyyy
403GuessCurrentYearForMonthMonthNum Suppose we want to let clerks type in "4 May" without
having to type in 2017 every bloody time! A huge number
of date inputs are 'around now' so this is a useful trick.
This function looks at the month and guesses which year
it applies to. For example if it's now January 2017 and
the input is 12 (December) then that probably referrs to
2016 just past.
'WARNING' While this is a useful short-cut there are two
issues that should be understood. 1: Obviously this is
only applicable to certain fields. 2: Clerks won't care
about the correctness of out of the ordinary inputs so
system-level checks for data integrity will be required.
74IFS_STATUS_BADLENGTH1, too short or too long
76IFS_STATUS_NOTOKENS2, Must have at least one part
73IFS_STATUS_OK0,
79IFS_STATUS_SIGNMISPLACED5, + or - other than at start
77IFS_STATUS_SIGNMISSING3, must start with + or -
75IFS_STATUS_TOOMANYTOKENS2, Can only have three parts
78IFS_STATUS_UNKNOWNUNIT4, suffix not recognised
80IFS_STATUS_UNSUITABLENUMBER6, unsuitable numeric value somewhere
20INT1, Interval
90INTERR_BADDATA1, malformed string/ data/ constructor arg
89INTERR_OK0, No error
95INTERR_READ_NV6, Read from a string as NV
96INTERR_TOBITS7, Conversion to 32 bits failed
93INTERR_USED_BT4, ) a scalar value.
94INTERR_USED_ET5, )
92INTERR_USED_NK3, ) DAYo methods means we can't arrive at
91INTERR_USED_NV2, ) One or more of the arguments used by
87INTPRES_D3, precise to day
86INTPRES_M2, precise to month
84INTPRES_X0, Constants for intervals
85INTPRES_Y1, precise to year
138INTTYPE_D3, precise to day (same as PRECISION_DAY)
135INTTYPE_DDD0, types of interval precision
137INTTYPE_M2, precise to month (same as PRECISION_MONTH)
139INTTYPE_X-1, error
136INTTYPE_Y1, precise to year (same as PRECISION_YEAR)
427IsLeapYearY Is a given year a leap year?
328JulianToYMDJulian Split Julian day number into array 'of Y,M,D'
It may throw an exception through an unsuitable input
(2436064 = 13/08/57)
* SEE ALSO _JulianToCal() and DAYo constructor
699LatestFinishArrayOfCals, IgnoreUnsuitable What is the latest finish of these dates?
Only Cals are suitable values for the array.
NVI,INT,NV,FLO will throw an exception
NK,BoT,EoT will NORMALLY throw an excepton
UNLESS the optional 2nd arg is set true when NK->NK,EoT->EoT and BoT ignored
Zero-length array throws an exception
687LatestStartArrayOfCals, IgnoreUnsuitable What is the latest start date of these dates?
Only Cals are suitable values for the array.
NVI,INT,NV,FLO will throw an exception
NK,BoT,EoT will NORMALLY throw an excepton
UNLESS the optional 2nd arg is set true when NK->NK,BoT->BoT and EoT ignored
Zero-length array throws an exception
912MakeBoT Construct DAYo for Beginning of time
902MakeCloneDayObj Clone a DAY object
Copies .errorCode but not .whatWentWrongStr
915MakeEoT Construct DAYo for End of time
943MakeINTYears,Months,Days Construct a DAYi interval
See DAYi.SetYMD()
918MakeNK Construct DAYo for Not known
927MakeNVErrorCode,Desc,MoreDayInfo Construct DAYo for Not Valid
ErrorCode is a number 0 - 7
Desc is an optional string description. To put the name of the routine
into the description put it in square brackets at the front by convention
in the manner of ._SetWWWS()
MoreDayInfo is an option DAYo object we will use to copy the sign,y,m,d elements from
Compare with .SetNV() which is an object method rather than a constructor
950MakeNVIErrorCode Construct a not valid interval with an optional error code
909MakeToday Construct DAYo for Today
784MonthOnlyAday Return a DAYo with just the month component
587MonthsDifferenceAday1,Aday2 calculate (or approximate if days are involved)
the number of months difference.
(Date2 - Date1)
Arguments must have the same pattern of y/m/d components
and be CAL or FLO.
Cal y m d, y m 0 or y 0 0
FLO 0 0 d, 0 m 0 or 0 m d
23NK4, date not known
21NV2, Not a date value
162NVD_INT_MULTINEGATIVE1, Not valid details
---day---
---date---
---int---
19NVI0, Invalid interval
106NVR_FUNCTION_FAILURE7, Not valid reasons
107NVR_NOT_CONCURRENT8, '@' change to 1..7
146PRECISION_DAY3, fully specified
143PRECISION_ERR-1, types of precision NB The greater the value the more precise
145PRECISION_MONTH2, only to months
144PRECISION_YEAR1, only to years
156SECONDSPERDAY864000, eg (J - UNIXDAYSTOJULIAN) * 86400 -> U
29SIGNATURE_STRINGS['NVI', 'INT', 'NV', 'FLO', 'NK', 'BoT', 'Cal', 'EoT'],
35SIGN_STRINGS['-ve','+ve','-','+'],
211SigStrToConstStr Convert a three character string into a signature constant
Case insensitive
Special case where digits 0..7 are allowed 'as they are'
Returns NV if unable to interpret Str
'T'
194SigToStrSig, NumericFlag Signature code to three character string
Sig is number 0..7
Return appropriate string from DAYu.SIGNATURE_STRINGS
If optional boolean NumericFlag is true then return
a single digit string "0".."7"
'T'
249SignStrToConstStr - or -ve return DAYu.neg
anything else returns DAYu.pos
'T'
235SignToStrSign, NumericFlag Sign to three character string
Sign is 0 or 1 returning "-" or "+"
If optional boolean NumericFlag is true then return
a single digit string "0" or "1"
'T'
532SortsBeforeDay1,Day2 Compare two DAYo objects
If both are intervals then compare magnitude
otherwise compare on 32 bit representation
Return -1 d1 < d2
0 d1 == d2
+1 d1 > d2
(Note this is SIMILAR but not identical to DAYo.SortsBefore()
which conflates == and > into false.)
957SumIntervalsIntervals Construct an interval by adding one or more intervals
154UNIXDAYSTOJULIAN2440587, Number to add to Unix day number to get Julian day number
167UNIX_BOT-2147540400, 13 Dec 1901 05:00:00
168UNIX_EOT2147410800, 18 Jan 2038 07:00:00
166UNIX_NK-2147544000, 13 Dec 1901 04:00:00
165UNIX_NV-2147551200, special values for unix timestamps
69UNKNOWNERROR7, Sanitize failure
150YEAR_GUESS_DELAY4, how many months might we go back to last year in GuessCurrentYearForMonth()
266YMDToJulianYr, Mo, Dy Create Julian day number from Year, month and day
Year can be +ve or negative
630YearsDifferenceAday1,Aday2 Practically the same as MonthsDifference / 12 except
- unsuitable args returns iNV
- where CAL pattern is y 0 0 the calculation is simple subtraction.
854_Diva,b Utility integer division function
eg (7,2) -> 3
719_EarliestLatestAnyAllCaller, ArrayOfCals, IgnoreUnsuitable Internal servicing method for Earliest/Latest Any/All
Caller is two character code eg EF for EarliestFinish
883_IsAlphaStr returns true if Str is all alpha
@@@ Do we ever use this now?
890_IsNumericStr returns true if Str is all numbers
@@@ Do we ever use this now?
351_JulianToCalJulian
866_PadIntLeftPadChr, Num, Width, Zero Utility pad-right for integer
LeftPadChr is typically 0 or space
Num is numeric value
Width is total width (Grows by 1 if Num is -ve)
Zero is an optional substitute character for 0
513_StepYearYear,Increment Step year up or down but trap year 0
46badNumber6, FromJulian()
44badSetObject2, DAYo.Set() given inappropriate object
43badSetSignature1, DAYo.Set() given inapropriate signature
39canNeverHappen001-1, Dayo.Set()
173debuggingTrail{ Debugging trail that can be used to log as required
Call as DAYu.debuggingTrail.Add(someMessage) etc.
115force32Bits'32',
114forceJulian'J',
119forceTilde'~',
118forceTimestamp'STAMP',
116forceYMD'YMD',
117forceYMDHMS'YMDHMS',
111iNV-9999999, integer not valid return value iNV
32neg0, sign negative
40noError0,
33pos1, sign positive
45unsuitableRange3, DAYo.Middle() on inapropriate object
15version"Built on {{BUILDDATE}}", curly placeholder modified by build-tools

DAYc.js

Internationalisation and parameters configuration
Singleton

DAYc

147AllowDayOnlyIntervalsNewValBool Do we allow INTs to be created with more than 31 days eg +0y 0m 66d
132AllowExcessDaysInMonthNewValBool Get/Set true if we allow silent coercing of slightly
too many days in month to end of month
192BCIndicator String used to indicate negative years
@@@ needs to rewritten as get/set
263BuildCommonTerms We need to look up shortcuts quite often for inputs so build
A list of shortcuts (eg B for BoT) and other terms such as Beg-of-time
247BuildInputHacks Create a lookup dictionary to allow some inputs to be converted
to other (more acceptable ones)
282BuildMonthLookups We're quite likely going to need to look-up month names
As with Common Terms we need a shortest version and a full version
for different ways of matching
443DumpCfg Diagnostic for useful parameters usually pertaining to input strings
427ExtendedErrorStrDayOrSig,ErrorNumber,ExtraInfo Return error string (if applicable)
If there's no error then return an empty string
This can be called in two ways:
Either
Int(0-7) DayOrSig, Int(0-7) ErrorNumber , optional string ExtraInfo
or
Just a DAYo object where .whatWentWrongStr will be used as the extra info.
eg if(var em = DAYc.ExtendedErrorStr(someDay)){ // single = is correct
DoShoutAnError(em);
. . .
472INITIAL_DATA[ Default, built-in en-gb settings
162ImpliedYearNewValInt Get/Set numeric value of IMPLIED_YEAR
Allowable inputs are 0,-1,-2 or a year > 999
465InYearLimitsYear Check to ensure the year given is within current limits.
Only applies to INT and Cal
62InitialiseOptionalAppendixData Load the appendix file with the UI settings
Must be done early on
Returns false if there is an error
OptionalAppendixData is either text in appendix format
or an object in straightforward Key-Value form
@@@ We need another method such as GetAppendix(appx-name) as a wrapper
which will be file getting and asynch :(
311InterpretStringInpStr Interpret string
Return '' or 0 for not understood
Return 'BoT','EoT','NK','NV','TODAY','NVI' if found
Return month number
118IsDmyOrderNewValBool Get/Set true if we are working in a d-m-y environment
Always returns boolean'
Only changed if NewValBool is of type boolean
7KVnew Dict(),
98LookupStr,Num Lookup a key
The args may be just a string or a string and number eg ('BoT',3)
409MonthNameMonNum,Version Convert month number into a name
MonNum 1..12
Version 1..4 (2 is 3 characters length)
364SearchMonthsInpStr Search month names to return a numeric equivilent eg Fe -> 2
Return a numeric equivilent or 0 if not found
329SearchShortcutsPossibleShortcutStr Search shortcuts to return a string code eg "BoT"
Return null string for not found
346SearchTermsPossibleTerm Look to see if PossibleTerm might be start of a standard term
For example PT=Be ST=Beg-of-Time -> "BoT"
returns key string or null string
107SetKeyValueKey,Value Temporaraly (session) set a K-V pair in the configuration
Preferably use one of the direct convenience methods
177TwoDigitFixNewValInt Get/Set numeric value of TWO_DIGIT_FIX
Allowable inputs are 0,20,50
203_ExtractAppxSettingsAppxFileData,FirstLoad (private) Read appendix file data. Sets .error to null string if OK
86_Rebuild
9appendix"en-gb.dax", actual file name
8error'', eg load issue such as badly formatted file
11force2or4DigitYearsfalse, if true then years input MUST be in the form yy or yyyy
10i18n"i18n", path (no trailing slash) to appendix
49inputHacksnew Dict(), AltStr -> NormalStr (all u/case)
48months1new Dict(), July ->4
47months32new Dict(), Jy ->4 Jul->4
46months4new Dict(), These are the officialy approved strings that represent special terms allowed
for input of BoT,EoT,NK,NV,NVI,TODAY. (Match if term starts with input.)
12needsBuildtrue, flag if needs to be initialised
39shortcutsnew Dict(), B->BoT,E->EoT etc
43specialTermsnew Dict(), shortcuts are the shortest string that identifies a special term eg E for EoT
These are generated from the .3 items in section 1 of the appendix for
BoT,EoT,NK,NV,NVI,TODAY. (Match if input starts with shortcut)
13yearLimit4095, Maximum size of year

DAYi.js

DAYi - INTERVAL
A distinct object that shares the same 32-bit representation with DAYo
----------------------------------------------------------------------
.signature Either DAYu.INT or DAYu.NVI.
NVI is reserved for actual errors
.positive boolean. Applies to all Y,M,D values together
.days 0 or +ve integer ) Except when converting to 32-bits
.months 0 or +ve integer ) these may be any 'reasonable' number
.years 0 or +ve integer ) eg 67-months is fine
.errorCode 0 .. 7 only relevant if signature is NVI
DAYu.INTERR_OK : 0 No error
DAYu.INTERR_BADDATA : 1 malformed string/ data/ constructor arg
DAYu.INTERR_USED_NV : 2 ) One or more of the arguments used by
DAYu.INTERR_USED_NK : 3 ) DAYo methods means we can't arrive at
DAYu.INTERR_USED_BT : 4 ) a scalar value
DAYu.INTERR_USED_ET : 5 )
.precision Integer constant telling how to interpret the data
DAYu.INTPRES_X : 0 not-set/error
DAYu.INTPRES_Y : 1 precise to year
DAYu.INTPRES_M : 2 precise to month
DAYu.INTPRES_D : 3 precise to day

DAYi

36constructorInitialiser Standard constructor
Initialiser can be
undefined ... Not very useful
string ...... see .FromString()
number
<4096... Number of days
>4095... see .From32Bits()
array ....... see .FromArray()
DAYi object.. make a copy
DAYo object.. see .ReadDAYo()
515AddDAYis
UseDurations
Add one or an array of DAYis
This is sign sensitive
If optional UseDurations is true then convert everything to days
NOTE If UseDurations is true then precision will be set to days
otherwise the least precise of the operands. This can have
unexpected consequences. For example if this is +1y to yearly precision
and we 'add' -200d we don't get 156d but 0y
Return false if we have a NVI result (In which case the error code is INTERR_USED_NV
Note
It's important to add a bunch of intervals as an array rather than a succession of
individual .Add() operations. This is because .Add() rounds fractions at the end of
the procedure. So if you have four intervals of 100 days to add to 1 year (with yearly
precision) then doing it the right way will be
roundToYears(365.25 + 100 + 100 + 100 + 100) => 2 years
but doing it the wrong way will be a succession of
roundToYears(365.25 + 100) => 1 year
which repeated four times is still 1 year.
  • 'i.Add'One or more operand is not an interval
468AsDays
463AsMonthsRespectPrecision
460AsYearsRespectPrecision Return floating point value for the overall value of the interval
in years. note NVIs return 0
If RespectPrecision is true then ignore elements beneath .Precision
151CopyDayi Copy argument values into this
490DaysDifferenceDayi Comparing the magnitudes of the intervals
If this is larger than the argument then the
result will be positive.
417DumpStr Debugging aid
451DurationRespectPrecision The size of the interval including the sign
Calculations as for .Magnitude()
Note that NVIs return iNV
277ErrorOrPrecision Depending on the signature (INT or NVI) return appropriate value
296FromStringIntStr Read the standard string format for interval of
required + or -
optional integer then y
optional integer then m
optional integer then d
  • string'){throw "'i.FromString' needs a string
  • 'i.FromString' must start with + or -
  • '){throw "'i.FromString' no Y,M or D elements
  • 'i.FromString' bad token ("+V+")
281GetErrorCode What is the errorCode
283GetPrecision What is the precision
140GetPrecisionOrError For the purposes of dressing an interval as a DAYo
we combine precision and error codes depending on
if the error is set. Return whichever is appropriate
483IsLargerThanDayi Does this have a larger magnitude (ignoring sign) than argument
411IsPositive
481IsSmallerThanDayi Does this have a smaller magnitude (ignoring sign) than argument
285IsValid Is this a valid interval
436MagnitudeRespectPrecision The absolute size of the interval ignoring the sign
An approximation to number of days
This is calculated in days assuming there are 365.25
days in a year and and 1/12th of that each month
NVIs return iNV
RespectPrecision is an optional boolean which if true
will respect the .precision value. So for example
+1y 2m with a precision of years will return 365.25 if
this is true but 426.125 if missing or false
413MakeNegative
412MakePositive
270PrecisionNewValue Get or set precision
  • 'Precision' Unsuitable new value
624ReduceDaysDays
Precision
We have a number of days which we want to set the interval to.
A simple case is 300 days where the interval is precise to days
in which case we end up with +0y 0m 300d.
BUT REAL LIFE ISN'T ALWAYS SIMPLE :(
If the precision is monthly then we'll have 200/30.4375
months (=6.57...) which is rounded to give +0y 7m 0d
If the precision is yearly 200 days becomes 200/365.25 = 0.547
with the result of +1y 0m 0d.
Yearly precision and 150 days gives the result +0y 0m 0d
The moral of the story is: If you want to work in days as
your unit of duration then stick to plain integers.
Precision can be
DAYu.INTPRES_Y ... year
DAYu.INTPRES_M ... month
DAYu.INTPRES_D ... day with Y and M allocated large amounts
missing .......... day with all other values zero. Day precision
196SetYMDY
M
D
Simple and mainstream way to set the key values
This will automatically set the precision according
to what arguments are given/omitted
eg (1,2) is monthly but (1,2,0) is daily
Values are always integers.
The last non-zero value will set the overall sign
@@@ allow args to be null also @@@
678To32Bits To32Bits()
Returns an unsigned number
bits 31 - 29 .signature
bits 28 .positive 0:-ve 1:+ve
bits 27 - 13 .years and .days combined
bits 12 - 11 split 0.3 See .FindYDSplit()
bits 10 - 7 .months
bits 6 - 4 .errorCode (if NVI) or .precision (if INT)
bit 3 Not used
bit 2 Valid flag 1:Is validated
bit 1
bit 0 Interval 1:Is interval
377ToStringForceFull
DigitCount
Return a string representation.
Optionally force all three parts if ForceFull is truthy
Optionally pad the output of the digits to a given number
using DigitCount so that columns will be aligned
753_FindYDSplitY
D
How to apportion 15 bits between years and days
Possibilities are
bits | Max values | result
------+---------------+--------
12/3 | 4095 7 | 0
10/5 | 1023 31 | 1
5/10 | 31 1023 | 2
3/12 | 7 4095 | 3
------+---------------+--------
If these combinations won't work straight-off,
see ._PackYMD() then hack about:-
a) convert everything into months...
b) ... then into years and months with spare days
If this doesn't work (because too many days) then
fudge the months and years.
The splitting arrangement is based on the assumption
that if you've got a large number of days then you're
hardly likely to be bothering with years. Similarly
if there are lots of years then who cares about a few
days being fudged
697_From32BitsUnsignedInt
234_FromArrayDayArray The lowest level 'constructor', all the other From() methods feed into this.
Initialiser is an array 'Signature,Sign,Years,Months,Days,Precision,ErrorString';
.Signature must be DAYu.INT or DAYu.NVI
.Years , .Months and .Days may be 0,-1 or a sensible value
null is used to indicate missing. For example a string of "+1y 2m"
would have a null for .Days. This is important for precision
For example "+1y 2m" is precice to month but "+1y 2m 0d" is precise to day
.ErrorCode is ignored unless .Signature is NVI
  • 'DAYi.ReadArray' Incorrect signature
122_Normalise Normalising means making sure the M and Y components
are within the expected range 0..12 and 0..29 respectively.
Un-normalised may have out of range values.
Values are always +ve integers regardless.
The reason for normalising is to fit into DAYo constraints.
Normalising is completely separate from sanitizing
It is also INACCURATE. 30 days in every month. 360 days in every year!
766_PackYMDY
M
D
Pack Y,M,D into 21 bits
Y and D have the top 15 bits split between them
2 bits used for where the split is
Least significant 4 bits used for month
164_ReadDayoDayo We may have DAYo wrapping an interval. So let's extract it.
  • '_ReadDAYo' Not a DAYo or bad signature
77_Reset Reset the internal state
93_Sanitize fundamental checking of internals
Throw all sorts of should never happen errors
  • number'){throw "'i._Sanitize' .signature is not a number.
  • 'i._Sanitize' Improper .signature ("+this.signature+")
  • boolean'){throw "'i._Sanitize' .positive is not boolean.
  • number'){throw "'i._Sanitize' .days is not a number.
  • 'i._Sanitize' .days can't be negative ("+this.days+")
  • number'){throw "'i._Sanitize' .months is not a number.
  • 'i._Sanitize' .months can't be negative ("+this.months+")
  • number'){throw "'i._Sanitize' .years is not a number.
  • 'i._Sanitize' .years can't be negative ("+this.years+")
  • number'){throw "'i._Sanitize' .precision is not a number.
  • 'i._Sanitize' Improper .precision ("+this.precision+")
  • number'){throw "'i._Sanitize' .errorCode is not a number.
  • 'i._Sanitize' Improper .errorCode ("+this.errorCode+")
  • 'i._Sanitize' ErrorCode set ("+this.errorCode+") but signature says valid.
  • 'i._Sanitize' Magnitude is too large.
810_UnpackYMDI21 Unpack 21 bits into array 'Y,M,D'

DAYx.js

Development and testing only
============================
"use strict"; var DAYx,DAYu,DAYo,$,DAYc,console; only for occasional extra linting

StackExpAct

21constructorExp
Act
~~~~~~~~~~~~~ Used by library methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Stack expected and actual results
NB Don't forget to do Exp='' afterwards

StartsWith

10constructorHaystack
Needle
~~~~~~~~~~~~~ Used by library methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
case insensitive string comparison

DAYx

356AddBadTestResultLineNum,Task,Expected,Actual,Comment THESE ARE NOT YET OBSOLETE
364AddCommentResultComment
360AddGoodTestResultLineNum,Task,Expected,Actual,Comment will be obs
676AddLibraryTestTestName,Desc,InpArg,OutArg,FunCode Add a test function to the library
TestName will be capitalised
Desc is description/purpose (Any authoring/versioning stuff will be
comments in the code calling this.
InpArg and OutArg describe the sort of input, ie bit in the brackets
of a test line, and nature of expected result.
FunCode is the actual code
NOTE We use the variable DAYx.__FILE__ to inject the source file name
This is normally set/cleared by the methods loader.
318AddResultOk,TestData,Result,Comment Add an entry to the results file
Ok is boolean or array of 'Ok,TestData,Result'
811AjaxForFilesPath,Ext,ThenDo Look for a list of files using AJAX call
Path is relative eg './tests/scripts'
Extension is type of file incl dot eg .testScript
ThenDo is a function taking an array of filenames which
have had their extensions removed
*NOTE* Browser only
830AjaxLoadMethodFiles look in the methods directory for js files
each should have one or more methods implemented
by AddLibraryTest(). All these are eval-ed
so as to populate the method library
48DayDisplayD Return HTML for the inner state of the DAYo object
655DescribeLibraryTestsInHtml List the tests in the library
If InHtml is truthy then return a string of TRs else an
array of 'Name,Desc,Input,Output,Filename'
684DoTestLineTestData Execute a line of a test script
93ErrorCodeToTextErrCode Return the text representation of the ErrorCode(number)
374GetNextTestLine Looks for the next line in the tests that contains an actual
test. Return null if 'EOF' or array
'TestName,Function arguments,Expected result string,Comment'
164InitAtSubstitutions set @TODAY and @YEAR substitutions
----------------------------------
308OutputLabel,Values Send debugging information to results listing
Can be toggled by the .showOutput property
Label is a string
Values is an array of bits to show
113RunTestsInBrowserFileName BROWSER MAIN CALL
Load the file of tests into an array of lines
tests'n' will be the nth line of the file
Uses jQuery
177RunTestsInNodeFileName,Fs,Path NODE MAIN CALL
FileName is relative to current dir
Fs is fs (file system) variable
Path is path utility
72SigToTextSignature Return the text representation of the signature(number)
751TestDateBothWaysTestData Implements the DATEBOTHWAYS test
487TestResultsTableShowAll Returns HTML for a table of results (BROWSER)
777TestSetConfigTestData Implements the SETCONFIG command (Not actually a test)
Normal use : SETCONFIG(KEY,VALUE)
Can be used for functions eg SETCONFIG(SetLimitToUnixExtended)
702TestTwoWaysDay This combines to/from js Date, to/from 32bits, to/from extended unix
the result is ok or D, 3, U! being the first failure in the both ways
We have this as a general add-on to the other tests so we get lots of coverage
We expect these to be pretty reliable... OK Hope... OK wish :)
447WrapS,Width Wrap long text to the specified width
When calculating, ignore HTML tags
625_BarText,Width pad/truncate cell value and add a leading bar
583_DumpResultsToFileShowAll Writes results to file.
either <script>.fails or <script>.results depending on ShowAll
Filename is in 1st line testResults
Node only
430_ErrorPlaceEx Return string giving line and file where exception happened
*** (Probably FF only. Alternatives at http://eriwen.com/javascript/js-stack-trace/)
644_UnZeroNumStr Utility function to drop trailing decimal zeroes
from a number-string. "123.000" --\> "123" "123.400" --\> "123.4"
236_UpdateOverview Update the collection of statistics
This is an HTML file with links to results
Node only
36__FILE__'', Used when reading-in methods
34atToday'', substitution for @TODAY
35atYear'', substitution for @YEAR
37firstLine1,
32glines'', temp
38lastLine9999,
26libMethods{}, library of available tests
43readStringTemplates["_D MN yy"], templates for ._ReadString()
33scriptName'', full name of file being used
41showOutputtrue, show results of .Output()
30testFailCount0,
31testPassCount0,
29testResults[], results of tests
28tests[], definition of test
This reference document is completely self-contained so download and put with your other data sheets.
Created 30 Jul 17 at 11:27:04
Generator: jsinfo.php Source from http://vulpeculox.net Written by Peter Fox @