Exemplo n.º 1
0
/***********************************************************************
 *
 * FUNCTION:    RepeatChangeRepeatOn
 *
 * DESCRIPTION: This routine is called when one of the weekly "repeat on"
 *              push button is pushed.  This routine checks
 *              if all the buttons has been turned off,  if so the day
 *              of the week of the appointment's start date is turn on.
 *
 * PARAMETERS:  event - pointer to and event
 *
 * RETURNED:    nothing
 *
 ***********************************************************************/
static void RepeatChangeRepeatOn(EventType* event) {
  UInt16 id = 0;
  UInt16 dayOfWeek = 0;
  FormType* frm = FrmGetFormPtr(RepeatForm);
  Boolean on = false;
  UInt16 i = 0;
  const UInt16 idx = FrmGetObjectIndex(frm, RepeatDayOfWeek1PushButton);

  /* Check if any of the buttons are on. */
  for (; i < daysInWeek; i++) {
    if (FrmGetControlValue(frm, idx + i) != 0) {
      on = true;
      break;
    }
  }

  /* If all the buttons are off, turn on the start date's button. */
  if (!on) {
    dayOfWeek = DayOfWeek (d.frm_date.month,
			   d.frm_date.day,
			   d.frm_date.year /*+ firstYear*/); /* frm_date is DateTimeType */
    dayOfWeek = (dayOfWeek - d.repeat_start_of_week + daysInWeek) % daysInWeek;
    
    id = RepeatDayOfWeek1PushButton + dayOfWeek;
    CtlSetValue(GetObjectPointer(frm, id), true);
  }

  /* Update the display of the repeat description. */
  RepeatDrawDescription(frm);
}
void SchedulesTabController::setDstEndDayOfWeekAndMonth(int newWeek, int newDay, int newMonth)
{
  model::RunPeriodControlDaylightSavingTime dst =
    m_model.getUniqueModelObject<model::RunPeriodControlDaylightSavingTime>();

  dst.setEndDate(NthDayOfWeekInMonth(newWeek), DayOfWeek(newDay), MonthOfYear(newMonth));
}
Exemplo n.º 3
0
// Calculate business days forward or back depending on a 5-day week.
// Send a negative bdaysaway to calculate days back.
// http://www.smart.net/~mmontes/ushols.html
//==============================================================================================
Date GetDateFromDateBDays(Date startDate, int bdaysaway, UrpCountry country) {
	Date fromdate = startDate; // Make working colpy
	int dayofweek = DayOfWeek(fromdate);
	if (dayofweek == 6 /* Sat */) fromdate+= 1; // Shift to sunday so week calc works
	int bdaysleftinweek = 5 - DayOfWeek(fromdate); // Calculate days left in week (backwards)
	int weeksinbetween = (bdaysaway - bdaysleftinweek + (bdaysaway > 0? 4 : 0)) / 5; // Substract current week if going forward
	bdaysaway = bdaysaway + (weeksinbetween * 2); // 2 days skipped per week

	// Holiday general calculator:
	// 1 + (Q-1)*7 + (N - DoW(Year,Month,1))%7
	// where N is the day of week, Q is what occurence (th) that we want DoW = Day of week for a date
	// http://www.tondering.dk/main/index.php/calendar-information
	Date edate;
	edate = fromdate + bdaysaway;
	
	if (holidays.GetCount() == 0) {
		LoadHolidays();
	}
	
	
	// If this is a holiday, skip ahead or back a working day (business day)
	if (holidays.At((int)country).Find(edate) != -1) {
		return GetDateFromDateBDays(edate, Sgn(bdaysaway), country);
	} else {
		// If the previous day is sunday and it was a holiday, since we only have official
		// non-working holidays in the database, then we calculate the observed holiday
		// as being Monday.  
		// Federal law (5 U.S.C. 6103) establishes the following public holidays for Federal employees. Please note that most Federal employees work on a Monday through Friday schedule. For these employees, when a holiday falls on a nonworkday -- Saturday or Sunday -- the holiday usually is observed on Monday (if the holiday falls on Sunday) or Friday (if the holiday falls on Saturday).
		// January 1, 2011 (the legal public holiday for New Year’s Day), falls on a Saturday. For most Federal employees, Friday, December 31, 2010, will be treated as a holiday for pay and leave purposes. (See 5 U.S.C. 6103(b).)
		// TODO: Does this work regardless of country?
		Date prevfrom_edate = edate - 1;
		
		if (DayOfWeek(prevfrom_edate) == SUNDAY && holidays.At((int)country).Find(prevfrom_edate) != -1) {
			return GetDateFromDateBDays(edate, Sgn(bdaysaway), country);
		}
		
		// Check if tomorrow is a saturday and a holiday. http://www.opm.gov/Operating_Status_Schedules/fedhol/2011.asp
		Date nextafter_edate = edate + 1;
		if (DayOfWeek(nextafter_edate) == SATURDAY && holidays.At((int)country).Find(nextafter_edate) != -1) {
			return GetDateFromDateBDays(edate, Sgn(bdaysaway), country);
		}

	}
	
	return edate;
}
Exemplo n.º 4
0
static void SaveDate(NumberEntry *dateEditor)
{
	int d = dateEditor->RangeValueAt(0, 2);
	int m = dateEditor->RangeValueAt(3, 2);
	int y = dateEditor->RangeValueAt(6, 4);

	SetRTCYEAR(y);
	SetRTCMON(m);
	SetRTCDAY(d);
	SetRTCDOW(DayOfWeek(y, m, d));
}
Exemplo n.º 5
0
Date GetNextMonday( const Date& d )
{
	Date returnDate;
	returnDate.day = d.day;
	returnDate.month = d.month;
	returnDate.year = d.year;

	if( DayOfWeek( returnDate ) =="Monday" )
		{
			AddDays( returnDate, 7 );
			return returnDate;
		}
	else
		{
			while( DayOfWeek( returnDate ) != "Monday" )
				AddDay( returnDate );
		}

	return returnDate;
}
Exemplo n.º 6
0
/*****************************************************************************
* Function: GadgetDrawWeekdays
*
* Description: Draws the weekdays, extra function since called in
*              GadgetDrawTimeline
*****************************************************************************/
void
GadgetDrawWeekdays(void)
{
  UInt8 i;
  MemHandle mh;
  Char *text;
  RGBColorType color, prevColor;
  DateTimeType now;
  Int16 dow;
  RectangleType bounds, rect;
  UInt16 gadgetIndex;

  // Get info about Gadget
  gadgetIndex = FrmGetObjectIndex(gForm, gGadgetID);
  FrmGetObjectBounds(gForm, gadgetIndex, &bounds);

  // Initialize time constants
  TimSecondsToDateTime(TimGetSeconds(), &now);
  dow = DayOfWeek(now.month, now.day, now.year);
  
  RctSetRectangle(&rect, bounds.topLeft.x+GADGET_BASELEFT+GADGET_LEFT, bounds.topLeft.y,
                         130, FntLineHeight()+2);

  // Erase background
  WinEraseRectangle(&rect, 0);

  for (i=0; i < gGadgetDaysNum; ++i) {
    Int16 leftoff;
    mh = DmGetResource(strRsc, GADGET_STRINGS_WDAYSTART+i);
    text = MemHandleLock(mh);
    leftoff = (gGadgetDaysWidth+2 - FntLineWidth(text, MemPtrSize(text))) / 2;
    if (TNisColored() && (dow == i+1)) {
      color.r = 0xFF;  color.g = 0x00;  color.b = 0x00;
      TNSetTextColorRGB(&color, &prevColor);
    }
    WinDrawChars(text, StrLen(text), bounds.topLeft.x+GADGET_BASELEFT+GADGET_LEFT+i*gGadgetDaysWidth+i+leftoff+2, bounds.topLeft.y);
    if (dow == i+1) {
      if (TNisColored()) {
        TNSetTextColorRGB(&prevColor, NULL);
      } else {
        // Draw some kind of underline to determine current day
        Int16 lineWidth=FntLineWidth(text, StrLen(text));
        WinDrawLine(rect.topLeft.x+i*gGadgetDaysWidth+i+leftoff+1, rect.topLeft.y+FntLineHeight(),
                    rect.topLeft.x+i*gGadgetDaysWidth+i+leftoff+1+lineWidth, rect.topLeft.y+FntLineHeight());
      }
    }
    MemHandleUnlock(mh);
  }
}
Exemplo n.º 7
0
static	SYSTEMTIME	STFtoSYSTEMTIME(const string& stf) {
	SYSTEMTIME	st;
	::ZeroMemory(&st, sizeof(st));

	strvec	vec;
	if ( split(stf, "_", vec)!=8 )
		return	st;
	if ( vec[0]!=STF_HEADER )
		return	st;

	st.wYear = stoi(vec[1]);
	st.wMonth = stoi(vec[2]);
	st.wDay = stoi(vec[3]);
	st.wDayOfWeek = DayOfWeek(st.wYear, st.wMonth, st.wDay);
	st.wHour = stoi(vec[4]);
	st.wMinute = stoi(vec[5]);
	st.wSecond = stoi(vec[6]);
	st.wMilliseconds = 0;
	return	st;
}
Exemplo n.º 8
0
// http://www.codeproject.com/KB/dotnet/HolidayCalculator.aspx
//==============================================================================================
Date GetDateByMonthWeekWeekday(int year, int month, int week, int weekday) {
	Date workDate(year, month, 1); // Calculate first

	while (DayOfWeek(workDate) != weekday) {
		workDate+= 1;
	}
	
	Date result;
	if (week == 1) {
		result = workDate;
	}
	else {
		int addDays = (week * 7) - 7;
		int day = workDate.day + addDays;
		if (day > LastDayOfMonth(workDate).day) {
			day = day - 7;
		}
		result = Date(workDate.year, workDate.month, day);
	}
	
	return result;
}
Exemplo n.º 9
0
std::string
DMYWDate<Cal, WeekType>::ToString( const std::string & format ) const
{
    std::string dateString;
    for ( std::string::const_iterator p = format.begin(); p != format.end(); ++p )
    {
        if ( *p == '%' )
        {
            int width = 0;
            bool zeroFill = false;
            ++p;
            if ( isdigit( *p ) )
            {
                if ( *p == '0' )
                {
                    zeroFill = true;
                    ++p;
                }
                while ( isdigit( *p ) )
                {
                    width = width * 10 + (*p - '0');
                    ++p;
                }
            }
            switch ( *p )
            {
            case 'd':
            case 'D':
            {
                dateString += IntToString( this->m_day, width, 0, zeroFill );
                break;
            }
            case 'm':
            {
                dateString += IntToString( this->m_month, width, 0, zeroFill );
                break;
            }
            case 'M':
            {
                const std::string & monthName
                    = Cal::MonthName( this->m_month, this->m_year );
                if ( monthName.length() == 0 )
                    dateString += IntToString( this->m_month, width, 0,
                                               zeroFill );
                else if ( width == 0 )
                    dateString += monthName;
                else
                    dateString += monthName.substr( 0, width );
                break;
            }
            case 'y':
            case 'Y':
            {
                long y = this->m_year;
                if ( width == 2 )
                    y %= 100;
                else if ( width == 3 )
                    y %= 1000;
                dateString += IntToString( y, width, 0, zeroFill );
                break;
            }
            case 'w':
            {
                dateString += IntToString( DayOfWeek(), width, 0, zeroFill );
                break;
            }
            case 'W':
            {
                const std::string & weekdayName
                    = Week::WeekDayName( DayOfWeek() );
                if ( weekdayName.length() == 0 )
                    dateString += IntToString( DayOfWeek(), width, 0,
                                               zeroFill );
                else if ( width == 0 )
                    dateString += weekdayName;
                else
                    dateString += weekdayName.substr( 0, width );
                break;
            }
            default:
                
                break;
            } //switch
        }
        else
        {
            dateString += *p;
        }
    }
    return dateString;
}
void PrintCalendar ( int cal_yy, int cal_mm )
{
    char      buffer [40];
    struct tm date;
    int       day_of_week;
    int       days_in_month;
    int       days_to_print[42];
    int       i, j, rows;

    if ( LoadDateStruct ( &date, cal_yy, cal_mm, 1 ) == -1 )
    {
        fprintf ( stderr, "Illegal month: %02d-%02d\n",
                    cal_yy, cal_mm );
        return;
    }

    /* get the day of the week for the 1st of month */

    day_of_week = DayOfWeek ( &date );

    /* find out how many days in the month */

    switch ( cal_mm )
    {
        case  1:
        case  3:
        case  5:
        case  7:
        case  8:
        case 10:
        case 12:
            days_in_month = 31;
            break;

        case  4:
        case  6:
        case  9:
        case 11:
            days_in_month = 30;
            break;

        case  2:
            days_in_month = 28;
            if ( IsYearLeap ( cal_yy ) == YES )
                days_in_month += 1;
            break;
    }

    /* load up the days to print */

    for ( i = 0; i < 42; i++ )
        days_to_print[i] = 0;

    for ( i = day_of_week, j = 1; j <= days_in_month; i++, j++ )
        days_to_print[i] = j;

    /* now print the calendar */

    TimeSprintf ( buffer, 40, "    %B %Y", &date );
    printf ( "%s\n", buffer );
    printf ( "  S  M Tu  W Th  F  S\n" );

    for ( rows = 0; rows < 6; rows++ )  /* print up to 6 rows */
    {                                   /* of 7 days.         */
        for ( i = 0; i < 7; i++ )
            if ( days_to_print[(rows * 7) + i] == 0 )
                printf ( "   " );
            else
                printf ( " %2d",
                            days_to_print[(rows * 7) + i] );
        printf ( "\n" );
    }
}
Exemplo n.º 11
0
void __fastcall TMyThread::Execute()
{
		//disable home button
		Form3->homeImageButton5->Enabled=false;
		//yes selected, save information in grid to database

		//create empty strings to add to query once populated from grid
		String headings = "";
		String values = "";
		String update = "";
		String updateHeading = "";

		//get day of week
		int Day = DayOfWeek(Form3->pureDate);
		String DayName;
		switch(Day)
		{
		case 1:
			DayName = L"Sunday";
			break;
		case 2:
			DayName = L"Monday";
			break;
		case 3:
			DayName = L"Tuesday";
			break;
		case 4:
			DayName = L"Wednesday";
			break;
		case 5:
			DayName = L"Thursday";
			break;
		case 6:
			DayName = L"Friday";
			break;
		case 7:
			DayName = L"Saturday";
		}

		//populate date and day of week (probably temporary solution)
		headings += ("Date, Day_Of_Week, ");
		values += ("'" + Form3->dateChosen + "', '" + DayName + "', ");

		//construct headings and values for an update query instead of insert query
		if (Form3->alreadyThere)
		{
			//populate strings only from the grid
			for (int i = 0; i < Form3->displayGrid->RowCount; ++i)
			{
				updateHeading = StringReplace(Form3->displayGrid->Cells[0][i], " ", "_", TReplaceFlags() << rfReplaceAll);

				if (i + 1 == Form3->displayGrid->RowCount)
				{
					update += (updateHeading + " = '" + Form3->displayGrid->Cells[1][i] + "'");
				}
				else
				{
					update += (updateHeading + " = '" + Form3->displayGrid->Cells[1][i] + "', ");
				}
			}
		}
		//check if basic input was used, if so populate headings/values from inputObject
		else if (Form1->getInputLevel() == 0)
		{
			//populate rest of strings from grid
			for (int i = 0; i < Form3->inputObject.size; ++i)
			{
				if (i + 1 == Form3->inputObject.size)
				{
					headings += ("" + Form3->inputObject.valueMap[i][0] + "");
					values += ("'" + Form3->displayGrid->Cells[1][i] + "'");
				}
				else
				{
					headings += ("" + Form3->inputObject.valueMap[i][0] + ", ");
					values += ("'" + Form3->displayGrid->Cells[1][i] + "', ");
				}
			}
		}
		//if inputLevel is not basic, get both headings and values from the grid
		else
		{
			//populate strings only from the grid (might not be "minus 1")
			for (int i = 0; i < Form3->displayGrid->RowCount; ++i)
			{
				if (i + 1 == Form3->displayGrid->RowCount)
				{
					headings += ("" + StringReplace(Form3->displayGrid->Cells[0][i], " ", "_", TReplaceFlags() << rfReplaceAll) + "");
					values += ("'" + Form3->displayGrid->Cells[1][i] + "'");
				}
				else
				{
					headings += ("" + StringReplace(Form3->displayGrid->Cells[0][i], " ", "_", TReplaceFlags() << rfReplaceAll) + ", ");
					values += ("'" + Form3->displayGrid->Cells[1][i] + "', ");
				}
			}
		}

		//run update query if item already in database
		if (Form3->alreadyThere)
		{
			//update the raw_input table
			Form3->SQLQuery2->SQL->Text = "UPDATE baldwins_hotel_data."+Form3->inputTable+" SET "+update+" WHERE "+Form3->inputTable+".Date = '"+Form3->dateChosen+"';";
			Form3->SQLQuery2->ExecSQL();

			//update the read_data table
			Form3->SQLQuery2->SQL->Text = "UPDATE baldwins_hotel_data."+Form3->readTable+" SET "+update+" WHERE "+Form3->readTable+".Date = '"+Form3->dateChosen+"';";
			Form3->SQLQuery2->ExecSQL();
		}
		//if item not there, then run the normal insert query
		else
		{
			//query input_table db and insert new row
			Form3->SQLQuery2->SQL->Text = "INSERT INTO baldwins_hotel_data."+Form3->inputTable+" ("+headings+") VALUES ("+values+");";
			Form3->SQLQuery2->ExecSQL();

			//query read_table db and insert new row
			Form3->SQLQuery2->SQL->Text = "INSERT INTO baldwins_hotel_data."+Form3->readTable+" ("+headings+") VALUES ("+values+");";
			Form3->SQLQuery2->ExecSQL();
		}

		//Calculate and update values for Standard_Hours and Percent_Performance
		//first, query role_table to get all the Role_Name, Bare_Role_Name and Standard_Hours_Reference
		String currentHotelID = Form1->getHotelID();
		vector<calculateInfo> infoVector;
		String roleName = "";
		String roleStandardHoursName = "";
		String bareRoleName = "";
		String standardHoursReference = "";
		int context = 0;
		double actual = 0;
		double labor = 0;
		double roleWages = 0;
		double totalLaborHoursHoursPaid = 0;
		double totalLaborHoursStandardHours = 0;
		double totalLaborHoursPercentPerformance = 0;
		double totalLaborCostHoursPaid = 0;
		double totalLaborCostStandardHours = 0;
		double totalLaborCostPercentPerformance = 0;
		Form3->SQLQuery2->SQL->Text = "SELECT Role_Name, Bare_Role_Name, Standard_Hours_Reference, Role_Wages FROM baldwins_hotel_data.role_table WHERE hotelID = '"+currentHotelID+"';";
		Form3->SQLQuery2->Open();
		Form3->SQLQuery2->First();
		while (!Form3->SQLQuery2->Eof)
		{
			//fill strings
			roleName = Form3->SQLQuery2->Fields->Fields[0]->AsString;
			roleStandardHoursName = StringReplace(roleName, "Hours_Paid", "Standard_Hours", TReplaceFlags() << rfReplaceAll);
			bareRoleName = Form3->SQLQuery2->Fields->Fields[1]->AsString;
			standardHoursReference = Form3->SQLQuery2->Fields->Fields[2]->AsString;
			roleWages = Form3->SQLQuery2->Fields->Fields[3]->AsFloat;

			//get the integer value based on above strings
			Form3->SQLQuery3->SQL->Text = "SELECT "+roleName+", "+standardHoursReference+" FROM baldwins_hotel_data."+Form3->readTable+" WHERE Date = '"+Form3->dateChosen+"';";
			Form3->SQLQuery3->Open();
			Form3->SQLQuery3->First();
			if (!Form3->SQLQuery3->Eof)
			{
				//get values for normal use in this while loop
				actual = Form3->SQLQuery3->Fields->Fields[0]->AsFloat;
				context = Form3->SQLQuery3->Fields->Fields[1]->AsInteger;
			}

			//get the labor value for standard hours
			Form3->SQLQuery3->SQL->Text = "SELECT "+bareRoleName+" FROM baldwins_hotel_data."+Form3->laborTable+" WHERE "+context+" >= Rooms_Occupied_Low AND "+context+" <= Rooms_Occupied_High;";
			Form3->SQLQuery3->Open();
			Form3->SQLQuery3->First();
			if (!Form3->SQLQuery3->Eof)
			{
				labor = Form3->SQLQuery3->Fields->Fields[0]->AsFloat;
			}

			//push_back calculateInfo object
			infoVector.push_back(calculateInfo(roleName, roleStandardHoursName, bareRoleName, standardHoursReference, context, actual, labor));

			//compute values used below this while loop in actual update query
			totalLaborHoursHoursPaid += actual;
			totalLaborHoursStandardHours += labor;
			totalLaborCostHoursPaid = totalLaborCostHoursPaid + (actual * roleWages);
			totalLaborCostStandardHours = totalLaborCostStandardHours + (labor * roleWages);

			//reset strings and doubles to empty for next iteration
			roleName = "";
			roleStandardHoursName = "";
			bareRoleName = "";
			standardHoursReference = "";
			actual = 0;
			context = 0;
			labor = 0;
			roleWages = 0;
			/*totalLaborHoursHoursPaid = 0;
			totalLaborHoursStandardHours = 0;
			totalLaborHoursPercentPerformance = 0;
			totalLaborCostHoursPaid = 0;
			totalLaborCostStandardHours = 0;
			totalLaborCostPercentPerformance = 0;*/

			//move cursor to next item
			Form3->SQLQuery2->Next();
		}

		//run update query that updates standard hours and percent performance
		updateHeading = "";
		String updateHeading2 = "";
		update = "";
		labor = 0;
		double percent = 0;
		for (int i = 0; i < infoVector.size(); ++i)
		{
			updateHeading = infoVector[i].roleStandardHours;
			updateHeading2 = StringReplace(updateHeading, "Standard_Hours", "Percent_Performance", TReplaceFlags() << rfReplaceAll);
			labor = infoVector[i].laborValue;
			percent = infoVector[i].percentPerformance;

			/*if (i + 1 == infoVector.size())
			{
				update += (updateHeading + " = '" + labor + "', " + updateHeading2 + " = '" + percent + "'");
			}*/
			//else
			//{
				update += (updateHeading + " = '" + labor + "', " + updateHeading2 + " = '" + percent + "', ");
			//}
		}

		//calculate/store overtime, total_labor_hours, total_labor_cost in read_data
		double overtimeHoursPaid = 0;
		double overtimeStandardHours = 0;
		double overtimePercentPerformance = 0;
		Form3->SQLQuery3->SQL->Text = "SELECT Overtime_Hours_Paid FROM baldwins_hotel_data."+Form3->inputTable+" WHERE "+Form3->inputTable+".Date = '"+Form3->dateChosen+"';";
		Form3->SQLQuery3->Open();
		Form3->SQLQuery3->First();
		if (!Form3->SQLQuery3->Eof)
			overtimeHoursPaid = Form3->SQLQuery3->Fields->Fields[0]->AsFloat;
		overtimeStandardHours = Form3->overtimePerHour * overtimeHoursPaid;
		overtimePercentPerformance = overtimeStandardHours / 3;
		if (totalLaborHoursHoursPaid != 0)
			totalLaborHoursPercentPerformance = totalLaborHoursStandardHours / totalLaborHoursHoursPaid;
		else
			totalLaborHoursPercentPerformance = 0;
		if (totalLaborCostHoursPaid != 0)
			totalLaborCostPercentPerformance = totalLaborCostStandardHours / totalLaborCostHoursPaid;
		else
			totalLaborCostPercentPerformance = 0;
		totalLaborCostHoursPaid += overtimePercentPerformance;
		String spaceTaker = "";
		update += (spaceTaker + "Overtime_Hours_Paid = '" + overtimeHoursPaid + "', " + "Overtime_Standard_Hours = '" + overtimeStandardHours + "', " + "Overtime_Percent_Performance = '" + overtimePercentPerformance + "', ");
		update += (spaceTaker + "Total_Labor_Hours_Hours_Paid = '" + totalLaborHoursHoursPaid + "', " + "Total_Labor_Hours_Standard_Hours = '" + totalLaborHoursStandardHours + "', " + "Total_Labor_Hours_Percent_Performance = '" + totalLaborHoursPercentPerformance + "', ");
		update += (spaceTaker + "Total_Labor_Cost_Hours_Paid = '" + totalLaborCostHoursPaid + "', " + "Total_Labor_Cost_Standard_Hours = '" + totalLaborCostStandardHours + "', " + "Total_Labor_Cost_Percent_Performance = '" + totalLaborCostPercentPerformance + "'");
		Form3->SQLQuery2->SQL->Text = "UPDATE baldwins_hotel_data."+Form3->readTable+" SET "+update+" WHERE "+Form3->readTable+".Date = '"+Form3->dateChosen+"';";
		Form3->SQLQuery2->ExecSQL();
	}
