3

What is the correct datatype for a field that represents a time of day for a recurring event?

I'm building a class enrollment system (for a hypothetical university, as a school project), and I need to record what time a class starts and ends at. It's assumed that classes meet at the same time every week, so it seems like it would be simplest to store time information with three fields: start time, end time, and day of the week.

Is this the correct approach? My first instinct is to store times as date/time and hide the date part from the user, but I worry that doing this might cause me trouble later on.

1
  • Does your assignment mention anything about timezones, are you expected to handle them? If you're in US and my user's timezone is set to UK - should I see the class starting at 8 AM or somewhere in the afternoon? In extreme case your date/time field with hidden date might wrap to next/previous day depending on the viewer :) Read about time-based formulas, they'll all "flatten" the time to GMT, for example here: help.salesforce.com/apex/HTViewSolution?id=000004518.
    – eyescream
    Commented May 13, 2014 at 18:03

2 Answers 2

3

Time, Date and Datetime: Variables declared with any of these data types hold time, date, or time and date values combined:

  • The Date data type does hold a time, even though it's set to 0 by default and you can't modify it
  • The date and time classes also have instance methods for converting from one format to another
  • You can also manipulate and interrogate the values by using a range of instance methods

You can find all you need in the documentation http://www.salesforce.com/us/developer/docs/apexcode/Content/langCon_apex_primitives.htm

1
  • I think the question is about sObject custom fields and not types of apex variables. It's clearly asking how to store them, not how to work with them later in the code.
    – eyescream
    Commented May 13, 2014 at 17:58
2

As you have noticed there isn't much built in support for time: you can't create a Time field on an SObject and therefore apex:inputField doesn't render a nice time selection widget. There is an Apex Time class but that doesn't help very much.

I built a booking system for a charity and ended up using picklists for the class start times because the classes only ever started on the hour and on the half your. This made the user interface cleaner in that the user could just pick from "8 am", "8:30 am", "9 am" etc. I then had a formula field to convert these selections into minutes in the day (TimeInMinutes__c) behind the scenes:

CASE(Time__c,
'8 am', 480,
'8:30 am', 510,
'9 am', 540,
...

for use in other calculations.

Its in use now with no complaints (at least about that bit).

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .