1、localtime返回的指针是个静态成员变量
1 struct tm *pstTmp1, *psttTmp2; 2 time_t tTime1 = , tTime2; 3 4 tTime1 = 1354852746; 5 tTime2 = 1350000000 6 7 pstTmp1 = localtime(&tTime1); 8 pstTmp2 = localtime(&Time2);
上述中的pstTmp1和pstTmp2指向的变量是同一个,所以它们的值是一样的。需要注意调用完localtime后,立马取出其值。
2、localtime传入的参数。
VS 2010 中的localtime的参数是__int64,所以如果传进去的数是32位的地址,那么可能会导致localtime返回NULL(我就被这样的事情困扰了半个小时)。
定义了如下一个结构体,其中m_uiTimeSaleBegin和m_uiTimeSaleEnd存放两个时间值
struct tmp { int m_iDateSold; //当天已卖出的个数 unsigned int m_uiTimeSaleBegin; //限时销售开始时间 unsigned int m_uiTimeSaleEnd; //限时销售结束时间 int m_iSaleTag; //标签(热卖,推荐等) };
然后调用一下代码来显示:
{ if (pstCommodity->m_uiTimeSaleBegin > 0) { TRACE("begintime = %u\n", pstCommodity->m_uiTimeSaleBegin); SYSTEMTIME stTimeTmp; struct tm *ptmTmp; ptmTmp = localtime((time_t *)&(pstCommodity->m_uiTimeSaleBegin)); if(NULL == ptmTmp) { TRACE("ptmTmp is NULL.\n"); } else { stTimeTmp.wYear = ptmTmp->tm_year + 1900; stTimeTmp.wMonth = ptmTmp->tm_mon + 1; stTimeTmp.wDay = ptmTmp->tm_mday; m_LimitBeginTime.SetTime(&stTimeTmp); m_LimitBeginTime.SetFormat(L"yyyy/MM/dd"); SYSTEMTIME SysTime; m_LimitBeginTime.SendMessage(DTM_GETSYSTEMTIME, NULL, (LPARAM)&SysTime); m_LimitBeginTime.SendMessage(DTM_SETSYSTEMTIME, GDT_VALID, (LPARAM)&SysTime); } } else { m_LimitBeginTime.SetFormat(_T(" ")); SYSTEMTIME SysTime; m_LimitBeginTime.SendMessage(DTM_GETSYSTEMTIME, NULL, (LPARAM)&SysTime); m_LimitBeginTime.SendMessage(DTM_SETSYSTEMTIME, GDT_NONE, (LPARAM)&SysTime); } if (pstCommodity->m_uiTimeSaleEnd > 0) { TRACE("endtime = %u\n", pstCommodity->m_uiTimeSaleEnd); time_t tt; tt = time(NULL); TRACE("tt = %u\n", tt); SYSTEMTIME stTimeTmp; struct tm *ptmTmp; ptmTmp = localtime((time_t *)&(pstCommodity->m_uiTimeSaleEnd)); if(NULL == ptmTmp) { TRACE("ptmTmp is NULL.\n"); } else { stTimeTmp.wYear = ptmTmp->tm_year+1900; stTimeTmp.wMonth = ptmTmp->tm_mon+1; stTimeTmp.wDay = ptmTmp->tm_mday; m_LimitEndTime.SetTime(&stTimeTmp); m_LimitEndTime.SetFormat(L"yyyy/MM/dd"); SYSTEMTIME SysTime; m_LimitEndTime.SendMessage(DTM_GETSYSTEMTIME, NULL, (LPARAM)&SysTime); m_LimitEndTime.SendMessage(DTM_SETSYSTEMTIME, GDT_VALID, (LPARAM)&SysTime); } }
奇葩的事情出现了,传给pstCommodity->m_uiSaleBeginTime 和pstCommodity->m_uiSaleEndTime的值是一样的,结果在BeginTime的循环中判断ptmTmp为NULL,而EndTime的循环中却能够正常的将时间给显示出来,后来查了好久才知道,原来是32位的指针地址赋给了64位的指针地址。回头看下结构体的定义就明白了(m_sSaleTag为0)。