Exemplo n.º 12
0
/***********************************************************************
 *
 * FUNCTION:    ApptRepeatsOnDate
 *
 * DESCRIPTION: This routine returns true if a repeating appointment
 *              occurrs on the specified date.
 *
 * PARAMETERS:  apptRec - a pointer to an appointment record
 *              date    - date to check              
 *
 * RETURNED:    true if the appointment occurs on the date specified
 *
 * REVISION HISTORY:
 *			Name	Date		Description
 *			----	----		-----------
 *			art	6/14/95		Initial Revision
 *
 ***********************************************************************/
Boolean ApptRepeatsOnDate (ApptDBRecordPtr apptRec, DateType date)
{
	Int16  i;
	UInt16 freq;
	UInt16 weeksDiff;
	UInt16 dayInMonth;
	UInt16 dayOfWeek;
	UInt16 dayOfMonth;
	UInt16 firstDayOfWeek;
	long dateInDays;
	long startInDays;
	Boolean onDate = false;
	DatePtr exceptions;
	DateType startDate;

	// Is the date passed before the start date of the appointment?
	if (DateCompare (date, apptRec->when->date) < 0)
		return (false);

	// Is the date passed after the end date of the appointment?
	if (DateCompare (date, apptRec->repeat->repeatEndDate) > 0)
		return (false);
	

	// Get the frequency of occurrecne
    //    (ex: every 2nd day, every 3rd month, etc.).  
	freq = apptRec->repeat->repeatFrequency;
	
	// Get the date of the first occurrecne of the appointment.
	startDate = apptRec->when->date;

	switch (apptRec->repeat->repeatType)
    {
		// Daily repeating appointment.
    case repeatDaily:
        dateInDays = DateToDays (date);
        startInDays = DateToDays (startDate);
        onDate = ((dateInDays - startInDays) % freq) == 0;
        break;
			

		// Weekly repeating appointment (ex: every Monday and Friday). 
		// Yes, weekly repeating appointment can occur more then once a
		// week.
    case repeatWeekly:
        // Are we on a day of the week that the appointment repeats on.
        dayOfWeek = DayOfWeek (date.month, date.day, date.year+firstYear);
        onDate = ((1 << dayOfWeek) & apptRec->repeat->repeatOn);
        if (! onDate) break;

        // Are we in a week in which the appointment occurrs, if not 
        // move to that start of the next week in which the appointment
        // does occur.
        dateInDays = DateToDays (date);
        startInDays = DateToDays (startDate);

        firstDayOfWeek = (DayOfWeek (1, 1, firstYear) - 
                          apptRec->repeat->repeatStartOfWeek + daysInWeek) % daysInWeek;

        weeksDiff = (((dateInDays + firstDayOfWeek) / daysInWeek) - 
                     ((startInDays + firstDayOfWeek) / daysInWeek)) %freq;
        onDate = (weeksDiff == 0);
        break;


//			// Compute the first occurrence of the appointment that occurs
//			// on the same day of the week as the date passed.
//			startDayOfWeek = DayOfWeek (startDate.month, startDate.day, 
//				startDate.year+firstYear);
//			startInDays = DateToDays (startDate);
//			if (startDayOfWeek < dayOfWeek)
//				startInDays += dayOfWeek - startDayOfWeek;
//			else if (startDayOfWeek > dayOfWeek)
//				startInDays += dayOfWeek+ (daysInWeek *freq) - startDayOfWeek;
//			
//			// Are we in a week in which the appointment repeats.
//			dateInDays = DateToDays (date);
//			onDate = (((dateInDays - startInDays) / daysInWeek) % freq) == 0;
//			break;


		// Monthly-by-day repeating appointment (ex: the 3rd Friday of every
		// month).
    case repeatMonthlyByDay:
        // Are we in a month in which the appointment repeats.
        onDate = ((((date.year - startDate.year) * monthsInYear) + 
                   (date.month - startDate.month)) % freq) == 0;
        if (! onDate) break;

        // Do the days of the month match (ex: 3rd Friday)
        dayOfMonth = DayOfMonth (date.month, date.day, date.year+firstYear);
        onDate = (dayOfMonth == apptRec->repeat->repeatOn);
        if (onDate) break;
			
        // If the appointment repeats on one of the last days of the month,
        // check if the date passed is also one of the last days of the 
        // month.  By last days of the month we mean: last sunday, 
        // last monday, etc.
        if ((apptRec->repeat->repeatOn >= domLastSun) &&
            (dayOfMonth >= dom4thSun))
        {
            dayOfWeek = DayOfWeek (date.month, date.day, date.year+firstYear);
            dayInMonth = DaysInMonth (date.month, date.year+firstYear);
            onDate = (((date.day + daysInWeek) > dayInMonth) &&
                      (dayOfWeek == (apptRec->repeat->repeatOn % daysInWeek)));
        }
        break;						


		// Monthly-by-date repeating appointment (ex: the 15th of every
		// month).
    case repeatMonthlyByDate:
        // Are we in a month in which the appointment repeats.
        onDate = ((((date.year - startDate.year) * monthsInYear) + 
                   (date.month - startDate.month)) % freq) == 0;
        if (! onDate) break;
			
        // Are we on the same day of the month as the start date.
        onDate = (date.day == startDate.day);
        if (onDate) break;

        // If the staring day of the appointment is greater then the 
        // number of day in the month passed, and the day passed is the 
        // last day of the month, then the appointment repeats on the day.
        dayInMonth = DaysInMonth (date.month, date.year+firstYear);
        onDate = ((startDate.day > dayInMonth) && (date.day == dayInMonth));
        break;


		// Yearly repeating appointment.
    case repeatYearly:
        // Are we in a year in which the appointment repeats.
        onDate = ((date.year - startDate.year) % freq) == 0;
        if (! onDate) break;
			
        // Are we on the month and day that the appointment repeats.
        onDate = (date.month == startDate.month) &&
            (date.day == startDate.day);
        if (onDate) break;
			
        // Specal leap day processing.
        if ( (startDate.month == february) && 
             (startDate.day == 29) &&
             (date.month == february) && 
             (date.day == DaysInMonth (date.month, date.year+firstYear)))
        {
            onDate = true;
        }				      
        break;
    default:
        break;
    }

	// Check for an exception.
	if ((onDate) && (apptRec->exceptions))
    {
		exceptions = &apptRec->exceptions->exception;
		for (i = 0; i < apptRec->exceptions->numExceptions; i++)
        {
			if (DateCompare (date, exceptions[i]) == 0)
            {
				onDate = false;
				break;
            }
        }
    }

	return (onDate);
}
Exemplo n.º 13
0
CString CTimeDate::Format (const CString &sFormat) const

