Example #1
0
TDuration CDateTime::operator-(const CDateTime &datetime) const
{
    TDuration d = { 0, 0 };

    if (!isValid() || !datetime.isValid())
    {
        return d;
    }

    int year = datetime.getYear();

    // Différence de jours
    int n1 = dayOfYear(m_year, m_month, m_day) - 1;
    int n2 = dayOfYear(year, datetime.getMonth(), datetime.getDay()) - 1;

    d.days = n1 - n2;

    // Durée positive
    if (year < m_year)
    {
        for (int a = year; a < m_year; ++a)
        {
            d.days += (isLeapYear(a) ? 366 : 365);
        }
    }
    // Durée négative
    else if (year > m_year)
    {
        for (int a = m_year; a < year; ++a)
        {
            d.days -= (isLeapYear(a) ? 366 : 365);
        }
    }

    // Différence de secondes
    int s1 = 3600 * m_hour + 60 * m_minute + m_second;
    int s2 = 3600 * datetime.getHour() + 60 * datetime.getMinute() + datetime.getSecond();

    d.seconds = s1 - s2;

    // Le nombre de secondes et le nombre de jours doivent être du même signe
    if (d.seconds < 0 && d.days > 0)
    {
        --d.days;
        d.seconds += 86400;
    }
    else if (d.seconds > 0 && d.days < 0)
    {
        ++d.days;
        d.seconds -= 86400;
    }

    return d;
}
Example #2
0
// ISO compliant week numbering, not traditional number, rename in KDE5 to isoWeekNumber()
// JPL still need to fully clean up here
int KCalendarSystem::weekNumber( const QDate &date, int *yearNum ) const
{
    if ( isValid( date ) ) {
        QDate firstDayWeek1, lastDayOfYear;
        int y = year( date );
        int week;
        int weekDay1, dayOfWeek1InYear;

        // let's guess 1st day of 1st week
        setDate( firstDayWeek1, y, 1, 1 );
        weekDay1 = dayOfWeek( firstDayWeek1 );

        // iso 8601: week 1  is the first containing thursday and week starts on monday
        if ( weekDay1 > 4 /*Thursday*/ ) {
            firstDayWeek1 = addDays( firstDayWeek1 , daysInWeek( date ) - weekDay1 + 1 ); // next monday
        }

        dayOfWeek1InYear = dayOfYear( firstDayWeek1 );

        // our date in prev year's week
        if ( dayOfYear( date ) < dayOfWeek1InYear ) { 
            if ( yearNum ) {
                *yearNum = y - 1;
            }
            return weeksInYear( y - 1 );
        }

        // let's check if its last week belongs to next year
        d->setAnyDate( lastDayOfYear, y + 1, 1, 1 );
        lastDayOfYear = addDays( lastDayOfYear, -1 );
        // if our date is in last week && 1st week in next year has thursday
        if ( ( dayOfYear( date ) >= daysInYear( date ) - dayOfWeek( lastDayOfYear ) + 1 )
             && dayOfWeek( lastDayOfYear ) < 4 ) {
            if ( yearNum ) {
                * yearNum = y + 1;
            }
             week = 1;
        } else {
            // To calculate properly the number of weeks from day a to x let's make a day 1 of week
            if( weekDay1 < 5 ) {
                firstDayWeek1 = addDays( firstDayWeek1, -( weekDay1 - 1 ) );
            }

            week = firstDayWeek1.daysTo( date ) / daysInWeek( date ) + 1;
        }

        return week;
    }

    return -1;
}
Example #3
0
const char *MSMBSDate::format(MSString& aString_,const char *format_) const
{
  #ifdef MS_THREAD_SAFE_FUNCTIONS
  struct tm tms;
  #endif //MS_THREAD_SAFE_FUNCTIONS

  MSString aString(0,((format_!=0)?strlen(format_):0)+3);
  // __tm_zone, a member of struct tm for the sun architecture
  // must be initialized if the strftime format %Z is used. Can
  // get this value from localtime.
  time_t now=time(0);
  struct tm *pCalendarTime=MS_LOCALTIME(&now,&tms);
  MSMonth m; MSDay d; MSYear y;
  asMonthDayYear(m,d,y);
  pCalendarTime->tm_sec=0;
  pCalendarTime->tm_min=0;
  pCalendarTime->tm_hour=0;
  pCalendarTime->tm_mday=d;
  pCalendarTime->tm_mon=m-1;
  pCalendarTime->tm_year=y-1900;
  pCalendarTime->tm_wday=weekDay()==7?0:weekDay();
  pCalendarTime->tm_yday=dayOfYear()-1;
  pCalendarTime->tm_isdst=-1;
  int numberOfChars;
  while ((numberOfChars=strftime((char*)aString.string(),aString.length(),format_,pCalendarTime))==0)
   {
     aString=MSString(0,2*aString.length());
   }
  // remove the terminating null from strftime. strftime returns the number of characters
  // produced not including the terminating null character.
  aString=MSString(aString.string(),numberOfChars);
  aString_=aString.string();
  return aString_;
}
int KCalendarSystemHebrew::weekNumber(const TQDate& date, int * yearNum) const
{
  TQDate firstDayWeek1, lastDayOfYear;
  int y = year(date);
  int week;
  int weekDay1, dayOfWeek1InYear;

  // let's guess 1st day of 1st week
  setYMD(firstDayWeek1, y, 1, 1);
  weekDay1 = dayOfWeek(firstDayWeek1);

  // iso 8601: week 1  is the first containing thursday and week starts on
  // monday
  if (weekDay1 > 4 /*Thursday*/)
    firstDayWeek1 = addDays(firstDayWeek1 , 7 - weekDay1 + 1); // next monday

  dayOfWeek1InYear = dayOfYear(firstDayWeek1);

  if ( dayOfYear(date) < dayOfWeek1InYear ) // our date in prev year's week
  {
    if ( yearNum )
      *yearNum = y - 1;
    return weeksInYear(y - 1);
  }

  // let's check if its last week belongs to next year
  setYMD(lastDayOfYear, y + 1, 1, 1);
  lastDayOfYear = addDays(lastDayOfYear, -1);
  if ( (dayOfYear(date) >= daysInYear(date) - dayOfWeek(lastDayOfYear) + 1)
       // our date is in last week
       && dayOfWeek(lastDayOfYear) < 4) // 1st week in next year has thursday
    {
      if ( yearNum )
        *yearNum = y + 1;
      week = 1;
    }
  else
  {
   if( weekDay1 < 5 ) // To calculate properly the number of weeks
                     //  from day a to x let's make a day 1 of week
      firstDayWeek1 = addDays( firstDayWeek1, -( weekDay1 - 1));

   week = firstDayWeek1.daysTo(date) / 7 + 1;
  }

  return week;
}
Example #5
0
/*
 * The number of days elapsed between the Gregorian date 12/31/1 BC and DATE.
 * The Gregorian date Sunday, December 31, 1 BC is imaginary.
 */
