25 HAZİRAN 2009, PERŞEMBE
Ekle İş Günü ve GetBusinessDays
2 zarif tam uygulamaları bulmam lazım
public static DateTime AddBusinessDays(this DateTime date, int days)
{
// code here
}
and
public static int GetBusinessDays(this DateTime start, DateTime end)
{
// code here
}
(1) tercih (döngüler) Ç.
EDİT: İş günü iş günü (Pazartesi, Salı, Çarşamba, Perşembe, Cuma). Hayır tatil, sadece hafta sonları hariç.
Ben zaten bu kişiler çirkin çözümler var ama eğer bunu yapmak için zarif bir yol olup olmadığını merak ediyorum. Teşekkürler
Bu şimdiye kadar yazdım. Tüm durumlarda çalışır ve çok negatifleri yok. Hala GetBusinessDays bir uygulama gerekir
public static DateTime AddBusinessDays(this DateTime startDate,
int businessDays)
{
int direction = Math.Sign(businessDays);
if(direction == 1)
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(2);
businessDays = businessDays - 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(1);
businessDays = businessDays - 1;
}
}
else
{
if(startDate.DayOfWeek == DayOfWeek.Saturday)
{
startDate = startDate.AddDays(-1);
businessDays = businessDays 1;
}
else if(startDate.DayOfWeek == DayOfWeek.Sunday)
{
startDate = startDate.AddDays(-2);
businessDays = businessDays 1;
}
}
int initialDayOfWeek = Convert.ToInt32(startDate.DayOfWeek);
int weeksBase = Math.Abs(businessDays / 5);
int addDays = Math.Abs(businessDays % 5);
if((direction == 1 && addDays initialDayOfWeek > 5) ||
(direction == -1 && addDays >= initialDayOfWeek))
{
addDays = 2;
}
int totalDays = (weeksBase * 7) addDays;
return startDate.AddDays(totalDays * direction);
}
CEVAP
25 HAZİRAN 2009, PERŞEMBE
En son ilk işlevi için çalışır:
public static DateTime AddBusinessDays(DateTime date, int days)
{
if (days < 0)
{
throw new ArgumentException("days cannot be negative", "days");
}
if (days == 0) return date;
if (date.DayOfWeek == DayOfWeek.Saturday)
{
date = date.AddDays(2);
days -= 1;
}
else if (date.DayOfWeek == DayOfWeek.Sunday)
{
date = date.AddDays(1);
days -= 1;
}
date = date.AddDays(days / 5 * 7);
int extraDays = days % 5;
if ((int)date.DayOfWeek extraDays > 5)
{
extraDays = 2;
}
return date.AddDays(extraDays);
}
İkinci işlevi, GetBusinessDays, aşağıdaki gibi uygulanabilir
public static int GetBusinessDays(DateTime start, DateTime end)
{
if (start.DayOfWeek == DayOfWeek.Saturday)
{
start = start.AddDays(2);
}
else if (start.DayOfWeek == DayOfWeek.Sunday)
{
start = start.AddDays(1);
}
if (end.DayOfWeek == DayOfWeek.Saturday)
{
end = end.AddDays(-1);
}
else if (end.DayOfWeek == DayOfWeek.Sunday)
{
end = end.AddDays(-2);
}
int diff = (int)end.Subtract(start).TotalDays;
int result = diff / 7 * 5 diff % 7;
if (end.DayOfWeek < start.DayOfWeek)
{
return result - 2;
}
else{
return result;
}
}
Bunu Paylaş:
Nasıl bugün için gün sayısını Ekle...
Can't taşınmış bir çalışma alanı ...
Nasıl Perl'in yazdırma varsayılan...
Nasıl SQL bir ayın ilk günü tercih ede...
'olmayan mutasyona " için en ...