TweetFollow Us on Twitter

September 30 - UDates

UDates

Jesse Feiler, The Philmont Software Mill

Who am I to argue with a cute, curly-haired orphan, but… Annie was wrong. "Tomorrow, tomorrow, I love ya, tomorrow, you're only a day away" she sang (and at the slightest provocation).

To those of us who have worked on systems that are time-sensitive, we know that "tomorrow" is only sometimes a day away. For example:

  • in most businesses, the "tomorrow" of Friday is Monday
  • similarly, the "tomorrow" of December 24 is December 26 (unless a weekend intervenes, or Boxing Day is a holiday, as in England [and in Canada: Ed.]).
  • and, if you are editing a transaction that was entered days ago in order to fix a typo, you may be processing data as of last week, and the system's idea of "tomorrow" is actually a week ago.

The code to handle all of this is not particularly obscure, and many of us have written it-over and over and over again.

From the earliest days on the Mac, we have had very good date and time manipulation routines available in the toolbox. Recently, the Script Manager incorporated some rather nifty text-parsing routines that it combines with new date routines to make everything transparent, whether you are in Japan or Egypt, and whether you are interested in this era or in one distant by several millennia.

I decided that once and for all I would take the toolbox routines and combine them into some MacApp objects that could be used (and overridden) for almost any purpose involving date manipulation. And thus was the UDates unit born.

From a user's point of view, the two most important objects in UDates are the TDateCluster and the TElapsedTimeCluster. Both are descendants of TCluster and are designed to be placed in TDialogViews.

Here's a step-by-step description of their behavior. Note that both are initialized to a "today" date which will be described later. In addition, assume that Saturday and Sunday are weekends, although UDates allows you to specify any weekend days that you want.

TDateCluster

Now, as you might expect, the two boxes at the left are editable. In fact, they belong to a class called TDateEditText which is a descendant of TEditText. TDateEditText objects are basically TEditTexts but with the added functionality that their Validate methods expect the contents to be a date which is parsable by the Script Manager routines. If the date doesn't pass the Script Manager parsing, Validate fails and MacApp restores the previous value. The programmer can thus always assume that there's a valid date in a TDateEditText.

Finally, the TDateCluster provides the information as to whether the date values it returns are the result of user data entry or of clicking on the radio buttons. In some cases, the program is only interested in the start and stop dates shown in the TDateCluster. In other cases, it is important to know whether the user is after this week's data (regardless of date) or the data for 3/12 – 3/16 specifically.

Here's the interface to TDateCluster:

TDateCluster = OBJECT (TCluster)
fDateObj: TDateObj;         {a TDateObj, probably set to today}
fFrom, fTo: TDateEditText;  {private - use GetStartStop}

FUNCTION TDateCluster.GetStartStop(
                                    VAR d1, d2: LongDateTime;
                                    VAR rChoice: IDType): BOOLEAN;
PROCEDURE TDateCluster.IDateCluster(aDate: TDateObj);
PROCEDURE TDateCluster.DoChoice(
                                    origView: TView; 
                                    itsChoice: INTEGER); OVERRIDE;
PROCEDURE TDateCluster.Fields(PROCEDURE DoToField(
                                    fieldName: STR255;
                                    feldAddr: Ptr;
                                    fieldType: INTEGER)); OVERRIDE;
PROCEDURE TDateCluster.Free; OVERRIDE;
END;

Only IDateCluster and GetStartStop are normally used.

TElapsedTimeCluster

The TElapsedTimeCluster consists of three editable fields: two date-time fields, and one field which represents the number of hours between the two date-times. Thus, after posing the TElapsedTimeCluster in the DateSample program, you can enter 1.5 in the elapsed time field… and after any other event in the dialog, the second date-time field will be adjusted. The TElapsedTimeCluster will take whatever two fields are entered and calculate the third.

