CTime Class

 

The new home for Visual Studio documentation is Visual Studio 2017 Documentation on docs.microsoft.com.

The latest version of this topic can be found at CTime Class.

Represents an absolute time and date.

Syntax

class CTime  

Members

Public Constructors

Name Description
CTime::CTime Constructs CTime objects in various ways.

Public Methods

Name Description
CTime::Format Converts a CTime object into a formatted string — based on the local time zone.
CTime::FormatGmt Converts a CTime object into a formatted string — based on UTC.
CTime::GetAsDBTIMESTAMP Converts the time information stored in the CTime object to a Win32-compatible DBTimeStamp structure.
CTime::GetAsSystemTime Converts the time information stored in the CTime object to a Win32-compatible SYSTEMTIME structure.
CTime::GetCurrentTime Creates a CTime object that represents the current time (static member function).
CTime::GetDay Returns the day represent by the CTime object.
CTime::GetDayOfWeek Returns the day of the week represented by the CTime object.
CTime::GetGmtTm Breaks down a CTime object into components — based on UTC.
CTime::GetHour Returns the hour represented by the CTime object.
CTime::GetLocalTm Breaks down a CTime object into components — based on the local time zone.
CTime::GetMinute Returns the minute represented by the CTime object.
CTime::GetMonth Returns the month represented by the CTime object.
CTime::GetSecond Returns the second represented by the CTime object.
CTime::GetTime Returns a __time64_t value for the given CTime object.
CTime::GetYear Returns the year represented by the CTime object.
CTime::Serialize64 Serializes data to or from an archive.

Operators

operator + – These operators add and subtract CTimeSpan and CTime objects.
operator +=, –= These operators add and subtract a CTimeSpan object to and from this CTime object.
operator = The assignment operator.
operator ==, < , etc. Comparison operators.

Remarks

CTime does not have a base class.

CTime values are based on coordinated universal time (UTC), which is equivalent to Coordinated Universal time (Greenwich Mean Time, GMT). See Time Management for information about how the time zone is determined.

When you create a CTime object, set the nDST parameter to 0 to indicate that standard time is in effect, or to a value larger than 0 to indicate that daylight saving time is in effect, or to a value less than zero to have the C run-time library code compute whether standard time or daylight saving time is in effect. tm_isdst is a required field. If not set, its value is undefined and the return value from mktime is unpredictable. If timeptr points to a tm structure returned by a previous call to asctime_s, _gmtime_s, or localtime_s, the tm_isdst field contains the correct value.

A companion class, CTimeSpan, represents a time interval.

The CTime and CTimeSpan classes are not designed for derivation. Because there are no virtual functions, the size of CTime and CTimeSpan objects is exactly 8 bytes. Most member functions are inline.

Note

The upper date limit is 12/31/3000. The lower limit is 1/1/1970 12:00:00 AM GMT.

For more information about using CTime, see the articles Date and Time, and Time Management in the Run-Time Library Reference.

Note

The CTime structure changed from MFC 7.1 to MFC 8.0. If you serialize a CTime structure by using the operator << under MFC 8.0 or a later version, the resulting file will not be readable on older versions of MFC.

Requirements

Header: atltime.h

CTime Comparison Operators

Comparison operators.

bool operator==(CTime time) const throw(); 
bool operator!=(CTime time) const throw();
bool operator<(CTime time) const throw();
bool operator>(CTime time) const throw();
bool operator<=(CTime time) const throw();
bool operator>=(CTime time) const throw(); 

Parameters

time
The CTime object to be compared.

Return Value

These operators compare two absolute times and return true if the condition is true; otherwise false.

Example

   CTime t1 = CTime::GetCurrentTime();
   CTime t2 = t1 + CTimeSpan(0, 1, 0, 0);    // 1 hour later
   ATLASSERT(t1 != t2);
   ATLASSERT(t1 < t2);
   ATLASSERT(t1 <= t2);   

