Calculate date, based on specified time and unit
/**********************************************************
* Author : Riwut Libinuko (cakriwut@gmail.com)
* Blog : http://blog.libinuko.com
* Copyright : Riwut Libinuko (c) 2009 - 2010
*
**********************************************************/
using System;
using System.Collections.Generic;
using System.Text;
namespace ScheduleAlertJob
{
/// <summary>
/// Utility class to provide simple operations for other components.
/// </summary>
public class Utility
{
/// <summary>
/// Calculate date, based on specified time and unit
/// </summary>
/// <param name="refDate">Reference date of the event</param>
/// <param name="reminderTime">Array of reminder time. The value is comming from SPFieldMultiChoice</param>
/// <returns></returns>
public static List<DateTime> CalculateDate(DateTime refDate, string[] reminderTime)
{
return CalculateDate(refDate, reminderTime, true);
}
/// <summary>
/// Calculate date, based on specified time and unit
/// </summary>
/// <param name="refDate">Reference date of the event</param>
/// <param name="reminderTime">Array of reminder time. The value is comming from SPFieldMultiChoice</param>
/// <param name="beforeTime">True to calculate time before refDate, false to reverse calculation</param>
/// <returns></returns>
public static List<DateTime> CalculateDate(DateTime refDate, string[] reminderTimeCollection, bool beforeTime)
{
List<DateTime> resultDates = new List<DateTime>();
foreach (string remindTime in reminderTimeCollection)
{
string[] reminderTime = remindTime.Split(new char[] { '(', ')' });
string spanTime = reminderTime[0].Trim().Substring(0, reminderTime[0].Trim().Length - 2);
double spanTimeVal;
if (double.TryParse(spanTime, out spanTimeVal))
{
if (beforeTime)
spanTimeVal = -spanTimeVal;
if (reminderTime[0].Trim().EndsWith("mi"))
{
resultDates.Add(refDate.AddMinutes(spanTimeVal));
}
else if (reminderTime[0].Trim().EndsWith("hr"))
{
resultDates.Add(refDate.AddHours(spanTimeVal));
}
else if (reminderTime[0].Trim().EndsWith("dy"))
{
resultDates.Add(refDate.AddDays(spanTimeVal));
}
else if (reminderTime[0].Trim().EndsWith("wk"))
{
resultDates.Add(refDate.AddDays(((double)7 * spanTimeVal)));
}
else if (reminderTime[0].Trim().EndsWith("mo"))
{
resultDates.Add(refDate.AddMonths((int)spanTimeVal));
}
else if (reminderTime[0].Trim().EndsWith("yr"))
{
resultDates.Add(refDate.AddYears((int)spanTimeVal));
}
}
}
resultDates.Sort();
return resultDates;
}
/// <summary>
/// Find date greater than TODAY
/// </summary>
/// <param name="dateTime">DateTime to compare</param>
/// <returns></returns>
public static bool DateGreaterThanToday(DateTime dateTime)
{
if (dateTime.CompareTo(DateTime.Now) > 0)
return true;
else
return false;
}
}
}
Related examples in the same category