//	Format
//
//	Formats a timedate
//
//    %a    abbreviated weekday name (Sun)
//    %A    full weekday name (Sunday)
//    %b    abbreviated month name (Dec)
//    %B    full month name (December)
//    %c    date and time (Dec  2 06:55:15 1979)
//    %d    day of the month (02)
//    %H    hour of the 24-hour day (06)
//    %I    hour of the 12-hour day (06)
//    %j    day of the year, from 001 (335)
//    %m    month of the year, from 01 (12)
//    %M    minutes after the hour (55)
//    %p    AM/PM indicator (AM)
//    %S    seconds after the minute (15)
//    %U    Sunday week of the year, from 00 (48)
//    %w    day of the week, from 0 for Sunday (6)
//    %W    Monday week of the year, from 00 (47)
//    %x    date (Dec  2 1979)
//    %X    time (06:55:15)
//    %y    year of the century, from 00 (79)
//    %Y    year (1979)
//    %Z    time zone name, if any (EST)
//    %%    percent character %

	{
	//	Internet format:
	//
	//	Sun, 06 Nov 1994 08:49:37 GMT

	if (strEquals(sFormat, FORMAT_INTERNET))
		{
		return strPatternSubst(CONSTLIT("%s, %02d %s %d %02d:%02d:%02d GMT"),
				CString(g_szDayNameShort[DayOfWeek()], 3, true),
				m_Time.wDay,
				CString(g_szMonthNameShort[m_Time.wMonth], 3, true),
				m_Time.wYear,
				m_Time.wHour,
				m_Time.wMinute,
				m_Time.wSecond);
		}

	//	Otherwise we expect various fields

	else
		{
		CMemoryWriteStream Stream(0);
		if (Stream.Create() != NOERROR)
			return NULL_STR;

		char *pPos = sFormat.GetASCIIZPointer();
		while (*pPos != '\0')
			{
			if (*pPos == '%')
				{
				pPos++;

				int iLeadingZeros;
				if (*pPos == '0')
					{
					pPos++;

					if (*pPos >= '1' && *pPos <= '9')
						{
						iLeadingZeros = (*pPos) - '0';
						pPos++;
						}
					else
						iLeadingZeros = 2;
					}
				else
					iLeadingZeros = 0;
			
				switch (*pPos)
					{
					case '\0':
						break;

					case 'B':
						Stream.Write(g_szMonthName[m_Time.wMonth], (int)::strlen(g_szMonthName[m_Time.wMonth]));
						pPos++;
						break;

					case 'd':
						WriteNumber(Stream, m_Time.wDay, iLeadingZeros);
						pPos++;
						break;

					case 'I':
						if ((m_Time.wHour % 12) == 0)
							WriteNumber(Stream, 12, iLeadingZeros);
						else
							WriteNumber(Stream, m_Time.wHour % 12, iLeadingZeros);
						pPos++;
						break;

					case 'M':
						WriteNumber(Stream, m_Time.wMinute, 2);
						pPos++;
						break;

					case 'p':
						if (m_Time.wHour < 12)
							Stream.Write("AM", 2);
						else
							Stream.Write("PM", 2);
						pPos++;
						break;

					case 'S':
						WriteNumber(Stream, m_Time.wSecond, 2);
						pPos++;
						break;

					case 'Y':
						WriteNumber(Stream, m_Time.wYear, 0);
						pPos++;
						break;

					default:
						{
						Stream.Write(pPos, 1);
						pPos++;
						}
					}
				}
			else
				{
				Stream.Write(pPos, 1);
				pPos++;
				}
			}

		return CString(Stream.GetPointer(), Stream.GetLength());
		}
	}