CTime::CTime

Creates a new CTime object initialized with the specified time.

CTime() throw(); 
CTime(__time64_t time) throw();
CTime(int nYear, int nMonth, int nDay,
      int nHour, int nMin, int nSec, int nDST = -1);
CTime(WORD wDosDate, WORD wDosTime, int nDST = -1);
CTime(const SYSTEMTIME& st, int nDST = - 1) throw();
CTime(const FILETIME& ft, int nDST = - 1);
CTime(const DBTIMESTAMP& dbts,int nDST = -1) throw();

Parameters

timeSrc
Indicates a CTime object that already exists.

time
A __time64_t time value, which is the number of seconds after January 1, 1970 UTC. Note that this will be adjusted to your local time. For example, if you are in New York and create a CTime object by passing a parameter of 0, CTime::GetMonth will return 12.

In Visual C++ versions 6.0 and earlier, time was a value of time_t. Visual C++ .NET and later converts a time_t parameter to __time64_t.

nYear, nMonth, nDay, nHour, nMin, nSec
Indicates the date and time values to be copied into the new CTime object.

nDST
Indicates whether daylight savings time is in effect. Can have one of three values:

  • nDST set to 0Standard time is in effect.

  • nDST set to a value greater than 0Daylight savings time is in effect.

  • nDST set to a value less than 0The default. Automatically computes whether standard time or daylight savings time is in effect.

wDosDate, wDosTime
MS-DOS date and time values to be converted to a date/time value and copied into the new CTime object.

st
A SYSTEMTIME structure to be converted to a date/time value and copied into the new CTime object.

ft
A FILETIME structure to be converted to a date/time value and copied into the new CTime object.

dbts
A reference to a DBTimeStamp structure containing the current local time.

Remarks

Each constructor is described below:

  • CTime( );Constructs an uninitialized CTime object. This constructor allows you to define CTime object arrays. You should initialize such arrays with valid times before using.

  • CTime( const CTime& );Constructs a CTime object from another CTime value.

  • CTime( __time64_t );Constructs a CTime object from a __time64_t type. This constructor expects a UTC time and converts the result to a local time before storing the result.

  • CTime( int, int, ...);Constructs a CTime object from local time components with each component constrained to the following ranges:

    Component Range
    nYear 1970–3000
    nMonth 1–12
    nDay 1–31
    nHour 0-23
    nMin 0-59
    nSec 0-59

    This constructor makes the appropriate conversion to UTC. The Debug version of the Microsoft Foundation Class Library asserts if one or more of the time components are out of range. You must validate the arguments before calling. This constructor expects a local time.

  • CTime( WORD, WORD ) ; Constructs a CTime object from the specified MS-DOS date and time values. This constructor expects a local time.

  • CTime( const SYSTEMTIME& ) ; Constructs a CTime object from a SYSTEMTIME structure. This constructor expects a local time.

  • CTime( const FILETIME& ) ; Constructs a CTime object from a FILETIME structure. You most likely will not use CTime``FILETIME initialization directly. If you use a CFile object to manipulate a file, CFile::GetStatus retrieves the file time stamp for you through a CTime object initialized with a FILETIME structure. This constructor assumes a time based on UTC and automatically converts the value to local time before storing the result.

    Note

    The constructor using DBTIMESTAMP parameter is only available when OLEDB.h is included.

For more information, see the SYSTEMTIME and FILETIME structure in the Windows SDK. Also see the MS-DOS Date and Time entry in the Windows SDK.

Example

   time_t osBinaryTime;  // C run-time time (defined in <time.h>)
   time(&osBinaryTime) ;  // Get the current time from the 
                            // operating system.
   CTime time1; // Empty CTime. (0 is illegal time value.)
   CTime time2 = time1; // Copy constructor.
   CTime time3(osBinaryTime);  // CTime from C run-time time
   CTime time4(1999, 3, 19, 22, 15, 0); // 10:15PM March 19, 1999   