long int greg2abs( date_t d )			/* "absolute date" */ 
{
    return ((long) dayOfYear (d)	/* days this year */
            + 365L * (long) (d.yy - 1)	/* + days in prior years */
            + (long) ((d.yy - 1) / 4	/* + Julian Leap years */
                      - (d.yy - 1) / 100	/* - century years */
                      + (d.yy - 1) / 400));	/* + Gregorian leap years */
}
Example #6
0
int
yearOfWeek(time_t t, bool beginOnMonday)
{
    const struct tm* tms = clocaltime(&t);
    int tm_year = tms->tm_year;

    int lastDayOfYear = dayOfYear(beginOfYear(sameTimeNextYear(t)) - 1);
    if (dayOfYear(t) < 4)
    {
        if (dayOfWeek(t, beginOnMonday) - dayOfYear(t) >= 3)
            return 1900 + tm_year - 1;
    }
    else if (dayOfYear(t) > lastDayOfYear - 4)
    {
        if (dayOfYear(t) - dayOfWeek(t, beginOnMonday) > lastDayOfYear - 4)
            return 1900 + tm_year + 1;
    }
    return 1900 + tm_year;
}
Example #7
0
void TimeStamp::add( int32 days, int32 hours, int32 mins, int32 secs, int32 msecs )
{
    m_day = days + dayOfYear();
    m_hour += hours;
    m_minute += mins;
    m_second += secs;
    m_msec += msecs;

    rollOver();
}
Example #8
0
 Month Date::month() const {
     Day d = dayOfYear(); // dayOfYear is 1 based
     Integer m = d/30 + 1;
     bool leap = isLeap(year());
     while (d <= monthOffset(Month(m),leap))
         --m;
     while (d > monthOffset(Month(m+1),leap))
         ++m;
     return Month(m);
 }
 inline BTime dateTimeToBTime(QDateTime dateTime)
 {
     auto date = dateTime.date();
     auto time = dateTime.time();
     BTime btime;
     btime.year = date.year();
     btime.day = date.dayOfYear();
     btime.hour = time.hour();
     btime.min = time.minute();
     btime.sec = time.second();
     btime.fract = time.msec();
     return btime;
 }
