Using Dates
This task contains examples on creating, comparing, and converting dates. Listing 1 shows you how to get the current absolute time and convert it into a CFDate object.
Listing 1 Creating a CFDate object
CFAbsoluteTime absTime; |
CFDateRef aCFDate; |
absTime = CFAbsoluteTimeGetCurrent(); |
aCFDate = CFDateCreate(kCFAllocatorDefault, absTime); |
To compare two dates, use the compare function CFDateCompare
as
shown in Listing 2.
Listing 2 Comparing two CFDate objects
// Standard Core Foundation comparison result. |
CFComparisonResult result; |
// Create two CFDates from absolute time. |
date1 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()); |
date2 = CFDateCreate(kCFAllocatorDefault, CFAbsoluteTimeGetCurrent()); |
// Pass NULL for the context param. |
result = CFDateCompare(date1, date2, NULL); |
switch (result) { |
case kCFCompareLessThan: |
printf("date1 is before date2!\n"); |
break; |
case kCFCompareEqualTo: |
printf("date1 is the same as date2!\n"); |
break; |
case kCFCompareGreaterThan: |
printf("date1 is after date2!\n"); |
break; |
} |
The CFDateCompare
function
performs exact comparisons, which means it detects sub-second differences
between dates. You might want to compare dates with a less fine granularity.
For example, you might want to consider two dates equal if they
are within one minute of each other. This can be accomplished by
simply converting the CFDates to absolute time and comparing the
two floating-point values using your fuzziness factor. To compare
Gregorian units like month or week, you can convert both CFDates
to CFGregorianDate and compare the appropriate fields. Converting
absolute time to and from Gregorian dates is quite simple. Listing 3 demonstrates
how to do this.
Listing 3 Working with Gregorian dates
Boolean status; |
CFGregorianDate gregDate; |
CFAbsoluteTime absTime; |
// Construct a Gregorian date. |
gregDate.year = 1999; |
gregDate.month = 11; |
gregDate.day = 23; |
gregDate.hour = 17; |
gregDate.minute = 33; |
gregDate.second = 22.7; |
// Check the validity of the date. |
status = CFGregorianDateIsValid(gregDate, kCFGregorianAllUnits); |
printf("Is my Gregorian date valid? %d\n", status); |
// Convert the Gregorian date to absolute time. |
absTime = CFGregorianDateGetAbsoluteTime(gregDate, NULL); |
printf("The Absolute Time from a Gregorian date is: %d\n", absTime); |
Copyright © 2005 Apple Computer, Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2005-08-11