CTime::Format

Call this member function to create a formatted representation of the date-time value.

CString Format(LPCTSTR pszFormat) const; 
CString Format(UINT nFormatID) const; 

Parameters

pszFormat
A formatting string similar to the printf formatting string. Formatting codes, preceded by a percent ( %) sign, are replaced by the corresponding CTime component. Other characters in the formatting string are copied unchanged to the returned string. See the run-time function strftime for a list of formatting codes.

nFormatID
The ID of the string that identifies this format.

Return Value

A CString that contains the formatted time.

Remarks

If the status of this CTime object is null, the return value is an empty string.

This method throws an exception if the date-time value to format does not range from midnight, January 1, 1970 through December 31, 3000 Universal Coordinated Time (UTC).

Example

   CTime t(1999, 3, 19, 22, 15, 0); 
   // 10:15 PM March 19, 1999
   CString s = t.Format(_T("%A, %B %d, %Y"));
   ATLASSERT(s == _T("Friday, March 19, 1999"));   

CTime::FormatGmt

Generates a formatted string that corresponds to this CTime object.

CString FormatGmt(LPCTSTR pszFormat) const; 
CString FormatGmt(UINT nFormatID) const; 

Parameters

pszFormat
Specifies a formatting string similar to the printf formatting string. See the run-time function strftime for details.

nFormatID
The ID of the string that identifies this format.

Return Value

A CString that contains the formatted time.

Remarks

The time value is not converted and thus reflects UTC.

This method throws an exception if the date-time value to format does not range from midnight, January 1, 1970 through December 31, 3000 Universal Coordinated Time (UTC).

Example

See the example for CTime::Format.

CTime::GetAsDBTIMESTAMP

Call this member function to convert the time information stored in the CTime object to a Win32–compatible DBTimeStamp structure.

bool GetAsDBTIMESTAMP(DBTIMESTAMP& dbts) const throw();

Parameters

dbts
A reference to a DBTimeStamp structure containing the current local time.

Return Value

Nonzero if successful; otherwise 0.

Remarks

Stores the resulting time in the referenced dbts structure. The DBTIMESTAMP data structure initialized by this function will have its fraction member set to zero.

Example

   CTime t = CTime::GetCurrentTime();
   DBTIMESTAMP ts;
   t.GetAsDBTIMESTAMP(ts); // Retrieves the time in t into the ts structure

CTime::GetAsSystemTime

Call this member function to convert the time information stored in the CTime object to a Win32–compatible SYSTEMTIME structure.

bool GetAsSystemTime(SYSTEMTIME& st) const throw();

Parameters

timeDest
A reference to a SYSTEMTIME structure that will hold the converted date/time value of the CTime object.

Return Value

True if successful; otherwise false.

Remarks

GetAsSystemTime stores the resulting time in the referenced timeDest structure. The SYSTEMTIME data structure initialized by this function will have its wMilliseconds member set to zero.

Example

   // Convert CTime to FILETIME
   CTime time(CTime::GetCurrentTime());
   SYSTEMTIME timeDest;
   time.GetAsSystemTime(timeDest);
   FILETIME fileTime;
   ::SystemTimeToFileTime(&timeDest, &fileTime);   

CTime::GetCurrentTime

Returns a CTime object that represents the current time.

static CTime WINAPI GetCurrentTime() throw();

Remarks

Returns the current system date and time in Coordinated Universal Time (UTC).

Example

   CTime t = CTime::GetCurrentTime();   

CTime::GetDay

Returns the day represent by the CTime object.

int GetDay() const throw();

Return Value

Returns the day of the month, based on local time, in the range 1 through 31.

Remarks