Example #10
0
/***********************************************************************
* Function:  daysBetween()
* Description: Returns the number of days between two given dates.
***********************************************************************/
int daysBetween( struct date *firstDate, struct date *secondDate )
{
	int numOfDays;
	int dayNum1, dayNum2;
	
	/*
	* Use 'dayOfYear()' function to calculate
	* the number of days between the two date arguments.
	*/
	dayNum1 = dayOfYear( firstDate );
	dayNum2 = dayOfYear( secondDate );
	
	/*
	*  Validate both arguments.
	*/
	
	if ((dayNum1 == -1) || (dayNum2 == -1))
	    numOfDays = -1;
 	else
	    numOfDays = abs( dayNum2 - dayNum1 );

	return numOfDays;
}
int main(void)
{

	while (1)
	{
		int day=0;
		int month = 0;
		int year = 0;
		scanf("%d", &day);
		scanf("%d", &month);
		scanf("%d", &year);
		printf("Number of Days: %d\n", dayOfYear(day, month, year));
	}
}
Example #12
0
int DateTime::week(int firstDayOfWeek) const
{
	poco_assert (firstDayOfWeek >= 0 && firstDayOfWeek <= 6);

	/// find the first firstDayOfWeek.
	int baseDay = 1;
	while (DateTime(_year, 1, baseDay).dayOfWeek() != firstDayOfWeek) ++baseDay;

	int doy  = dayOfYear();
	int offs = baseDay <= 4 ? 0 : 1; 
	if (doy < baseDay)
		return offs;
	else
		return (doy - baseDay)/7 + 1 + offs;
}
Example #13
0
unsigned int CDateTime::timestamp(int year, unsigned int month, unsigned int day, unsigned int hour, unsigned int minute, unsigned int second)
{
    // Date incorrectes
    if (year < 1970 || !isValid(year, month, day, hour, minute, second))
    {
        return static_cast<unsigned int>(-1);
    }

    unsigned int n = dayOfYear(year, month, day) - 1;

    for (int a = 1970 ; a < year ; ++a)
    {
        n += (isLeapYear(a) ? 366 : 365);
    }

    return (n * 86400 + 3600 * hour + 60 * minute + second);
}
Example #14
0
/** week starting on monday, 0 based. */
int16 TimeStamp::dayOfWeek() const
{
    // consider 1700 the epoch
    if ( m_year < 1700 )
        return -1;

    // compute days since epoch.
    int32 nyears = m_year - 1700;
    int32 nday = nyears * 365;

    // add leap years (up to the previous year. This year is  computed in dayOfYear()
    if( m_year > 1700 )
        nday += ((nyears-1) / 4) - ((nyears-1) / 100) + ((nyears-1) / 400);

    // add day of the year.
    nday += dayOfYear();

    // add epoch (1/1/1700 was a Friday)
    nday += 4;

    nday %= 7;
    return nday;
}
Example #15
0
unsigned int CDateTime::weekOfYear(int year, unsigned int month, unsigned int day)
{
    if (!isValid(year, month, day))
    {
        return 0;
    }

    CDateTime d1(year, month, day);
    int a = dayOfWeek(year, month, day);
    d1.addDays(4 - a); // Jeudi de cette semaine

    int y1 = d1.getYear();

    CDateTime d2(y1, 1, 4);
    int b = dayOfWeek(y1, 1, 4);
    d2.addDays(1 - b); // Lundi de cette semaine

    int y2 = d2.getYear();

    if (y1 < y2)
    {
        unsigned int a1 = (isLeapYear(y1) ? 366 : 365) - dayOfYear(y1, d1.getMonth(), d1.getDay());
        unsigned int a2 = dayOfYear(y2, d2.getMonth(), d2.getDay());

        return (1 + (a1 + a2) / 7);
    }
    else if (y1 > y2)
    {
        unsigned int a1 = dayOfYear(y1, d1.getMonth(), d1.getDay());
        unsigned int a2 = (isLeapYear(y2) ? 366 : 365) - dayOfYear(y2, d2.getMonth(), d2.getDay());

        return (1 + (a1 + a2) / 7);
    }
    else
    {
        unsigned int a1 = dayOfYear(y1, d1.getMonth(), d1.getDay());
        unsigned int a2 = dayOfYear(y2, d2.getMonth(), d2.getDay());

        return (1 + (a2 > a1 ? a2 - a1 : a1 - a2) / 7);
    }
}
Example #16
0
std::string Timestamp::format(const std::string& format) const
{
    char buf[20];
    uint16_t year, month, day, hour, minute, second, millisecond;
    calcFromJulDay(_time, year, month, day, hour, minute, second, millisecond);

    FormatContext context(format);
    std::stringstream ss;
    while(!context.ready()) {
        char c = context.nextFormatSpecifier();
        switch(c) {
        case '%': {
            char n = context.nextFormatSpecifier();
            switch(n) {
            case 'Y':
                ss << std::setw(4) << std::setfill('0') << itoa(year, buf);
                break;
            case 'm':
                ss << std::setw(2) << std::setfill('0') << itoa(month, buf);
                break;
            case 'd':
                ss << std::setw(2) << std::setfill('0') << itoa(day, buf);
                break;
            case 'F': {
                if(year > 1000) {
                    itoa(year, buf);
                } else if(year > 100) {
                    buf[0] = '0';
                    itoa(year, &buf[1]);
                } else if(year > 10) {
                    buf[0] = '0';
                    buf[1] = '0';
                    itoa(year, &buf[2]);
                } else {
                    buf[0] = '0';
                    buf[1] = '0';
                    buf[2] = '0';
                    itoa(year, &buf[3]);
                }
                buf[4] = '-';
                if(month > 9) {
                    itoa(month, &buf[5]);
                } else {
                    buf[5] = '0';
                    itoa(month, &buf[6]);
                }
                buf[7] = '-';
                if(day > 9) {
                    itoa(day, &buf[8]);
                } else {
                    buf[8] = '0';
                    itoa(day, &buf[9]);
                }
                buf[10] = 'T';
                if(hour > 9) {
                    itoa(hour, &buf[11]);
                } else {
                    buf[11] = '0';
                    itoa(hour, &buf[12]);
                }
                buf[13] = ':';
                if(minute > 9) {
                    itoa(minute, &buf[14]);
                } else {
                    buf[14] = '0';
                    itoa(minute, &buf[15]);
                }
                buf[16] = ':';
                if(second > 9) {
                    itoa(second, &buf[17]);
                } else {
                    buf[17] = '0';
                    itoa(second, &buf[18]);
                }
                ss << buf;
                break;
            }
            case 'j':
                ss << std::setw(3) << std::setfill('0') << itoa(dayOfYear(), buf);
                break;
            case 'U':
                ss << std::setw(2) << std::setfill('0') << itoa(weekOfYear(), buf);
                break;
            case 'w':
                ss << itoa(dayOfWeek(), buf);
                break;
            case 'H':
                ss << std::setw(2) << std::setfill('0') << itoa(hour, buf);
                break;
            case 'M':
                ss << std::setw(2) << std::setfill('0') << itoa(minute, buf);
                break;
            case 'S':
                ss << std::setw(2) << std::setfill('0') << itoa(second, buf);
                break;
            case 's':
                ss << std::setw(3) << std::setfill('0') << itoa(millisecond, buf);
                break;
            }
            break;
        }
        default:
            ss << c;
        }
    }

    return ss.str();
}
Example #17
0
 inline Day Date::dayOfMonth() const {
     return dayOfYear() - monthOffset(month(),isLeap(year()));
 }