Exemplo n.º 14
0
void PrivDrawCell(void* table, Int16 row, Int16 column, RectanglePtr bounds)
{
	char string[50];
	FontID font = stdFont;

	if (g_CurrentRow != row) {
		if (g_CurrentMemHandle) {
			MemHandleUnlock(g_CurrentMemHandle);
			g_CurrentMemHandle = NULL;
		}
	}
	if (g_CurrentMemHandle == NULL) {
		Err err = GetSMSRecord(g_SmsDb, g_SelectedCategory, row + g_CurrentPage * TABLE_PAGE_SIZE, 
			g_CurrentRecord, g_CurrentMemHandle, true);
		if (err) return;
		g_CurrentRow = row;
	}
		
	switch(column) {
		case 0:
			StrCopy(string, "");
			if (g_SelectedCategory == CAT_INBOX) {
				if (IsRecordRead(&g_CurrentRecord)) {
					StrCopy(string, "");
				} else {
					font = symbolFont;
					StrCopy(string, "\020");
				}
			} else if (g_SelectedCategory == CAT_SENT) {
				if (IsRecordRequestReport(&g_CurrentRecord)) {
					font = symbolFont;
					if (IsRecordDelivered(&g_CurrentRecord)) {
						StrCopy(string, "\026");
					} else {
						StrCopy(string, "\024");
					}
				}
			}
			break;
		case 1:
			StrNCopy(string, g_CurrentRecord.personName, 48);
			if (StrLen(string) == 0) {
				StrNCopy(string, g_CurrentRecord.phoneNumber, 48);
			}
			break;
		case 2:
			StrNCopy(string, g_CurrentRecord.content, 48);
			break;
		case 3:
			{
				DateTimeType smsDatetime;
				TimSecondsToDateTime(g_CurrentRecord.time, &smsDatetime);

				UInt32 nowSeconds = TimGetSeconds();
				DateTimeType nowDatetime;
				TimSecondsToDateTime(nowSeconds, &nowDatetime);
				
				if ((nowDatetime.year == smsDatetime.year) && 
					(nowDatetime.month == smsDatetime.month) &&
					(nowDatetime.day == smsDatetime.day)) {
					TimeToAscii(smsDatetime.hour, smsDatetime.minute, tfColon24h, string);
				} else {
					StrCopy(string, DayOfWeekInChinese[DayOfWeek(smsDatetime.month, smsDatetime.day, smsDatetime.year)]);
					DateTemplateToAscii(" ^3z-^0z", smsDatetime.month, smsDatetime.day, smsDatetime.year, string + 2, 47);
				}
				MemHandleUnlock(g_CurrentMemHandle);
				g_CurrentMemHandle = NULL;
			}
			break;
		default:
			StrCopy(string, "");
	}

	WinPushDrawState();
	
	RGBColorType foreColor, backColor;

	foreColor.index = 0;
	backColor.index = 0;
	if ((row == g_CurrentSelection) && (column != 0)) {
		foreColor.r = 255;
		foreColor.g = 255;
		foreColor.b = 255;
		
		backColor.r = 10;
		backColor.g = 36;
		backColor.b = 106;
	} else if (row % 2 == 0) {
		backColor.r = 255;
		backColor.g = 255;
		backColor.b = 255;
		
		foreColor.r = 0;
		foreColor.g = 0;
		foreColor.b = 0;
	} else {
		backColor.r = 220;
		backColor.g = 220;
		backColor.b = 220;
		
		foreColor.r = 0;
		foreColor.g = 0;
		foreColor.b = 0;
	}
	WinSetForeColorRGB(&foreColor, NULL);
	WinSetTextColorRGB(&foreColor, NULL);
	WinSetBackColorRGB(&backColor, NULL);
	
	WinSetUnderlineMode(noUnderline);
		
	FntSetFont(font);

	Int16 width = bounds->extent.x - 2;
	Int16 len = StrLen(string);
	Boolean noFit = false;
	FntCharsInWidth(string, &width, &len, &noFit);
	
	UInt16 x = bounds->topLeft.x;
	UInt16 y = bounds->topLeft.y;
	
	bounds->topLeft.x += - 1;
	bounds->topLeft.y += 0;
	bounds->extent.x += 2;
	bounds->extent.y += 0;
	
	WinEraseRectangle(bounds, 0);
	WinDrawGrayLine(
		bounds->topLeft.x + bounds->extent.x - 2, 
		bounds->topLeft.y,
		bounds->topLeft.x + bounds->extent.x - 2, 
		bounds->topLeft.y + bounds->extent.y);// - 2);
		
	WinDrawChars(string, len, x, y);
	
	WinPopDrawState();
}
Exemplo n.º 15
0
Boolean Ln2SlFormHandleEvent(EventPtr e)
{
    Boolean handled = false;
    DateType dt = {0, 0};
    FormPtr frm = FrmGetFormPtr(Ln2SlForm);

    switch (e->eType) {
    case frmOpenEvent:
        if(gbVgaExists)
       		VgaFormModify(frm, vgaFormModify160To240);

        DateSecondsToDate(TimGetSeconds(), &dt);
        DateToAsciiLong(dt.month, dt.day, dt.year + 1904,
					gPrefdfmts, gAppErrStr);
        SetFieldTextFromStr(Ln2SlFormInput, gAppErrStr);

        FrmDrawForm(frm);
        handled = true;
        break;

    case ctlSelectEvent:
        switch(e->data.ctlSelect.controlID) {
        case Ln2SlFormOk:
            FrmReturnToForm(0);

            handled = true;
            break;

        case Ln2SlFormConvert:
        {
            HappyDaysFlag dummy;
            Int16 year, month, day;
            Char* input;
            int ret;
            
            input = FldGetTextPtr(GetObjectPointer(frm, Ln2SlFormInput));

            if ((ret = AnalysisHappyDays(input, &dummy,
                                         &year, &month, &day))) {
                int syear, smonth, sday;
                int leapyes
                    = CtlGetValue(GetObjectPointer(frm, Ln2SlFormInputLeap));

                ret = lunarL2S(lunarRefNum, year, month, day, leapyes, &syear, &smonth, &sday);
                if (ret == errNone) {
                    Char temp[15];
                    SysCopyStringResource(temp, DayOfWeek(smonth, sday, syear) + SunString);

                    DateToAsciiLong(smonth, sday, syear, gPrefdfmts, gAppErrStr);
                    StrNCat(gAppErrStr, " [", AppErrStrLen);
                    StrNCat(gAppErrStr, temp, AppErrStrLen);
                    StrNCat(gAppErrStr, "]", AppErrStrLen);

                    FldDrawField(SetFieldTextFromStr(Ln2SlFormResult, gAppErrStr));
                }
                else DisplayInvalidDateErrorString(Ln2SlFormResult);
            }
            else {
                DisplayInvalidDateErrorString(Ln2SlFormResult);
            }
            
            handled = true;
            break;
        }
        
        default:
            break;
                
        }
        break;

    case menuEvent:
        handled = TextMenuHandleEvent(e->data.menu.itemID, Ln2SlFormInput);
        break;

    default:
        break;
    }

    return handled;
}
Exemplo n.º 16
0
Boolean NextRepeat (ApptDBRecordPtr apptRec, DatePtr dateP) 
{
	Int16  i;
	UInt16 day;
	UInt16 freq;
	UInt16 year;
	UInt16 adjust;
	UInt16 weeksDiff;
	UInt16 monthsDiff;
	UInt16 daysInMonth;
	UInt16 dayOfWeek;
	UInt16 apptWeekDay;
	UInt16 firstDayOfWeek;
	UInt16 daysTilNext;
	UInt16 monthsTilNext;
	UInt32 dateInDays;
	UInt32 startInDays;
	DateType start;
	DateType date;
	DateType next;

	date = *dateP;

	// Is the date passed after the end date of the appointment?
	if (DateCompare (date, apptRec->repeat->repeatEndDate) > 0)
		return (false);
	
	// Is the date passed before the start date of the appointment?
	if (DateCompare (date, apptRec->when->date) < 0)
		date = apptRec->when->date;

	// Get the frequency on occurrecne (ex: every 2nd day, every 3rd month, etc).  
	freq = apptRec->repeat->repeatFrequency;
	
	// Get the date of the first occurrecne of the appointment.
	start = apptRec->when->date;
	

	switch (apptRec->repeat->repeatType)
    {
		// Daily repeating appointment.
    case repeatDaily:
        dateInDays = DateToDays (date);
        startInDays = DateToDays (start);
        daysTilNext = (dateInDays - startInDays + freq - 1) / freq * freq;
        if (startInDays + daysTilNext > (UInt32) maxDays)
            return (false);
        DateDaysToDate (startInDays + daysTilNext, &next);
        break;
			


		// Weekly repeating appointment (ex: every Monday and Friday). 
		// Yes, weekly repeating appointment can occur more then once a
		// week.
    case repeatWeekly:
        dateInDays = DateToDays (date);
        startInDays = DateToDays (start);

        firstDayOfWeek = (DayOfWeek (1, 1, firstYear) - 
                          apptRec->repeat->repeatStartOfWeek + daysInWeek) % daysInWeek;

        dayOfWeek = DayOfWeek (date.month, date.day, date.year+firstYear);
        apptWeekDay = (dayOfWeek - apptRec->repeat->repeatStartOfWeek +
                       daysInWeek) % daysInWeek;

        // Are we in a week in which the appointment occurrs, if not 
        // move to that start of the next week in which the appointment
        // does occur.
        weeksDiff = (((dateInDays + firstDayOfWeek) / daysInWeek) - 
                     ((startInDays + firstDayOfWeek) / daysInWeek)) %freq;
        if (weeksDiff)
        {
            adjust = ((freq - weeksDiff) * daysInWeek)- apptWeekDay;
            apptWeekDay = 0;
            dayOfWeek = (dayOfWeek + adjust) % daysInWeek;
        }
        else
            adjust = 0;
			
        // Find the next day on which the appointment repeats.
        for (i = 0; i < daysInWeek; i++)
        {
            if (apptRec->repeat->repeatOn & (1 << dayOfWeek)) break;
            adjust++;
            if (++dayOfWeek == daysInWeek)
                dayOfWeek = 0;
            if (++apptWeekDay == daysInWeek)
                adjust += (freq - 1) * daysInWeek;
        }

        if (dateInDays + adjust > (UInt32) maxDays)
            return (false);
        DateDaysToDate (dateInDays + adjust, &next);
//			next = date;
//			DateAdjust (&next, adjust);
        break;



		// Monthly-by-day repeating appointment (ex: the 3rd Friday of every
		// month).
    case repeatMonthlyByDay:
        // Compute the number of month until the appointment repeats again.
        monthsTilNext = (date.month - start.month);

        monthsTilNext = ((((date.year - start.year) * monthsInYear) + 
                          (date.month - start.month)) + freq - 1) /
            freq * freq;

        while (true)
        {
            year = start.year + 
                (start.month - 1 + monthsTilNext) / monthsInYear;
            if (year >= numberOfYears)
                return (false);

            next.year = year;
            next.month = (start.month - 1 + monthsTilNext) % monthsInYear + 1;
	
            dayOfWeek = DayOfWeek (next.month, 1, next.year+firstYear);
            if ((apptRec->repeat->repeatOn % daysInWeek) >= dayOfWeek)
                day = apptRec->repeat->repeatOn - dayOfWeek + 1;
            else
                day = apptRec->repeat->repeatOn + daysInWeek - dayOfWeek + 1;
	
            // If repeat-on day is between the last sunday and the last
            // saturday, make sure we're not passed the end of the month.
            if ( (apptRec->repeat->repeatOn >= domLastSun) &&
                 (day > DaysInMonth (next.month, next.year+firstYear)))
            {
                day -= daysInWeek;
            }
            next.day = day;

            // Its posible that "next date" calculated above is 
            // before the date passed.  If so, move forward
            // by the length of the repeat freguency and preform
            // the calculation again.
            if ( DateToInt(date) > DateToInt (next))
                monthsTilNext += freq;
            else
                break;
        }
        break;						



		// Monthly-by-date repeating appointment (ex: the 15th of every
		// month).
    case repeatMonthlyByDate:
        // Compute the number of month until the appointment repeats again.
        monthsDiff = ((date.year - start.year) * monthsInYear) + 
            (date.month - start.month);
        monthsTilNext = (monthsDiff + freq - 1) / freq * freq;

        if ((date.day > start.day) && (!(monthsDiff % freq)))
            monthsTilNext += freq;
				
        year = start.year + 
            (start.month - 1 + monthsTilNext) / monthsInYear;
        if (year >= numberOfYears)
            return (false);

        next.year = year;
        next.month = (start.month - 1 + monthsTilNext) % monthsInYear + 1;
        next.day = start.day;

        // Make sure we're not passed the last day of the month.
        daysInMonth = DaysInMonth (next.month, next.year+firstYear);
        if (next.day > daysInMonth)
            next.day = daysInMonth;
        break;



		// Yearly repeating appointment.
    case repeatYearly:
        next.day = start.day;
        next.month = start.month;

        year = start.year + 
            ((date.year - start.year + freq - 1) / freq * freq);
			
        if ((date.month > start.month) ||
            ((date.month == start.month) && (date.day > start.day)))
            year += freq;

        // Specal leap day processing.
        if ( (next.month == february) && (next.day == 29) &&
             (next.day > DaysInMonth (next.month, year+firstYear)))
        {
            next.day = DaysInMonth (next.month, year+firstYear);
        }				      
        if (year >= numberOfYears)
            return (false);

        next.year = year;	
        break;
    default:
        break;
    }

	// Is the next occurrence after the end date of the appointment?
	if (DateCompare (next, apptRec->repeat->repeatEndDate) > 0)
		return (false);

	ErrFatalDisplayIf ((DateToInt (next) < DateToInt (*dateP)),
                       "Calculation error");

	*dateP = next;
	return (true);
}
Exemplo n.º 17
0
std::string 
BadiDate::ToString( const std::string & format ) const
{
    std::string dateString;
    for ( std::string::const_iterator p = format.begin(); p != format.end(); ++p )
    {
        if ( *p == '%' )
        {
            int width = 0;
            bool zeroFill = false;
            ++p;
            if ( isdigit( *p ) )
            {
                if ( *p == '0' )
                {
                    zeroFill = true;
                    ++p;
                }
                while ( isdigit( *p ) )
                {
                    width = width * 10 + (*p - '0');
                    ++p;
                }
            }
            switch ( *p )
            {
            case 'd':
            {
                dateString += IntToString( m_day, width, 0, zeroFill );
                break;
            }
            case 'D':
            {
                const std::string & dayName
                    = BadiCalendar::DayName( m_day );
                if ( width == 0 )
                    dateString += dayName;
                else
                    dateString += dayName.substr( 0, width );
                break;
            }
            case 'm':
            {
                dateString += IntToString( m_month, width, 0, zeroFill );
                break;
            }
            case 'M':
            {
                const std::string & monthName
                    = BadiCalendar::MonthName( m_month );
                if ( width == 0 )
                    dateString += monthName;
                else
                    dateString += monthName.substr( 0, width );
                break;
            }
            case 'y':
            {
                dateString += IntToString( m_year, width, 0, zeroFill );
                break;
            }
            case 'Y':
            {
                const std::string & yearName
                    = BadiCalendar::YearName( m_year );
                if ( width == 0 )
                    dateString += yearName;
                else
                    dateString += yearName.substr( 0, width );
                break;
            }
            case 'v':
            {
                dateString += IntToString( m_vahid, width, 0, zeroFill );
                break;
            }
            case 'V':
            {
                dateString += OrdinalToString( m_vahid, width );
                break;
            }
            case 'k':
            {
                dateString += IntToString( m_kulliShay, width, 0, zeroFill );
                break;
            }
            case 'K':
            {
                dateString += OrdinalToString( m_kulliShay, width );
                break;
            }
            case 'w':
            {
                dateString += IntToString( DayOfWeek(), width, 0, zeroFill );
                break;
            }
            case 'W':
            {
                const std::string & weekdayName
                    = BahaiWeek::WeekDayName( DayOfWeek() );
                if ( weekdayName.length() == 0 )
                    dateString += IntToString( DayOfWeek(), width, 0,
                                               zeroFill );
                else if ( width == 0 )
                    dateString += weekdayName;
                else
                    dateString += weekdayName.substr( 0, width );
                break;
            }
            default:
                
                break;
            } //switch
        }
        else
        {
            dateString += *p;
        }
    }
    return dateString;
}
Exemplo n.º 18
0
/***********************************************************************
 *
 * FUNCTION:    NextRepeat
 *
 * DESCRIPTION: This routine computes the date of the next
 *              occurrence of a repeating appointment.
 *
 * PARAMETERS:  rec     - a pointer to a DiddleBug record
 *              date    - passed:   date to start from
 *                        returned: date of next occurrence
 *
 * RETURNED:    true if the appointment occurs again
 *
 ***********************************************************************/