This function calls GetLocalTm, which uses an internal, statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

   // Example for CTime::GetDay, CTime::GetMonth, and CTime::GetYear
   CTime t(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
   ATLASSERT(t.GetDay() == 19);
   ATLASSERT(t.GetMonth() == 3);
   ATLASSERT(t.GetYear() == 1999);

CTime::GetDayOfWeek

Returns the day of the week represented by the CTime object.

int GetDayOfWeek() const throw();

Return Value

Returns the day of the week based on local time; 1 = Sunday, 2 = Monday, to 7 = Saturday.

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

   // Print out the day of the week using localized day name
   UINT DayOfWeek[] = {
      LOCALE_SDAYNAME7,   // Sunday
      LOCALE_SDAYNAME1,   
      LOCALE_SDAYNAME2,
      LOCALE_SDAYNAME3,
      LOCALE_SDAYNAME4, 
      LOCALE_SDAYNAME5, 
      LOCALE_SDAYNAME6   // Saturday
   };
   TCHAR strWeekday[256];
   CTime time(CTime::GetCurrentTime());   // Initialize CTime with current time
   ::GetLocaleInfo(LOCALE_USER_DEFAULT,   // Get string for day of the week from system
      DayOfWeek[time.GetDayOfWeek()-1],   // Get day of week from CTime
      strWeekday, sizeof(strWeekday) / sizeof(strWeekday[0]));
   ATLTRACE(_T("%s\n"), strWeekday);               // Print out day of the week   

CTime::GetGmtTm

Gets a struct tm that contains a decomposition of the time contained in this CTime object.

struct tm* GetGmtTm(struct tm* ptm) const; 

Parameters

ptm
Points to a buffer that will receive the time data. If this pointer is NULL, an exception is thrown.

Return Value

A pointer to a filled-in struct tm as defined in the include file TIME.H. See gmtime, _gmtime32, _gmtime64 for the structure layout.

Remarks

GetGmtTm returns UTC.

ptm cannot be NULL. If you want to revert to the old behavior, in which ptm could be NULL to indicate that an internal, statically allocated buffer should be used, then undefine _SECURE_ATL.

Example

   // Compute difference between local time and GMT
   CTime time(CTime::GetCurrentTime());
   tm t1, t2;
   time.GetLocalTm(&t1);
   time.GetGmtTm(&t2);

   ATLTRACE(_T("Difference between local time and GMT is %d hours.\n"), 
      t1.tm_hour - t2.tm_hour);   

CTime::GetHour

Returns the hour represented by the CTime object.

int GetHour() const throw();

Return Value

Returns the hour, based on local time, in the range 0 through 23.

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

   // Example for CTime::GetHour, CTime::GetMinute, and CTime::GetSecond
   CTime t(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
   ATLASSERT(t.GetSecond() == 0);
   ATLASSERT(t.GetMinute() == 15);
   ATLASSERT(t.GetHour() == 22);   

CTime::GetLocalTm

Gets a struct tm containing a decomposition of the time contained in this CTime object.

struct tm* GetLocalTm(struct tm* ptm) const; 

Parameters

ptm
Points to a buffer that will receive the time data. If this pointer is NULL, an exception is thrown.

Return Value

A pointer to a filled-in struct tm as defined in the include file TIME.H. See gmtime, _gmtime32, _gmtime64 for the structure layout.

Remarks

GetLocalTm returns local time.

ptm cannot be NULL. If you want to revert to the old behavior, in which ptm could be NULL to indicate that an internal, statically allocated buffer should be used, then undefine _SECURE_ATL.

Example

   CTime t(1999, 3, 19, 22, 15, 0); // 10:15PM March 19, 1999
   tm osTime;  // A structure containing time elements.
   t.GetLocalTm(&osTime);
   ATLASSERT(osTime.tm_mon == 2); // Note zero-based month!   

CTime::GetMinute

Returns the minute represented by the CTime object.

int GetMinute() const throw();

Return Value

Returns the minute, based on local time, in the range 0 through 59.

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

See the example for GetHour.

CTime::GetMonth

Returns the month represented by the CTime object.

int GetMonth() const throw();

Return Value

Returns the month, based on local time, in the range 1 through 12 (1 = January).

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

See the example for GetDay.

CTime::GetSecond

Returns the second represented by the CTime object.

int GetSecond() const throw();

Return Value

Returns the second, based on local time, in the range 0 through 59.

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

See the example for GetHour.

CTime::GetTime

Returns a __time64_t value for the given CTime object.

__time64_t GetTime() const throw(); 

Return Value

GetTime will return the number of seconds between the current CTime object and January 1, 1970.

Example

   CTime t(2005, 10, 20, 23, 50, 0); // 11:50 PM October 20, 2005
   time_t osBinaryTime = t.GetTime();  // time_t defined in <time.h>

   _tprintf_s(_T("time_t = %ld\n"), osBinaryTime);

CTime::GetYear

Returns the year represented by the CTime object.

int GetYear();

Return Value

Returns the year, based on local time, in the range January 1,1970, to January 18, 2038 (inclusive).

Remarks

This function calls GetLocalTm, which uses an internal statically allocated buffer. The data in this buffer is overwritten because of calls to other CTime member functions.

Example

See the example for GetDay.

CTime::operator =

The assignment operator.

CTime& operator=(__time64_t time) throw();

Parameters

time
The new date/time value.

Return Value

The updated CTime object.

Remarks

This overloaded assignment operator copies the source time into this CTime object. The internal time storage in a CTime object is independent of time zone. Time zone conversion is not necessary during assignment.

CTime::operator +, -

These operators add and subtract CTimeSpan and CTime objects.

CTime operator+(CTimeSpan timeSpan) const throw(); 
CTime operator-(CTimeSpan timeSpan) const throw(); 
CTimeSpan operator-(CTime time) const throw(); 

Parameters

timeSpan
The CTimeSpan object to be added or subtracted.

time
The CTime object to be subtracted.

Return Value

A CTime or CTimeSpan object representing the result of the operation.

Remarks

CTime objects represent absolute time, CTimeSpan objects represent relative time. The first two operators allow you to add and subtract CTimeSpan objects to and from CTime objects. The third operator allows you to subtract one CTime object from another to yield a CTimeSpan object.

Example

   CTime t1(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
   CTime t2(1999, 3, 20, 22, 15, 0); // 10:15 PM March 20, 1999
   CTimeSpan ts = t2 - t1;             // Subtract 2 CTimes
   ATLASSERT(ts.GetTotalSeconds() == 86400L);
   ATLASSERT((t1 + ts) == t2);       // Add a CTimeSpan to a CTime.
   ATLASSERT((t2 - ts) == t1);       // Subtract a CTimeSpan from a CTime.   

CTime::operator +=, -=

These operators add and subtract a CTimeSpan object to and from this CTime object.

CTime& operator+=(CTimeSpan span) throw();
CTime& operator-=(CTimeSpan span) throw();

Parameters

span
The CTimeSpan object to be added or subtracted.

Return Value

The updated CTime object.

Remarks

These operators allow you to add and subtract a CTimeSpan object to and from this CTime object.

Example

   CTime t(1999, 3, 19, 22, 15, 0); // 10:15 PM March 19, 1999
   t += CTimeSpan(0, 1, 0, 0);      // 1 hour exactly
   ATLASSERT(t.GetHour() == 23);   

CTime::Serialize64

Note

This method is only available in MFC projects.

Serializes the data associated with the member variable to or from an archive.

CArchive& Serialize64(CArchive& ar);

Parameters

ar
The CArchive object that you want to update.

Return Value

The updated CArchive object.

See Also

asctime_s, _wasctime_s
_ftime_s, _ftime32_s, _ftime64_s
gmtime_s, _gmtime32_s, _gmtime64_s
localtime_s, _localtime32_s, _localtime64_s
strftime, wcsftime, _strftime_l, _wcsftime_l
time, _time32, _time64
CTimeSpan Class
Hierarchy Chart
ATL/MFC Shared Classes