Example #18
0
/***********************************************************************
* Function:  calendar()
* Description: Illustrates some general calendar functions.
************************************************************************/
long calendar( long callParm )
{
	volatile char  *temp;
	volatile short  days;
	volatile int    status;
	volatile int    dayNumber, numOfDays;
	struct date firstDate, secondDate;   /* Local month date structures */
	struct date lclMonthDate;
	
	/*
	*  Initialize the year1997 structure
	*/
	year1997.yearName = "1997";
	year1997.month    = &MONTH[0];
	year1997.initId   = INITIALIZED;
	
	/*
	*  Setup 'temp' and 'days', useful to use as watch-window variables while stepping through the
	*  next set of instructions to illustrate how the structure is arranged.
	*/
	temp = year1997.yearName;
	
	temp = year1997.month[0].monthName;
	days = year1997.month[0].numOfDays;
	temp = year1997.month[0].startDay;
	
	temp = year1997.month[4].monthName;
	days = year1997.month[4].numOfDays;
	temp = year1997.month[4].startDay;
	
	temp = year1997.month[10].monthName;
	days = year1997.month[10].numOfDays;
	temp = year1997.month[10].startDay;
	
	/*
	*  Given a specific date, determine the 'day of the year'.
	*  For example, January 1, is day number one, December 31 is
	*  day 365 in 1997. If dayOfYear() returns a -1, then the year1997 structure
	*  was never properly initialized, that is, an error condition.
	*/
	glbMonthDate.monthName = "January";
	glbMonthDate.date      = 15;
	dayNumber = dayOfYear( &glbMonthDate );
	
	glbMonthDate.monthName = "October";
	glbMonthDate.date      = 13;
	dayNumber = dayOfYear( &glbMonthDate );
	
	glbMonthDate.monthName = "WINDober";     /* error case */
	glbMonthDate.date      = 30;
	dayNumber = dayOfYear( &glbMonthDate );
	
	
	/*
	*  Do the inverse operation of the operation above, that is, 
	*  given a specific 'day number', calculate the month and day.
	*  For example, for day number 16, dateForDayNum returns 
	*  January, 16th.  This function returns a 'status' that indicates
	*  if the date argument is legal. The month information is returned
	*  via the lclMonthDate argument.
	*/
	
	dayNumber = 134;          /* getting date for a legal day number */
	status = dateForDayNum( dayNumber, &lclMonthDate );
	
	/*
	* The locals window view of  'status' shows a valid dayNumber arugmnet. 
	* Also, either view the contents of lclMonthDate or view
	* the temp and days variables below.
	*/
	temp = lclMonthDate.monthName;
	days = lclMonthDate.date;
	
	/* 
	* Try an invalid day number and check status in the local window.
	*/
	dayNumber = 366;
	status = dateForDayNum( dayNumber, &lclMonthDate );
	
	/*
	*  Given two dates, calculate the number of days between them,
	*  excluding the boundary dates. For example, the number of days
	*  between January 1 and January 3, is one day, excluding the boundary dates.
	*/
	firstDate.monthName = "June"; 
	firstDate.date = 17;
	secondDate.monthName = "September";
	secondDate.date = 23;
	
	numOfDays = daysBetween( &firstDate, &secondDate );

	return ((long) *temp);
}
Example #19
0
unsigned MSMBSDate::weekOfYear(void) const
{ return (dayOfYear()/7)+1; }
Example #20
0
void testDayOfYear(int day, int month, int year)
{
  printf ("%d/%d/%d => %d\n", day, month, year,
          dayOfYear(day, month, year));
}
Example #21
0
 // Format:
 //    '%a' : Weekday abbreviated name (Sun, Mon, ..., Sat)
 //    '%A' : Weekday full name (Sunday, Monday, ..., Saturday)
 //    '%w' : Numeric representation of the day of the week (0 = Sunday, 6 = Saturday)
 //    '%d' : Day of the month, 2 digits with leading zeros (01..31)
 //    '%D' : Day of the month without leading zeros (1..31)
 //    '%b' : Month abbreviated name (Jan, Feb, ..., Dec)
 //    '%B' : Month full name (January, February, ..., December)
 //    '%m' : Numeric representation of a month, with leading zeros (01..12)
 //    '%y' : Two digits year (99, 00...)
 //    '%Y' : A full numeric representation of a year, 4 digits (1999, 2000...)
 //    '%H' : 24-hour format of an hour with leading zeros (00..23)
 //    '%I' : Hour (12-hour clock) as a zero-padded decimal number (01, 02, ..., 12)
 //    '%p' : AM or PM
 //    '%M' : Minutes with leading zeros (00..59)
 //    '%S' : Seconds, with leading zeros (00..59)
 //    '%z' : UTC offset in the form +HHMM or -HHMM (+0000, -0400, +1030, ...)
 //    '%j' : Day of the year as a zero-padded decimal number (001, 002, ..., 366)    
 //    '%c' : Date and time representation (Tue Aug 16 2015 21:30:00 +0000)
 // Returns resulting string length without trailing zero.
 // Example:
 //   char str[50];
 //   datetime.format(str, "%a %b %d %Y %H:%M:%S %z");  // equivalent to "%c"
 uint16_t MTD_FLASHMEM DateTime::format(char* outbuf, char const* formatstr)
 {
     static char const* DAYS[]   = {FSTR("Sunday"), FSTR("Monday"), FSTR("Tuesday"), FSTR("Wednesday"), FSTR("Thursday"), FSTR("Friday"), FSTR("Saturday")};
     static char const* MONTHS[] = {FSTR("January"), FSTR("February"), FSTR("March"), FSTR("April"), FSTR("May"), FSTR("June"), FSTR("July"), FSTR("August"), FSTR("September"), FSTR("October"), FSTR("November"), FSTR("December")};
     
     char* outbuf_start = outbuf;
     
     for (; getChar(formatstr); ++formatstr)
     {
         if (getChar(formatstr) == '%')
         {
             ++formatstr;
             switch (getChar(formatstr))
             {
                 case '%':
                     *outbuf++ = '%';
                     break;
                 case 'a':
                     outbuf += sprintf(outbuf, FSTR("%.3s"), DAYS[dayOfWeek()]);
                     break;
                 case 'A':
                     outbuf += sprintf(outbuf, FSTR("%s"), DAYS[dayOfWeek()]);
                     break;
                 case 'w':
                     outbuf += sprintf(outbuf, FSTR("%d"), dayOfWeek());
                     break;
                 case 'd':
                     outbuf += sprintf(outbuf, FSTR("%02d"), day);
                     break;
                 case 'D':
                     outbuf += sprintf(outbuf, FSTR("%d"), day);
                     break;
                 case 'b':
                     outbuf += sprintf(outbuf, FSTR("%.3s"), MONTHS[month - 1]);
                     break;
                 case 'B':
                     outbuf += sprintf(outbuf, FSTR("%s"), MONTHS[month - 1]);
                     break;
                 case 'm':
                     outbuf += sprintf(outbuf, FSTR("%02d"), month);
                     break;
                 case 'y':
                     outbuf += sprintf(outbuf, FSTR("%02d"), year % 100);
                     break;
                 case 'Y':
                     outbuf += sprintf(outbuf, FSTR("%d"), year);
                     break;
                 case 'H':
                     outbuf += sprintf(outbuf, FSTR("%02d"), hours);
                     break;
                 case 'I':
                     outbuf += sprintf(outbuf, FSTR("%02d"), (hours == 0 || hours == 12)? 12 : (hours % 12));
                     break;
                 case 'p':
                     outbuf += sprintf(outbuf, FSTR("%s"), hours > 11? FSTR("PM") : FSTR("AM"));
                     break;
                 case 'M':
                     outbuf += sprintf(outbuf, FSTR("%02d"), minutes);
                     break;
                 case 'S':
                     outbuf += sprintf(outbuf, FSTR("%02d"), seconds);
                     break;
                 case 'z':
                     outbuf += sprintf(outbuf, FSTR("%+03d%02d"), timezoneHours, timezoneMinutes);
                     break;
                 case 'j':
                     outbuf += sprintf(outbuf, FSTR("%03d"), dayOfYear());
                     break;
                 case 'c':
                     outbuf += format(outbuf, FSTR("%a %b %d %Y %H:%M:%S %z"));
                     break;
             }
         }
         else
             *outbuf++ = getChar(formatstr);
     }
     *outbuf = 0;
     return outbuf - outbuf_start;
 }