Boolean NextRepeat(DiddleBugRecordType* rec, DateTimeType* dateP) {

  /*
  ** Get the frequency on occurrence
  **(ex: every 2nd day, every 3rd month, etc).
  */ 
  const UInt16 freq = rec->repeatInfo.repeatFrequency;
  
  Int16  i = 0;
  UInt16 day;
  UInt16 year;
  UInt16 adjust;
  UInt16 weeksDiff;
  UInt16 monthsDiff;
  UInt16 daysInMonth;
  UInt16 dayOfWeek;
  UInt16 apptWeekDay;
  UInt16 firstDayOfWeek;
  UInt16 daysTilNext;
  UInt16 monthsTilNext;
  UInt32 dateInDays;
  UInt32 startInDays;
  DateType start, date, when, next;
  DateTimeType nextReal;
  UInt32 startSecs, nextSecs;

  DateSecondsToDate(TimDateTimeToSeconds(dateP), &date);
  TimSecondsToDateTime(rec->alarmSecs, &nextReal);
  nextReal.year = dateP->year;
  nextReal.month = dateP->month;
  nextReal.day = dateP->day;
  nextReal.weekDay = dateP->weekDay;

  /* Calculate alarm date */
  DateSecondsToDate(rec->alarmSecs, &when);

  /* Is the date passed after the end date of the appointment? */
  if (DateCompare(date, rec->repeatInfo.repeatEndDate) > 0)
    return false;

  /* Is the date passed before the start date of the appointment? */
  if (DateCompare(date, when) < 0)
    date = when;
  
  /* Get the date of the first occurrecne of the appointment. */
  start = when;

  switch (rec->repeatInfo.repeatType) {
    /* Hourly repeating appointment */
  case repeatHourly:
    startSecs = TimDateTimeToSeconds(dateP);
    nextSecs = rec->alarmSecs;
    while (nextSecs < startSecs)
      nextSecs += freq * hoursInSeconds;
    
    TimSecondsToDateTime(nextSecs, &nextReal);
    DateSecondsToDate(nextSecs, &next);
    break;

    /* Daily repeating appointment. */
  case repeatDaily:
    dateInDays = DateToDays(date);
    startInDays = DateToDays(start);
    daysTilNext = (dateInDays - startInDays + freq - 1) / freq * freq;
    if (startInDays + daysTilNext > (UInt32) maxDays)
      return false;
    DateDaysToDate (startInDays + daysTilNext, &next);
    break;
    
    /*
    ** Weekly repeating appointment (ex: every Monday and Friday).
    ** Yes, weekly repeating appointment can occur more then once a
    ** week.
    */
  case repeatWeekly:
    dateInDays = DateToDays(date);
    startInDays = DateToDays(start);
    
    firstDayOfWeek = (DayOfWeek (1, 1, firstYear) -
		      rec->repeatInfo.repeatStartOfWeek + daysInWeek) % daysInWeek;

    dayOfWeek = DayOfWeek(date.month, date.day, date.year+firstYear);
    apptWeekDay = (dayOfWeek - rec->repeatInfo.repeatStartOfWeek +
		   daysInWeek) % daysInWeek;

    /*
    ** Are we in a week in which the appointment occurrs, if not
    ** move to that start of the next week in which the appointment
    ** does occur.
    */
    weeksDiff = (((dateInDays + firstDayOfWeek) / daysInWeek) -
		 ((startInDays + firstDayOfWeek) / daysInWeek)) % freq;
    if (weeksDiff) {
      adjust = ((freq - weeksDiff) * daysInWeek) - apptWeekDay;
      apptWeekDay = 0;
      dayOfWeek = (dayOfWeek + adjust) % daysInWeek;
    } else {
      adjust = 0;
    }

    /* Find the next day on which the appointment repeats. */
    for (; i < daysInWeek; i++) {
      if (rec->repeatInfo.repeatOn & (1 << dayOfWeek))
	break;
      
      adjust++;
      
      if (++dayOfWeek == daysInWeek)
	dayOfWeek = 0;

      if (++apptWeekDay == daysInWeek)
	adjust += (freq - 1) * daysInWeek;
    }

    if (dateInDays + adjust > (UInt32) maxDays)
      return false;
    
    DateDaysToDate (dateInDays + adjust, &next);
    break;

    /*
    ** Monthly-by-day repeating appointment
    ** (ex: the 3rd Friday of every month).
    */
  case repeatMonthlyByDay:
    /* Compute the number of month until the appointment repeats again. */
    monthsTilNext = ((((date.year - start.year) * monthsInYear) +
		      (date.month - start.month)) + freq - 1) / freq * freq;

    while (true) {
      year = start.year + (start.month - 1 + monthsTilNext) / monthsInYear;
      if (year >= numberOfYears)
	return false;
      
      next.year = year;
      next.month = (start.month - 1 + monthsTilNext) % monthsInYear + 1;
      
      dayOfWeek = DayOfWeek (next.month, 1, next.year+firstYear);
      if ((rec->repeatInfo.repeatOn % daysInWeek) >= dayOfWeek)
	day = rec->repeatInfo.repeatOn - dayOfWeek + 1;
      else
	day = rec->repeatInfo.repeatOn + daysInWeek - dayOfWeek + 1;
      
      /*
      ** If repeat-on day is between the last sunday and the last
      ** saturday, make sure we're not passed the end of the month.
      */
      if ( (rec->repeatInfo.repeatOn >= domLastSun) &&
	   (day > DaysInMonth (next.month, next.year+firstYear))) {
	day -= daysInWeek;
      }
      next.day = day;

      /*
      ** Its posible that "next date" calculated above is
      ** before the date passed.  If so, move forward
      ** by the length of the repeat freguency and preform
      ** the calculation again.
      */
      if (DateToInt(date) > DateToInt(next))
	monthsTilNext += freq;
      else
	break;
    }
    break;

    /*
    ** Monthly-by-date repeating appointment
    ** (ex: the 15th of every month).
    */
  case repeatMonthlyByDate:
    /* Compute the number of month until the appointment repeats again. */
    monthsDiff = (date.year - start.year) * monthsInYear + date.month - start.month;
    monthsTilNext = (monthsDiff + freq - 1) / freq * freq;

    if (date.day > start.day && !(monthsDiff % freq))
      monthsTilNext += freq;

    year = start.year +	(start.month - 1 + monthsTilNext) / monthsInYear;
    if (year >= numberOfYears)
      return false;

    next.year = year;
    next.month = (start.month - 1 + monthsTilNext) % monthsInYear + 1;
    next.day = start.day;

    /* Make sure we're not passed the last day of the month. */
    daysInMonth = DaysInMonth(next.month, next.year+firstYear);
    if (next.day > daysInMonth)
      next.day = daysInMonth;
    break;

    /* Yearly repeating appointment. */
  case repeatYearly:
    next.day = start.day;
    next.month = start.month;
    
    year = start.year + ((date.year - start.year + freq - 1) / freq * freq);

    if (date.month > start.month || 
	(date.month == start.month && date.day > start.day))
      year += freq;

    /* Specal leap day processing. */
    if (next.month == february && next.day == 29 &&
	next.day > DaysInMonth(next.month, year+firstYear)) {
      next.day = DaysInMonth (next.month, year+firstYear);
    }
    if (year >= numberOfYears)
      return false;
    
    next.year = year;
    break;

  default:
    /* ignore */
  }

  /* Is the next occurrence after the end date of the appointment? */
  if (DateCompare(next, rec->repeatInfo.repeatEndDate) > 0)
    return false;

  dateP->day = next.day;
  dateP->month = next.month;
  dateP->year = next.year + firstYear;
  dateP->hour = nextReal.hour;
  dateP->minute = nextReal.minute;
  dateP->second = nextReal.second;

  return true;
}
Exemplo n.º 19
0
/***********************************************************************
 *
 * FUNCTION:    RepeatDrawDescription
 *
 * DESCRIPTION: This routine draws the text description of the current
 *              repeat type and frequency.
 *
 *              The description is created from a template string.  The
 *              repeat type and frequency determines which template is
 *              used.  The template may contain one or more of the
 *              following token:
 *                   ^d - day name (ex: Monday)
 *							^f - frequency
 *                   ^x - day of the month ordinal number (ex: 1st - 31th)
 *                   ^m - month name (ex: July)
 *                   ^w - week ordinal number (1st, 2nd, 3rd, 4th, or last)
 *
 * PARAMETERS:  frm - pointer to the repeat dialog box
 *
 * RETURNED:    nothing
 *
 ***********************************************************************/