{IElapsedTimeCluster can handle a 0 for d2 (stop time) and/or duration. If duration is 0, it is calculated. If d2 (stop time) is 0, it is calculated using duration. You might want to do your own error-checking to make sure that you are passing in good values. TElapsedTimeCluster makes sure that all three fields are consistent: change fFrom or fTo, and fDuration is updated. Change fDuration and fTo is changed. (Yes, it could have been coded the other way, but it wasn't. If you want duration to count backwards from fTo and modify fFrom, modify the object.) GetStartStop gives you the start and stop times.}

Here is the interface to TElapsedTimeCluster:

TElapsedTimeCluster = OBJECT (TCluster)

fDateObj:   TDateObj;           {probably today}
fFrom, fTo: TValDateEditText;   {private - use StartStop}
fDuration:  TValEditText;       {private - use GetStartStop}

PROCEDURE TElapsedTimeCluster.Free; OVERRIDE;
FUNCTION TElapsedTimeCluster.GetStartStop( 
                                    VAR  d1,d2:LongDateTime):BOOLEAN;
PROCEDURE TElapsedTimeCluster.IElapsedTimeCluster(
                                    aDate: TDateObj; 
                                    d1,d2: LongDateTime;
                                    duration: comp;
                                    aStyle: TextStyle);
FUNCTION TElapsedTimeCluster.Validate:LONGINT; OVERRIDE;
PROCEDURE TElapsedTimeCluster.Fields(PROCEDUREDoToField(
                                    fieldName:STR255;
                                    fieldAddr: Ptr;
                                    FieldType:INTEGER)); OVERRIDE;
END;

Again, GetStartStop and IElapsedTimeCluster are likely to be the only methods which you'll call directly. Validate is called for you by TDialogView, but nothing prevents you from calling it yourself at some other time.

TDateEditText

In the DateSample program, the Set "today" dialog allows you not only to set the "today," but also to experiment with a TDateEditText field. Typing in "12" sets the date to March 12, 1990, since the Script Manager defaults to current month and current year. The Script Manager will recognize non-standard delimiters and-as shown in a recent Tech Note-its flexibility will allow it in some circumstances to wander off in very peculiar directions. Fortunately, you can check to see how far afield the parser has gone and set your tolerance level as low or as high as you want.

{The IEditText and IRes methods initialize all fields. You may want to subsequently reset fWantDate or fWantTime. Resetting fDidEdit is undefined (polite for "stupid"). fDate is obtainable in alternate formats by calling GetLongDateTime or GetLongDateRec. }

Here's the interface to TDateEditText:

TDateEditText = OBJECT (TEditText)

fWantDate, fWantTime, fDidEdit, fZeroBlank: BOOLEAN;
fDate: LongDateRec; 

PROCEDURE TDateEditText.Fields(PROCEDURE DoToField(
                                 fieldName:STR255;
                                 fieldAddr: Ptr;
                                 FieldType: INTEGER)); OVERRIDE;
FUNCTION TDateEditText.GetLongDateTime(
                             VAR aDate: LongDateTime):BOOLEAN;
FUNCTION TDateEditText.GetLongDateRec(
                             VAR aDateRec: LongDateRec): BOOLEAN;

PROCEDURE TDateEditText.IEditText(
                                 itsSuperView: TView;
                                 itsLocation, itsSize:VPoint;
                                 itsMaxChars: INTEGER);
     OVERRIDE;
PROCEDURE TDateEditText.IRes(
                                 itsDocument: TDocument;
                                 itsSuperView: TView;
                                 VAR itsParams: Ptr); OVERRIDE;
PROCEDURE TDateEditText.SetDate(
                                 aDate: LongDateTime;
                                 reDraw: BOOLEAN);
FUNCTION TDateEditText.Validate: LONGINT; OVERRIDE;

END;

Once again, the methods shown in bold are the ones which you are likely to call directly. Note one point about IEditText: it does NOT set the initial value; you have to call SetDate. It is generally agreed that the IYourObject methods should leave all fields set to some value (e.g., handles to NIL if not actually allocated). In our recent projects we have tended to separate the setting of values from the initialization of the object. Thus, in a project that uses UDates, we have three methods that handle the fields:

  1. InstallADate (location, etc.)
  2. LoadADate (sets values)
  3. UnLoadADate (gets values)

Similar triplets of methods are used for other types of data entry fields. This works very nicely for cases where one view is used to show and update data from various database records.

TDateObj

The third major object in UDates is the TDateObj. It is initialized to a given date and to the weekends and holidays which it should recognize. Thereafter, it can quickly provide yesterday, tomorrow, next week, etc. as needed. In general, one TDateObj is initialized for the application and is not reset during program execution.

The interface for TDateObj is not provided here, since it is fairly lengthy and is provided in the code which follows.

Using UDates

The objects in UDates are designed to be as basic as possible and still provide the needed functionality. They can be customized in two ways. First of all, they can of course be overridden to change their behavior. Secondly, there are parameters which can be set by the program (e.g., do you want both date and time shown in a TDateEditText field?) to modify their behavior. In general, I have assumed that the parameter setting will be fairly constant within an application, and therefore error-checking for parameters is done only in the Debug version. Both Debug and NonDebug versions should catch errors which a user might make in data entry.

In addition, the TDateCluster and TElapsedTimeCluster are views that are editable in ViewEdit to allow a developer to use a specific application's standard fonts and graphic styles. TElapsedTimeCluster is about as sparse as you can get in terms of text, because in those cases where it's been used, we have always modified the resource to incorporate additional text fields.

The code which follows is for UDates itself as well as for DateSample, a small application which uses UDates and to show the results of various commands via messages in the Debug window.

The code is (I hope) fairly clear and well-annotated, so there's no point in going through it in detail. I will, however, mention a few points which may be of interest.

Creating a new, generalized unit

All programmers, and MacApp programmers in particular, have sections of code which they reuse. In my particular repertoire are a FailDBErr routine that I use to trap Inside Out errors, a unit of utility dialogs, and of course UDates itself. In creating these units, I've found a few points to be useful:
  • Do spend a few extra moments to provide Get… and Set… routines for variables of your objects that would normally be visible to the outside world, even if that outside world is you. In TDateEditText, the GetLongDateRec and GetLongDateTime functions were the last changes made. At first it seemed silly to write these functions when the data could easily be found with the field names. The decision to add the functions was NOT made for reasons of ideological purity; it was made because some of the manipulation code was being written several times in my application.

    Whenever code is duplicated, that's a clue that it's in the wrong place and should be moved to a location where it's written once and done with. In UDates, not every variable is accessible to the outside world; providing Get… and Set… methods for all fields of an object is unnecessary (in my humble opinion). What is necessary is to decide which fields and which common transformations of them are likely to be necessary, and to provide those.

  • Don't think you save time by not having a Fields method for every object. Even if the Fields method has nothing but the object's title (bClass), it may well save you from lost time trying to figure out where you are.
  • In creating new units that you plan to reuse, take a moment to think of all possible uses of the unit. For example, we are in the process of creating a generalized numeric entry object-much like TDateEditText. That object must be a descendant of TEditText and not of TNumberText. Why? The fMinimum and fMaximum fields of TNumberText are LongInts. In addition, lots of TNumberText code assumes LongInt values.
  • Don't use standard segment names. Thus you'll find that in UDates, code is placed into $ADateRes and $ADateFields segments. The –sn option in your MAMake file will allow you to remap these segments to $ARes and $ADates if you want to. By keeping your segmentation at least temporarily separate from normal MacApp segmentation, you can easily make adjustments if you blow up a segment with the infamous >32000 error.
  • Add a local debugging option (such as qTraceDate). You'll notice that this option tracks procedure entries, sometimes printing parameters out so that you can see how things are going. Again, by using your own debugging options, you avoid interfering with MacApp and your other debuggers, so that you don't get a slew of UDates debugging messages while you're trying to debug a database problem.
  • Consider adding additional debugging code to your unit. Debugging code turns out to be (in my experience) some of the most reusable code there is. The bLongDateRec and bLongDateTime Fields options are used all through our applications.

Creating the clusters

Normally, one has a choice of creating views either from templates or programmatically. In UDates, the clusters are designed to be created ONLY from templates-and in fact the appropriate ICluster methods are missing. This is deliberate and should be considered as an advertisement for ViewEdit. The TDateCluster contains eight subviews, each of which must be placed, sized, and identified properly in order for the TDateCluster to work. In addition, the six radio buttons must be named with appropriate base names-and no one would consider hard-coding words like "Today" or "Yesterday," so those would have to be stored in a string resource. The code for doing all of this initialization is about 50 lines long. In a case like this, I do not think that template and programmatic creation are equally appropriate: ViewEdit wins hands down in such a case (even with some of its bugs-which I'm sure will be gone shortly).

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fallout Shelter pulls in ten times its u...
When the Fallout TV series was announced I, like I assume many others, assumed it was going to be an utter pile of garbage. Well, as we now know that couldn't be further from the truth. It was a smash hit, and this success has of course given the... | Read more »
Recruit two powerful-sounding students t...
I am a fan of anime, and I hear about a lot that comes through, but one that escaped my attention until now is A Certain Scientific Railgun T, and that name is very enticing. If it's new to you too, then players of Blue Archive can get a hands-on... | Read more »
Top Hat Studios unveils a new gameplay t...
There are a lot of big games coming that you might be excited about, but one of those I am most interested in is Athenian Rhapsody because it looks delightfully silly. The developers behind this project, the rather fancy-sounding Top Hat Studios,... | Read more »
Bound through time on the hunt for sneak...
Have you ever sat down and wondered what would happen if Dr Who and Sherlock Holmes went on an adventure? Well, besides probably being the best mash-up of English fiction, you'd get the Hidden Through Time series, and now Rogueside has announced... | Read more »
The secrets of Penacony might soon come...
Version 2.2 of Honkai: Star Rail is on the horizon and brings the culmination of the Penacony adventure after quite the escalation in the latest story quests. To help you through this new expansion is the introduction of two powerful new... | Read more »
The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »

Price Scanner via MacPrices.net

Apple’s 24-inch M3 iMacs are on sale for $150...
Amazon is offering a $150 discount on Apple’s new M3-powered 24″ iMacs. Prices start at $1149 for models with 8GB of RAM and 256GB of storage: – 24″ M3 iMac/8-core GPU/8GB/256GB: $1149.99, $150 off... Read more
Verizon has Apple AirPods on sale this weeken...
Verizon has Apple AirPods on sale for up to 31% off MSRP on their online store this weekend. Their prices are the lowest price available for AirPods from any Apple retailer. Verizon service is not... Read more
Apple has 15-inch M2 MacBook Airs available s...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs available starting at $1019 and ranging up to $300 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at Apple.... Read more
May 2024 Apple Education discounts on MacBook...
If you’re a student, teacher, or staff member at any educational institution, you can use your .edu email address when ordering at Apple Education to take up to $300 off the purchase of a new MacBook... Read more
Clearance 16-inch M2 Pro MacBook Pros in stoc...
Apple has clearance 16″ M2 Pro MacBook Pros available in their Certified Refurbished store starting at $2049 and ranging up to $450 off original MSRP. Each model features a new outer case, shipping... Read more
Save $300 at Apple on 14-inch M3 MacBook Pros...
Apple has 14″ M3 MacBook Pros with 16GB of RAM, Certified Refurbished, available for $270-$300 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year warranty is... Read more
Apple continues to offer 14-inch M3 MacBook P...
Apple has 14″ M3 MacBook Pros, Certified Refurbished, available starting at only $1359 and ranging up to $270 off MSRP. Each model features a new outer case, shipping is free, and an Apple 1-year... Read more
Apple AirPods Pro with USB-C return to all-ti...
Amazon has Apple’s AirPods Pro with USB-C in stock and on sale for $179.99 including free shipping. Their price is $70 (28%) off MSRP, and it’s currently the lowest price available for new AirPods... Read more
Apple Magic Keyboards for iPads are on sale f...
Amazon has Apple Magic Keyboards for iPads on sale today for up to $70 off MSRP, shipping included: – Magic Keyboard for 10th-generation Apple iPad: $199, save $50 – Magic Keyboard for 11″ iPad Pro/... Read more
Apple’s 13-inch M2 MacBook Airs return to rec...
Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices currently... Read more

Jobs Board

Liquor Stock Clerk - S. *Apple* St. - Idaho...
Liquor Stock Clerk - S. Apple St. Boise Posting Begin Date: 2023/10/10 Posting End Date: 2024/10/14 Category: Retail Sub Category: Customer Service Work Type: Part Read more
*Apple* App Developer - Datrose (United Stat...
…year experiencein programming and have computer knowledge with SWIFT. Job Responsibilites: Apple App Developer is expected to support essential tasks for the RxASL Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.