Example #22
0
RTCx::time_t RTCx::mktime(struct tm *tm)
{
  // Normalise the time
  tm->tm_min += (tm->tm_sec / 60);
  tm->tm_sec = (tm->tm_sec % 60);
  if (tm->tm_sec < 0) {
    tm->tm_sec += 60;
    --(tm->tm_min);
  }

  tm->tm_hour += (tm->tm_min / 60);
  tm->tm_min = (tm->tm_min % 60);
  if (tm->tm_min < 0) {
    tm->tm_min += 60;
    --(tm->tm_hour);
  }

  tm->tm_mday += (tm->tm_hour / 24);
  tm->tm_hour = (tm->tm_hour % 24);
  if (tm->tm_hour < 0) {
    tm->tm_hour += 24;
    --(tm->tm_mday);
  }

  if (tm->tm_mon < 0 || tm->tm_mon > 11 || tm->tm_mday < 1)
    return -1;

  // Normalise the date
  while (true) {
    uint8_t dim = daysInMonth(tm->tm_year+1900, tm->tm_mon+1);
    if (tm->tm_mday > dim) {
      tm->tm_mday -= dim;
      ++(tm->tm_mon);
      if (tm->tm_mon == 12) {
	tm->tm_mon = 0;
	++(tm->tm_year);
      }
      continue;
    }
    
    if (tm->tm_mday < 1) {
      --(tm->tm_mon);
      if (tm->tm_mon == -1) {
	tm->tm_mon = 11;
	--(tm->tm_year);
      }

      uint8_t dim = daysInMonth(tm->tm_year+1900, tm->tm_mon+1);
      tm->tm_mday += dim;
      continue;
    }
    break;      
  }

  // Compute day of year
  tm->tm_yday = dayOfYear(tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday) - 1;

  uint8_t yearsSinceEpoch = tm->tm_year + 1900  - RTCX_EPOCH; 
  time_t t = (yearsSinceEpoch * 365 * SECS_PER_DAY) // Whole years, leap days excluded
    + ((yearsSinceEpoch / 4) * SECS_PER_DAY)  // Leap days in whole 4 year period
    // Leap days in partial 4 year period. Count only if in last year
    + ((yearsSinceEpoch % 4) == 3 ? SECS_PER_DAY : 0L) 
    + (tm->tm_yday * SECS_PER_DAY)           // Whole days in current year
    + (tm->tm_hour * 3600L)
    + (tm->tm_min * (uint16_t)60)
    + tm->tm_sec;
  
  // Compute day of week
  uint32_t daysSinceEpoch = (t / SECS_PER_DAY);
  tm->tm_wday = (daysSinceEpoch + 4) % 7; // 1970-01-01 was Thursday (day 4)
  return t;
}
Example #23
0
CString CDateTime::toString(const CString& format) const
{
    if (isNull())
    {
        return CString();
    }

    CString str;
    bool special = false;
    const unsigned int len = format.getSize();

    for (unsigned int i = 0 ; i < len ; ++i)
    {
        if (format[i] == CChar('%'))
        {
            special = true;
        }
        else if (special)
        {
            switch (format[i].toLatin1())
            {
                default:
                    str += format[i];
                    break;

                case 'a':
                    str += (m_hour < 12 ? "am" : "pm");
                    break;

                case 'A':
                    str += (m_hour < 12 ? "AM" : "PM");
                    break;

                case 'd':

                    if (m_day < 10)
                        str += '0';

                    str += CString::fromNumber(m_day);
                    break;

                case 'D':
                    str += shortDayName(dayOfWeek(m_year, m_month, m_day));
                    break;

                case 'F':
                    str += longMonthName(m_month);
                    break;

                case 'g':

                    if (m_hour == 0)
                    {
                        str += "12";
                    }
                    else if (m_hour < 13)
                    {
                        str += CString::fromNumber(m_hour);
                    }
                    else
                    {
                        str += CString::fromNumber(m_hour - 12);
                    }

                    break;

                case 'G':
                    str += CString::fromNumber(m_hour);
                    break;

                case 'h':

                    if (m_hour == 0)
                    {
                        str += "12";
                    }
                    else if (m_hour < 13)
                    {
                        if (m_hour < 10)
                        {
                            str += '0';
                        }

                        str += CString::fromNumber(m_hour);
                    }
                    else
                    {
                        if (m_hour < 22)
                        {
                            str += '0';
                        }

                        str += CString::fromNumber(m_hour - 12);
                    }

                    break;

                case 'H':

                    if (m_hour < 10)
                    {
                        str += '0';
                    }

                    str += CString::fromNumber(m_hour);

                    break;

                case 'i':

                    if (m_minute < 10)
                    {
                        str += '0';
                    }

                    str += CString::fromNumber(m_minute);

                    break;

                case 'j':
                    str += CString::fromNumber(m_day);
                    break;

                case 'l':
                    str += longDayName(dayOfWeek(m_year, m_month, m_day));
                    break;

                case 'L':
                    str += (isLeapYear(m_year) ? '1' : '0');
                    break;

                case 'm':

                    if (m_month < 10)
                    {
                        str += '0';
                    }

                    str += CString::fromNumber(m_month);

                    break;

                case 'M':
                    str += shortMonthName(m_month);
                    break;

                case 'n':
                    str += CString::fromNumber(m_month);
                    break;

                case 'N':
                    str += dayOfWeek(m_year, m_month, m_day);
                    break;

                case 's':

                    if (m_second < 10)
                    {
                        str += '0';
                    }

                    str += CString::fromNumber(m_second);

                    break;

                case 't':
                    str += CString::fromNumber(daysInMonth(m_month, m_year));
                    break;

                case 'U':
                    str += CString::fromNumber(timestamp(m_year, m_month, m_day, m_hour, m_minute, m_second));
                    break;

                case 'W':
                    str += CString::fromNumber(weekOfYear(m_year, m_month, m_day));
                    break;

                case 'y':

                    if (m_year < 0)
                    {
                        str += CString::fromNumber(m_year);
                    }
                    else
                    {
                        unsigned int tmp = m_year % 100;

                        if (tmp < 10)
                        {
                            str += "0";
                        }

                        str += CString::fromNumber(tmp);
                    }

                    break;

                case 'Y':

                    if (m_year < 0)
                    {
                        str += CString::fromNumber(m_year);
                    }
                    else
                    {
                        unsigned int tmp = m_year % 10000;

                        if (tmp < 10)
                            str += "000";
                        if (tmp < 100)
                            str += "00";
                        if (tmp < 1000)
                            str += "000";

                        str += CString::fromNumber(tmp);
                    }

                    break;

                case 'z':
                    str += dayOfYear(m_year, m_month, m_day);
                    break;
            }

            special = false;
        }
        else
        {
            str += format[i];
        }
    }

    return str;
}