void RepeatDrawDescription(FormType* frm) {
  UInt8 repeatOn;
  UInt16 i;
  UInt16 len;
  UInt16 freq;
  UInt16 dayOfWeek;
  UInt16 templateId = repeatNoneString;
  UInt16 repeatOnCount = 0;
  Char* descP = NULL;
  Char* resP = NULL;
  Char* saveResP = NULL;
  MemHandle descH = NULL;
  MemHandle resH = NULL;
  RepeatInfoType repeat;
  FieldType* fld = GetObjectPointer(frm, RepeatDescField);

  FldEraseField (fld);

  /* Get the current setting of the repeat ui gadgets. */
  RepeatGetUIValues(frm, &repeat);
  
  /*
  ** Determine which template string to use.  The template string is
  ** used to format the description string. Note that we could add
  ** a soft constant which tells us whether we need to use different
  ** strings for freq == 1 case (depends on language), thus saving space.
  */
  freq = repeat.repeatFrequency;
  switch (repeat.repeatType) {
  case repeatNone:
    templateId = repeatNoneString;
    break;
    
  case repeatHourly:
    if (freq == 1)
      /* "Every hour" */
      templateId = everyHourRepeatString;
    else
      /* "Every [other | 2nd | 3rd...] hour" */
      templateId = hourlyRepeatString;
    break;
    
  case repeatDaily:
    if (freq == 1)
      /* "Every day" */
      templateId = everyDayRepeatString;
    else
      /* "Every [other | 2nd | 3rd...] day" */
      templateId = dailyRepeatString;
    break;
    
  case repeatWeekly:
    if (freq == 1)
      /* "Every week on [days of week]" */
      templateId = everyWeekRepeat1DayString;
    else
      templateId = weeklyRepeat1DayString;
    
    /*
    ** Generate offset to appropriate string id,
    ** based on # of days that we need to append.
    */
    for (i = 0; i < daysInWeek; i++) {
      if (repeat.repeatOn & (1 << i) ) 
	repeatOnCount++;
    }
    templateId += repeatOnCount - 1;
    break;

  case repeatMonthlyByDate:
    if (freq == 1)
      /* "The ^w ^d of every month" */
      templateId = everyMonthByDateRepeatString;
    else
      templateId = monthlyByDateRepeatString;
    break;
    
  case repeatMonthlyByDay:
    if (freq == 1)
      templateId = everyMonthByDayRepeatString;
    else
      templateId = monthlyByDayRepeatString;
    break;
    
  case repeatYearly:
    if (freq == 1)
      templateId = everyYearRepeatString;
    else
      templateId = yearlyRepeatString;
    break;
    
  default:
    ErrNonFatalDisplay("Unknown repeat type");
    break;
  }

  /*
  ** Allocate a block to hold the description and copy the template
  ** string into it.
  */
  resH = DmGetResource(strRsc, templateId);
  resP = MemHandleLock(resH);
  descH = MemHandleNew(MemPtrSize(resP));
  ASSERT(descH);
  descP = MemHandleLock(descH);
  StrCopy(descP, resP);
  MemHandleUnlock(resH);
  
  /* Substitute the month name string for the month name token. */
  resH = DmGetResource(strRsc, repeatMonthNamesString);
  resP = MemHandleLock(resH);
  for (i = 1; i < d.frm_date.month; i++)
    resP = StrChr(resP, spaceChr) + 1;
  len = StrChr(resP, spaceChr) - resP;
  descP = SubstituteStr(descP, monthNameToken, resP, len);
  MemHandleUnlock(resH);

  /* Substitute the day name string for the day name token. */
  if ((repeatOnCount == 1) || (repeat.repeatType == repeatMonthlyByDay))
    templateId = repeatFullDOWNamesString;
  else
    templateId = repeatShortDOWNamesString;
  
  resH = DmGetResource(strRsc, templateId);
  resP = MemHandleLock(resH);
  if (repeat.repeatType == repeatWeekly) {
    dayOfWeek = repeat.repeatStartOfWeek;
    repeatOn = repeat.repeatOn;
    saveResP = resP;
    while (StrStr (descP, dayNameToken)) {
      for (i = 0; i < daysInWeek; i++) {
	if (repeatOn & (1 << dayOfWeek)) {
	  repeatOn &= ~(1 << dayOfWeek);
	  break;
	}
	dayOfWeek = (dayOfWeek + 1 + daysInWeek) % daysInWeek;
      }
      resP = saveResP;
      for (i = 0; i < dayOfWeek; i++)
	resP = StrChr(resP, spaceChr) + 1;
      
      len = StrChr(resP, spaceChr) - resP;
      descP = SubstituteStr(descP, dayNameToken, resP, len);
    }
  } else {
    dayOfWeek = DayOfWeek (d.frm_date.month, d.frm_date.day,
			   d.frm_date.year/* + firstYear*/);
    for (i = 0; i < dayOfWeek; i++)
      resP = StrChr(resP, spaceChr) + 1;
    len = StrChr(resP, spaceChr) - resP;
    descP = SubstituteStr(descP, dayNameToken, resP, len);
  }
  MemHandleUnlock (resH);

  /*
  ** Substitute the repeat frequency string for the frequency token. Note that
  ** we do something special for 2nd (other), since the gender of 'other' changes
  ** for some languages, depending on whether the next word is day, month, week,
  ** or year.
  */
  if (freq == 2) {
    Char otherFreqName[16];
    const UInt16 index = repeat.repeatType - repeatNone;
    SysStringByIndex(freqOrdinal2ndStrlID, index, otherFreqName, sizeof(otherFreqName));
    descP = SubstituteStr(descP, frequenceToken, otherFreqName, StrLen(otherFreqName));
  } else {
    resH = DmGetResource(strRsc, freqOrdinalsString);
    resP = MemHandleLock(resH);
    for (i = 1; i < freq; i++)
      resP = StrChr(resP, spaceChr) + 1;
    len = StrChr(resP, spaceChr) - resP;
    descP = SubstituteStr(descP, frequenceToken, resP, len);
    MemHandleUnlock(resH);
  }

  /*
  ** Substitute the repeat week string (1st, 2nd, 3rd, 4th, or last)
  ** for the week ordinal token.
  */
  if (repeat.repeatType == repeatMonthlyByDay) {
    resH = DmGetResource(strRsc, weekOrdinalsString);
    resP = MemHandleLock(resH);
    for (i = 0; i < repeat.repeatOn / daysInWeek; i++)
      resP = StrChr (resP, spaceChr) + 1;
    len = StrChr(resP, spaceChr) - resP;
    descP = SubstituteStr(descP, weekOrdinalToken, resP, len);
    MemHandleUnlock(resH);
  } else {
    /* make sure the week ordinal token really doesn't appear */
    ErrNonFatalDisplayIf(StrStr(descP, weekOrdinalToken) != NULL, "week ordinal not substituted");
  }

  /*
  ** Substitute the repeat date string (1st, 2nd, ..., 31th) for the
  ** day ordinal token.
  */
  resH = DmGetResource(strRsc, dayOrdinalsString);
  resP = MemHandleLock(resH);
  for (i = 1; i < d.frm_date.day; i++)
    resP = StrChr(resP, spaceChr) + 1;
  len = StrChr(resP, spaceChr) - resP;
  descP = SubstituteStr(descP, dayOrdinalToken, resP, len);
  MemHandleUnlock(resH);

  /* Draw the description. */
  MemHandleUnlock(descH);
  FldFreeMemory(fld);
  FldSetTextHandle(fld, descH);
  FldDrawField(fld);
}
Exemplo n.º 20
0
void
MakeMotTitle ( char *title, char *dattim, char *product, char *level,
	       char *vlevel, char *label, char *location )
{
	char	buf[GEMPAKSTRING];
	char	time[20], day[4], imon[3], year[5], slash[2];
	char	*dayw, *month;
	int	len=FILENAMESTRING, iret;
	BooleanType	pdattim = False;

	strcpy ( title, " " );
	bpad ( title, len, &iret );
	strcpy ( title, " " );

/*
 *	Parse the input dattim string formatted as: YYYYMMDD/HHMM????? where
 *	the question marks (?) could represent model forecast time.
 */
	if ( dattim != NULL ) {
/*
 *	Write date/time to title as a dattim string.
 */
	    if ( pdattim ) {
		if ( strcmp ( dattim, "MISSING" ) != 0 )
	    	    strcat ( title, dattim );
	    }
/*
 *	Write date/time to title in components.
 */
	    else if ( strlen (dattim)>10 ) {
	    	sscanf ( dattim, "%4s%2s%2s%1s%s",
	                         year, imon, day, slash, time );
	    	dayw = DayOfWeek ( dattim );
	    	month = MonthOfYear ( str2int(imon) );;

		strcat ( title, dayw );
		strcat ( title, " " );
		strcat ( title, month );
		strcat ( title, " " );
		strcat ( title, day );
		strcat ( title, " " );
		strcat ( title, year );
		strcat ( title, " " );
		strcat ( title, time );

		Free ( dayw );
		Free ( month );
	    }
/*
 *	Date time is missing so don't write it to the title.
 */
	    else if ( strcmp ( dattim, "MISSING" ) == 0 )
		(void) 0;

/*
 *	Error check.
 */
	    else
	    	printf ("MakeMotTitle - input time is invalid\n");
	}

/*
 *	Write product ( or model ) to title.
 */
	if ( product != NULL ) {
	    strcat ( title, " " );
	    strcat ( title, product );
	}

/*
 *	Special case for level = 0, vcord = none
 */
	if ( level && vlevel &&
	     strncmp (level, "0", 1 ) == 0 &&
	   ( strncmp (vlevel, "NONE", 4 ) == 0 || strncmp (vlevel, "none", 4 ) == 0 )) {
	     strcat ( title, " (SFC)" );
	}
	else {
/*
 *	    Write vertical level to title.
 */
	    if ( level != NULL ) {
		strcat ( title, " (" );
		strcat ( title, level );
	    }

/*
 *	    Write vertical coordinate units to title.
 */
	    if ( vlevel != NULL ) {
		if ( level == NULL )
		    strcat ( title, " (" );
		else
		    strcat ( title, " " );
		strcat ( title, vlevel );
		strcat ( title, ")" );
	    }
	    else
		if ( level != NULL ) strcat ( title, ")" );
	}

/*
 *	Write label ( or model field ) to title.
 */
	if ( label != NULL ) {
	    strcat ( title, " " );
	    strcat ( title, label );
	}

/*
 *	Write station location to title.
 */
	if ( location != NULL ) {
	    sprintf ( buf, "%s%s%s", " (", location, ")" );
	    strcat ( title, buf );
	}
}
int main ( int argc, char *argv[] )
{
    FILE *infile;

    char *p, str[40], str2[40];
    int  action, i;
    long day_num;

    time_t timer;
    struct tm *tms,
              *tms2;

    struct tm tm1, tm2;

    tms = &tm1;
    tms2= &tm2;

    if ( argc < 2 )     /* if no args, just print the date */
    {
        timer = time ( NULL );
        tms   = localtime ( &timer );

        TimeSprintf ( str, 40,
                "%m-%d-%Y at %H:%M:%S", tms );
        printf ( "Today is %s\n", str );

        return ( EXIT_SUCCESS );
    }

    if ( argc == 3 )
    {
        long start, end, test, count;
        start = atol ( argv[1] );
        end   = atol ( argv[2] );

        if ( start < 1 || ( start + end ) < 1 )
        {
            printf ( "Usage: datelib start-day-num "
                     "how-many-dates\n" );
            return ( 0 );
        }

        count = 0L;
        day_num = start;

        while ( 1 )
        {
            DayNumberToDate ( day_num, tms );
            test = DateToDayNumber ( tms );
            if ( test != day_num )
            {
                count += 1;
                printf ( "%ld is %d-%d-%d but becomes %ld\n",
                            day_num,
                            tms->tm_mon, tms->tm_mday,
                            tms->tm_year,
                            test );
            }

            if ( start < end )
            {
                if ( day_num < end )
                    day_num += 1;
                else
                    break;
            }
            else
            if ( start > end )
            {
                if ( day_num > end )
                    day_num -= 1;
                else
                    break;
            }
        }

        printf ( "\n%01ld error(s) occurred\n", count );

        return ( 0 );
    }

    /* only valid arg is a test script; so read and play it */

    infile =  fopen ( argv[1], "rt" );
    if ( infile == NULL )
    {
        printf ( "Cannot open %s\n", argv[1] );
        return ( EXIT_FAILURE );
    }

    while ( ! feof ( infile ))
    {
        if ( fgets ( str, 40, infile ) == NULL )
            break;

        action = *str;
        p = str + 1;

        switch ( action )
        {
            case ';':   /* comment line */
                        continue;

            case 'a':   /* exercise TimeSprintf() */
            case 'A':
                        i = script_date_to_tms ( p, tms );
                        if ( i < 0 )
                            continue;
                        p++;
                        while ( *p != ' ' && *p != '\n' )
                            p++;
                        i = script_time_to_tms ( p, tms );
                        if ( i < 0 )
                            continue;

                        tms2->tm_year = tms->tm_year - 1900;
                        tms2->tm_mon  = tms->tm_mon;
                        tms2->tm_mday = tms->tm_mday;
                        tms2->tm_hour = tms->tm_hour;
                        tms2->tm_min  = tms->tm_min;
                        tms2->tm_sec  = tms->tm_sec;
                        mktime ( tms2 );

                        printf      ( "Format               TimeSprintf             strftime\n\n" );

                        TimeSprintf ( str,  40, "%a %A", tms );
                        strftime    ( str2, 40, "%a %A", tms2 );
                        printf      ( "%%a %%A      %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%b %B", tms );
                        strftime    ( str2, 40, "%b %B", tms2 );
                        printf      ( "%%b %%B      %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%d", tms );
                        strftime    ( str2, 40, "%d", tms2 );
                        printf      ( "%%d         %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%y %Y", tms );
                        strftime    ( str2, 40, "%y %Y", tms2 );
                        printf      ( "%%y %%Y      %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%H/%I:%M:%S %p", tms );
                        strftime    ( str2, 40, "%H/%I:%M:%S %p", tms2 );
                        printf      ( "%%H/I%%M%%S%%p %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%U %W", tms );
                        strftime    ( str2, 40, "%U %W", tms2 );
                        printf      ( "%%U %%W      %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%j %m %%", tms );
                        strftime    ( str2, 40, "%j %m %%", tms2 );
                        printf      ( "%%j %%m %%    %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%x %X", tms );
                        strftime    ( str2, 40, "%x %X", tms2 );
                        printf      ( "%%X %%x       %20s        %20s\n",
                                         str, str2 );

                        TimeSprintf ( str,  40, "%c %Z", tms );
                        strftime    ( str2, 40, "%c %Z", tms2 );
                        printf      ( "%%c %%Z       %20s        %20s\n",
                                         str, str2 );

                        break;

            case 'f':   /* difference between dates */
            case 'F':
                        i = script_date_to_tms ( p, tms );
                        if ( i < 0 )
                            continue;
                        p++;
                        while ( *p != ' ' && *p != '\n' )
                            p++;
                        i = script_date_to_tms ( p, tms2 );
                        day_num = DateDiff ( tms, tms2 );
                        TimeSprintf ( str, 40, "%m-%d-%Y", tms );
                        printf ( "%s is %ld days from ",
                                 str, day_num );
                        TimeSprintf ( str, 40, "%m-%d-%Y", tms2);
                        printf ( "%s\n", str );
                        break;

            case 'n':   /* convert day number to date */
            case 'N':
                        while ( *p != '\n' && ! isdigit ( *p ))
                            p++;

                        day_num = atol ( p );
                        DayNumberToDate ( day_num, tms );
                        TimeSprintf ( str, 40, "%m-%d-%Y", tms );
                        printf ( "%ld is %s\n", day_num, str );
                        break;

            case 't':   /* print today's date */
            case 'T':
                        timer = time ( NULL );
                        tms   = localtime ( &timer );

                        TimeSprintf ( str, 40,
                                "%m-%d-%Y at %H:%M:%S", tms );
                        printf ( "Today is %s, ", str );

                        tms->tm_year += 1900;
                        LoadDateStruct ( tms2, 1, 1, 1 );
                        LoadTimeStruct ( tms2, 0, 0, 0 );
                        printf ( "%g secs elapsed in the modern era\n",
                                 TimeDiff ( tms, tms2 ));
                        break;

            case 'u':   /* Sunday/Monday week count */
            case 'U':
                        i = script_date_to_tms ( p, tms );
                        if ( i < 0 )
                            continue;

                        tms2->tm_year = tms->tm_year - 1900;
                        tms2->tm_mon  = tms->tm_mon;
                        tms2->tm_mday = tms->tm_mday;
                        tms2->tm_hour = 9;
                        tms2->tm_min  = 10;
                        tms2->tm_sec  = 11;
                        mktime ( tms2 );

                        printf      ( "Format               TimeSprintf                   strftime\n\n" );

                        TimeSprintf ( str,  40, "%U %W", tms );
                        strftime    ( str2, 40, "%U %W", tms2 );
                        printf      ( "%%U %%W      %20s        %20s\n",
                                         str, str2 );
                        break;

            case 'w':   /* day of week */
            case 'W':
                        i = script_date_to_tms ( p, tms );
                        if ( i < 0 )
                            continue;
                        i = DayOfWeek ( tms );
                        day_num = DateToDayNumber ( tms );
                        printf ( "%d-%d-%d is %s day num: %ld\n",
                                    tms->tm_mon + 1, tms->tm_mday,
                                    tms->tm_year,
                                    Day_name[i], day_num );
                        break;

            default:
                        printf ( "Error: %s\n", str );
                        break;
        }

    }
    return ( EXIT_SUCCESS );
}
void WINAPI MainThread()
{
	while(1)
	{
		// Thread Principal da dll, chamada de 1 em 1 segundo. 
		// Usar para não sobrecarregar a ProcessMinTimer
		// Não cometer a negragem de dar break

		time_t rawnow = time(NULL);
		struct tm *now = localtime(&rawnow);

		if((DayOfWeek() == Terça  || DayOfWeek() == Quinta) && now->tm_hour == 21)
		{
			if(!now->tm_min && !now->tm_sec)
			{
				SendNotice("Entrada na GuildWar liberada, boa sorte !");

				//SendLog("system", "Entrada na GuildWar liberada.");

				for(int i = 0; i < 0xFFFF; i++)
					Guilds[i].WarPoints = 0;
			}

			if(now->tm_min == 30 && !now->tm_sec)
			{
				UINT16 Winner = DefineGuildWinner();

				char szMsg[120];

				if(Winner)
				{
					sprintf(szMsg, "Guild %s foi a vencedora da GuildWar, parabéns!", Guilds[Winner].GuildName);
					
					Guilds[Winner].FAME += 1000;
				}
				else
					sprintf(szMsg, "Não houve vencedores na GuildWar.");

				SendNotice(szMsg);
				//SendLog("system", szMsg);
			}
		}

		DecrementWaterTime();
		LettersTime();

		for(int z = 0; z < 0xFFFF; z++)
		{
			if(Guilds[z].confirmTransfer)
				Guilds[z].confirmTransfer--;
			if(!Guilds[z].confirmTransfer)
			{
				Guilds[z].transfer = false;

				strncpy(Guilds[z].NewLiderName, "", 16);
			}
		}

		if(!now->tm_hour && !now->tm_min && !now->tm_sec)// 0:00:00
		{
			if(DayOfWeek() == Sabado)
			{
				*(INT32*)0x008BF1814 = 1;
				SendNotice("++++ DOUBLE EXP ON ++++");
			}
			else if(DayOfWeek() == Segunda)
			{
				*(INT32*)0x008BF1814 = 0;
				SendNotice("++++ DOUBLE EXP OFF ++++");
			}
		}

		if(!now->tm_sec && (now->tm_min == 1 || now->tm_min == 16 || now->tm_min == 31 || now->tm_min == 46))
		{
			for(INT8 i = 0; i < 3; i++)
			{
				Pesa[i].TimeLeft = 840;

				for(INT8 e = 0; e < 3; e++)
				{
					for(INT8 j = 0; j < 13; j++)
					{
						if(Pesa[i].CIDS[e][j] < 0 || Pesa[i].CIDS[e][j] > 750)
							continue;
						else if(Users[Pesa[i].CIDS[e][j]].Status != 22)
							continue;

						SendClientSignalParm(Pesa[i].CIDS[e][j], 0x7530, 0x3A1, Pesa[i].TimeLeft);
					}
				}
			}
		}

		if((now->tm_min == 14 || now->tm_min == 29 || now->tm_min == 44 || now->tm_min == 59) && now->tm_sec == 59)
		{
			ClearArea(1150, 130, 1270, 220); // Pesa A
			ClearArea(1050, 260, 1135, 350); // Pesa M
			ClearArea(1295, 290, 1325, 365); // Pesa N

			for(int i = 0; i < sizeof(QuestList) / sizeof(Quests); i++)
			{
				ClearArea(MaxMinCoordsQuest[i][0], MaxMinCoordsQuest[i][1], MaxMinCoordsQuest[i][2], MaxMinCoordsQuest[i][3]);

				for(int z = 0; z < 40; z++)
					QuestList[i].CidID[z] = 0;
			}

			for(int i = 0; i < sizeof(Pesa) / sizeof(Pesas); i++)
			{
				Pesa[i].Status = false;
				Pesa[i].Groups = 0;
				Pesa[i].NpcsAlive = 0;

				for(int e = 0; e < 13; e++)
				{
					Pesa[i].CIDS[0][e] = 0;
					Pesa[i].CIDS[1][e] = 0;
					Pesa[i].CIDS[2][e] = 0;
				}
			}
		}

		if(!now->tm_sec && !now->tm_min && now->tm_hour == 21 && DayOfWeek() == Domingo)
		{
			INT64 BetValue[4][2];

			for(UINT32 I = 0; I < 0xFFFF; I++)
			{
				// Se não tiver nome, não é uma  guild ativa.
				if(!strcmp(Guilds[I].GuildName, ""))
					continue;

				// Coloca na struct da guerra os valores referentes a guilds apostantes
				for(int e = 0; e < 4; e++)
				{
					if(Guilds[I].BetValue[e] > BetValue[e][0])
					{
						BetValue[e][0] = Guilds[I].BetValue[e];
						War.BetIndex[e][0] = I;
					}
					else if(Guilds[I].BetValue[e] > BetValue[e][1])
					{
						BetValue[e][1] = Guilds[I].BetValue[e];
						War.BetIndex[e][1] = I;
					}

					Guilds[I].BetValue[e] = 0;
				}
			}

		    TeleportWar();
		}
		else if(now->tm_hour == 21 && DayOfWeek() == Domingo && now->tm_min == 3 && !now->tm_sec)
		{
			// Inicio real da pancadaria
			//SendLog("system", "Portões da Guerra abertos.");

			WarGate(1);
		}

		if(now->tm_hour == 21 && DayOfWeek() == Domingo)
		{
			for(int i = 0; i < 4; i++)
			{
				if(!War.Iniciada[i])
					continue;

				int OwnerAlive = GetTeamAlive(i, 0),
					DefyAlive  = GetTeamAlive(i, 1);

				if(!OwnerAlive)// Seta o desafiante como vencedor
					PutAsWinner(i, 1);
				else if(!DefyAlive)// Seta o defensor como vencedor
					PutAsWinner(i, 0);

				if(War.Finalizada[i])
					continue;

				for(int e = 0; e < 2; e++)
				{
					for(int j = 0; j < War.TeamCount[i][e]; j++)
					{
						INT16 cId = 0;

						if(!e)
							cId = War.OwnerTeam[i][j];
						else
							cId = War.DefyTeam[i][j];

						st_Mob *player = GetMobFromIndex(cId);

						if(player->Status.curHP <= 0)
						{
							if(wdBuffer[cId].Ingame.WarRestTime >= 1)
								wdBuffer[cId].Ingame.WarRestTime--;
							else
								wdBuffer[cId].Ingame.cantRessurect = false;
						}

						// Manda o score, não sei se vai funfar...
						NpcsAlive(cId, GetTeamAlive(i, 0), GetTeamAlive(i, 1));
					}
				}
			}
		}

		usersCount = 0;

		for(int i = 0; i < MAX_PLAYER; i++)
		{
			if(Users[i].Status != 22)
				continue;

			usersCount++;

			if(wdBuffer[i].Ingame.ChatGlobal > 0)
				wdBuffer[i].Ingame.ChatGlobal--;
			if(wdBuffer[i].Ingame.hasFailed > 0)
				wdBuffer[i].Ingame.hasFailed--;
			if(wdBuffer[i].Ingame.Grito > 0)
				wdBuffer[i].Ingame.Grito--;
			if(wdBuffer[i].Ingame.RetectItem)
				wdBuffer[i].Ingame.RetectItem--;

			st_Mob *tmpPlayer = GetMobFromIndex(i);

			if(tmpPlayer->Equip[0].EFV2 < HARDCORE && tmpPlayer->Equip[1].Index == 3505 && !wdBuffer[i].Ingame.isAdmin)
			{
				SendBan(Users[i].Username);

				char szNotice[120];

				sprintf(szNotice, "Jogador [%s] banido por uso de item irregular.", tmpPlayer->Name);

				//SendLog("banneds", szNotice);
				//SendNotice(szNotice);

				CloseUser(i);
			}

			for(int i = 0; i < *(DWORD*)(0x004C7BD8); i++) 
				memset((void*)(0x8B9E778), 0, 8);

			VerifyPesa(i);
			VerifyQuests(i);
			//VerifyWarArea(i);
		}

		Server.Seconds++;

		if(Server.Seconds >= 60)
		{
			Server.Seconds -= 60;
			Server.Minuts++;

			if(Server.Minuts >= 60)
			{
				Server.Minuts -= 60;
				Server.Hours++;

				if(Server.Hours >= 24)
				{
					Server.Days++;
					Server.Hours -= 24;
				}
			}
		}

		char szTitle[120];

		if(usersCount)
			sprintf(szTitle, "Secrets of Destiny [%d] Jogadores conectados. [%02d:%02d:%02d:%02d]", usersCount, Server.Days, Server.Hours, Server.Minuts, Server.Seconds);
		else
			sprintf(szTitle, "Secrets of Destiny [%02d:%02d:%02d:%02d]", Server.Days, Server.Hours, Server.Minuts, Server.Seconds);

		SetConsoleTitle(szTitle);

		if(!now->tm_min && !now->tm_sec)
		{
			// Funções executadas todo inicio de hora
			if(!Server.SombraNegra)
			{
				CreateMob("Sombra_Negra", 3819, 2880, "npc");

				Server.SombraNegra = TRUE;

				SendNotice("Sombra Negra acaba de nascer em Karden!");

				//SendLog("system", "Sombra Negra nasceu.");
			}
			else
				SendNotice("Sombra Negra ainda reina em Karden.");
			
			StartThread(PremiumDelivery);
		}

		Sleep(1000);
		// Não colocarei 1000 para termos margem de tempo
		// Para a execução das tarefas desta thread
	}	
}
Exemplo n.º 23
0
/***********************************************************************
 *
 * FUNCTION:    RepeatChangeType
 *
 * DESCRIPTION: This routine changes the ui gadgets in the repeat dialog
 *              such that they match the newly selected repeat type.  The
 *              routine is called when one of the repeat type push buttons
 *              are pushed.
 *
 * PARAMETERS:  event - pointer to and event
 *
 * RETURNED:    nothing
 *
 ***********************************************************************/
static void RepeatChangeType(EventType* event) {
  UInt16 id;
  FormType* frm = FrmGetFormPtr(RepeatForm);
  const RepeatType oldType = d.repeat_event_type;
  RepeatType newType;
  RepeatInfoType repeat;

  /* If the type if monthly default to monthly-by-date. */
  newType = (RepeatType) (event->data.ctlSelect.controlID - RepeatNone);
  if (newType > repeatWeekly) 
    newType++;

  if (oldType == newType)
    return;

  /* Initialize the UI gadgets. */
  if (newType == d.tmp_repeat.repeatType) {
    RepeatSetUIValues(frm, &d.tmp_repeat);

    /*
    ** If reselecting current repeat type, reset d.repeat_end_date global
    ** to current date so if user attemps to "choose" a new day, the
    ** default matches date displayed as opposed to last date picked
    ** last in choose form.
    */
    d.repeat_end_date = d.tmp_repeat.repeatEndDate;
  } else {
    repeat.repeatType = newType;

    /*
    ** When switching to a repeat type different from the current
    ** setting, always start user with default end date and frequency
    ** settings.
    */
    DateToInt(repeat.repeatEndDate) = defaultRepeatEndDate;
    DateToInt(d.repeat_end_date) = defaultRepeatEndDate;
    repeat.repeatFrequency = defaultRepeatFrequency;
    
    repeat.repeatStartOfWeek = PrefGetPreference(prefWeekStartDay);

    if (newType == repeatWeekly) {
      repeat.repeatOn = (1 << DayOfWeek(d.frm_date.month,
					d.frm_date.day,
					d.frm_date.year/*+firstYear*/));
    } else if (newType == repeatMonthlyByDay) {
      repeat.repeatOn = DayOfMonth(d.frm_date.month,
				   d.frm_date.day,
				   d.frm_date.year/* + firstYear*/);
    } else {
      repeat.repeatOn = 0;
    }

    RepeatSetUIValues (frm, &repeat);
  }
  
  /*
  ** Hide the UI gadgets that are unique to the repeat type we are
  ** no longer editing.
  */
  switch (oldType) {
  case repeatNone:
    HideObject(frm, RepeatNoRepeatLabel);
    break;

  case repeatHourly:
    HideObject(frm, RepeatHoursLabel);
    break;

  case repeatDaily:
    HideObject(frm, RepeatDaysLabel);
    break;

  case repeatWeekly:
    HideObject(frm, RepeatWeeksLabel);
    for (id = RepeatRepeatOnLabel; id <= RepeatDayOfWeek7PushButton; id++)
      HideObject (frm, id);
    break;

  case repeatMonthlyByDay:
  case repeatMonthlyByDate:
    HideObject(frm, RepeatMonthsLabel);
    for (id = RepeatByLabel; id <= RepeatByDatePushButton; id++)
      HideObject (frm, id);
    break;

  case repeatYearly:
    HideObject(frm, RepeatYearsLabel);
    break;
  }

  /* Handle switching to or from "no" repeat. */
  if (oldType == repeatNone) {
    ShowObject(frm, RepeatEveryLabel);
    ShowObject(frm, RepeatFrequenceField);
    ShowObject(frm, RepeatEndOnLabel);
    ShowObject(frm, RepeatEndOnTrigger);
  } else if (newType == repeatNone) {
    HideObject(frm, RepeatEveryLabel);
    HideObject(frm, RepeatFrequenceField);
    HideObject(frm, RepeatEndOnLabel);
    HideObject(frm, RepeatEndOnTrigger);
  }

  /* Show the UI object that are appropriate for the new repeat type. */
  switch (newType) {
  case repeatNone:
    ShowObject(frm, RepeatNoRepeatLabel);
    break;

  case repeatHourly:
    ShowObject(frm, RepeatHoursLabel);
    break;

  case repeatDaily:
    ShowObject(frm, RepeatDaysLabel);
    break;

  case repeatWeekly:
    ShowObject(frm, RepeatWeeksLabel);
    ShowObject(frm, RepeatRepeatOnLabel);
    for (id = RepeatRepeatOnLabel; id <= RepeatDayOfWeek7PushButton; id++)
      ShowObject(frm, id);
    break;

  case repeatMonthlyByDay:
  case repeatMonthlyByDate:
    ShowObject(frm, RepeatMonthsLabel);
    ShowObject(frm, RepeatByLabel);
    ShowObject(frm, RepeatByDayPushButton);
    ShowObject(frm, RepeatByDatePushButton);
    break;

  case repeatYearly:
    ShowObject(frm, RepeatYearsLabel);
    break;
  }

  d.repeat_event_type = newType;

  /* Update the display of the repeat descrition. */
  RepeatDrawDescription(frm);
}
/*--------------------------------------------------------------
 * Operates like strftime() except:
 *  a) it returns -1 on error;
 *  b) strftime() expects tm_year to be 2 digits and so always
 *     adds 1900 to the year, while TimeSprintf() believes the
 *     year to be the actual year: 94 is AD 94 and so does not
 *     add 1900.
 *-------------------------------------------------------------*/
int TimeSprintf ( char *string, int max_size,
                  char *format, struct tm *ptm )
{
    char *pf;
    int  i, j;

    int  yy;        /* scratch variable for year */
    int  mon;       /* our internal use of the month is 1-12 */
    char *buffer;   /* where the output string goes */

    mon = ptm->tm_mon + 1;

    buffer = malloc ( 1024 );   /* largest likely output string */
    if ( buffer == NULL )
        return ( -1 );

    i = 0;    /* where we are in the output string */


    for ( pf = format; *pf != '\0' && i < 1024; pf++ )
    {
        if ( *pf != '%' )
            buffer[i++] = *pf;
        else
            switch ( *(++pf) )
            {
                /*--- day of the week: Sunday, Monday...---*/

            case 'a':               /* 3-letter weekday */
                j = DayOfWeek ( ptm );
                strncpy ( buffer + i,
                          Day_name_abbrev[j], 3 );
                i += 3;
                break;

            case 'A':               /* full weekday */
                j = DayOfWeek ( ptm );
                strcpy ( buffer + i, Day_name[j] );
                while ( *(buffer + i) != '\0' )
                    i++;
                break;

            case 'w':               /* weekday as a digit */
                j = DayOfWeek ( ptm );
                buffer[i++] = j + '0';
                break;

                /*--- day of the month: 1, 2, 3...---*/

            case 'd':               /* day as a number */
                buffer[i++] = ptm->tm_mday / 10 + '0';
                buffer[i++] = ptm->tm_mday % 10 + '0';
                break;

            case 'm':               /* month as a number */
                buffer[i++] =  mon  / 10 + '0';
                buffer[i++] =  mon  % 10 + '0';
                break;

                /*--- month ---*/

            case 'b':               /* 3-letter month */
                strncpy ( buffer + i,
                          Month_name_abbrev[mon], 3 );
                i += 3;
                break;

            case 'B':               /* full month name */
                strcpy ( buffer + i, Month_name[mon] );
                while ( *(buffer + i) != '\0' )
                    i++;
                break;

                /*--- year ---*/

            case 'Y':               /* year with century: 1994 */
                yy = ptm->tm_year;

                if ( yy < 0 )
                {
                    buffer[i++] = '-';
                    yy = -yy;
                }

                if ( yy > 9999 )
                {
                    buffer[i++] = yy / 10000 + '0';
                    yy %= 10000;
                }

                if ( yy > 999 )
                {
                    buffer[i++] = yy / 1000 + '0';
                    yy %= 1000;
                }

                if ( yy > 99 )
                {
                    buffer[i++] = yy / 100 + '0';
                    yy %= 100;
                }

                buffer[i++] = yy / 10 + '0';
                buffer[i++] = yy % 10 + '0';
                break;

            case 'y':               /* year without century: 94 */
                yy = ptm->tm_year;

                if ( yy < 0 )
                {
                    buffer[i++] = '-';
                    yy = -yy;
                }

                if ( yy > 100 )
                    yy %= 100;

                buffer[i++] = yy / 10 + '0';
                buffer[i++] = yy % 10 + '0';
                break;

            case 'x':               /* locale-specific date */
            {
                char s[18];

                TimeSprintf ( s, 18, "%a, %b %d, %Y", ptm );
                strcpy ( buffer + i, s );
                i += strlen ( s );
            }
                break;

                /*--- time in numbers ---*/

            case 'I':               /* hour on 12-hr clock */
            {
                int hour;

                if ( ptm->tm_hour > 12 )
                    hour = ptm->tm_hour - 12;
                else
                    hour = ptm->tm_hour;

                buffer[i++] = hour / 10 + '0';
                buffer[i++] = hour % 10 + '0';
            }
                break;

            case 'H':               /* hour on 24-hr clock */
                buffer[i++] = ptm->tm_hour / 10 + '0';
                buffer[i++] = ptm->tm_hour % 10 + '0';
                break;

            case 'M':               /* minute as a number */
                buffer[i++] = ptm->tm_min / 10 + '0';
                buffer[i++] = ptm->tm_min % 10 + '0';
                break;

            case 'S':               /* seconds as a number */
                buffer[i++] = ptm->tm_sec / 10 + '0';
                buffer[i++] = ptm->tm_sec % 10 + '0';
                break;

            case 'X':               /* time string: hh:mm:ss */
            {
                char s[9];

                TimeSprintf ( s, 9, "%H:%M:%S", ptm );
                strcpy ( buffer + i, s );
                i += 8;
            }
                break;

                /*--- miscellaneous ---*/

            case 'c':               /* date and time */
            {
                char s[28];

                TimeSprintf ( s, 28, "%b %d %H:%M:%S %Y", ptm );
                strcpy ( buffer + i, s );
                i += strlen ( s );
            }
                break;

            case 'j':               /* day of the year: 1-366 */
            {
                int day_of_year;

                day_of_year = DayOfYear ( ptm );

                if ( day_of_year < 10 )
                    buffer[i++] = day_of_year + '0';
                else
                {
                    if ( day_of_year > 99 )
                    {
                        buffer[i++] = day_of_year / 100 + '0';
                        day_of_year %= 100;
                    }

                    buffer[i++] = day_of_year / 10 + '0';
                    buffer[i++] = day_of_year % 10 + '0';
                }
            }
                break;

            case 'p':               /* AM or PM */
                if ( ptm->tm_hour < 12 )
                    buffer[i++] = 'A';
                else
                    buffer[i++] = 'P';
                buffer[i++] = 'M';
                break;

            case 'U':               /* Sunday week of year */
            case 'W':               /* Monday week of year */
            {
                int day_of_year,
                    day_of_week,
                    sunday_week;

                struct tm jan1;

                int jan1_dow;       /* jan 1 day of week */

                day_of_year = DayOfYear ( ptm );
                day_of_week = DayOfWeek ( ptm );

                LoadDateStruct ( &jan1, ptm->tm_year, 1, 1 );
                jan1_dow = DayOfWeek ( &jan1 );

                if ( jan1_dow != 0 )
                    day_of_year -= ( 7 - jan1_dow );

                if ( day_of_year < 1 )
                    sunday_week = 0;
                else
                {
                    sunday_week = 1;
                    sunday_week += ( day_of_year - 1 ) / 7;
                }

                if ( *pf == 'W' )   /* if Monday week */
                    if ( day_of_week < 1 )
                        sunday_week -= 1;

                if ( sunday_week > 9 )
                {
                    buffer[i++] = ( sunday_week / 10 ) + '0';
                    sunday_week %= 10;
                }

                buffer[i++] = sunday_week + '0';
            }
                break;

            case 'Z':               /* the time zone */
            {
                char *temp;

                temp = setlocale ( LC_TIME, NULL );
                if ( temp == NULL )
                    buffer[i++] = 'C';
                else
                {
                    strcpy ( buffer + i, temp );
                    i += strlen ( temp );
                }
            }
                break;

            case '%':               /* the percent sign */
                buffer[i++] = '%';
                break;

            default:
                strcpy ( buffer + i, "Error in TimeSprintf() " );
                i += 23;
            }
    }
    buffer[i] = '\0';

    strncpy ( string, buffer, max_size );
    free ( buffer );

    if ( i <= max_size )
        return ( i );
    else
        return ( 0 );
}
Exemplo n.º 25
0
String   Format(Date date) {
	String  s;
	if(IsNull(date))
		return String();
	return Format(*s_date_format_thread ? s_date_format_thread : s_date_format_main, date.year, date.month, date.day, DayOfWeek(date));
}