我正在使用C#winforms开发一个视频租赁应用程序,并遇到了一个我似乎无法编写或找到解决方案的问题。
程序需要检查当前日期和过去的天数以及它们之间的范围。
如果当前日期小于或等于指定日期,则不会计算罚金。
否则,如果今天的日期已经超过指定的日期,它将计算罚款成本乘以它们之间经过的天数。
以下是我玩过这个想法的示例代码:
DateTime db = DateTime.Parse(dateBeforeString);
DateTime dt = DateTime.Now;
var dateDiff = (dt - db);
double totalDays = dateDiff.TotalDays;
int totalPenalty = initialPenaltyInt*(int)Convert.ToInt64(totalDays);
int totalCost = totalPenalty + rentalCostInt;
if(DateTime.Now != db)
{
//do stuff here to:
//check if current day is less than the one on the database
//set total penalty to zero
}
else if(DateTime.Now > db)
{
//otherwise calculate the total penalty cost multipled by the number of days passed since a specific date
}
答案 0 :(得分:1)
简单,但可能有助于你进步,希望:
public class Penalties
{
// What about this choice of "int" (vs. decimal)?
public virtual int ComputeOverdueDaysPenalty(int penaltyPerOverdueDay, DateTime dueDate)
{
// Work only with year, month, day, to drop time info and ignore time zone
dueDate = new DateTime(dueDate.Year, dueDate.Month, dueDate.Day);
var now = DateTime.Now;
now = new DateTime(now.Year, now.Month, now.Day);
return now > dueDate ? (int)now.Subtract(dueDate).TotalDays * penaltyPerOverdueDay : 0;
}
}
class Program
{
static void Main(string[] args)
{
var penalties = new Penalties();
var now = DateTime.Now;
// due = today
// should print 0
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, new DateTime(now.Year, now.Month, now.Day)));
// due = today plus 1
var dueDate = now.AddDays(1);
// should print 0 again
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
// due = today minus 1
dueDate = dueDate.Subtract(new TimeSpan(48, 0, 0));
// should print 1234
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
// due = today minus 2
dueDate = dueDate.Subtract(new TimeSpan(24, 0, 0));
// should print 2468
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
dueDate = DateTime.Parse("2016-10-02");
// should print 12340, as of 10/12/2016
Console.WriteLine(penalties.ComputeOverdueDaysPenalty(1234, dueDate));
Console.ReadKey();
}
}
只是一句话:
我觉得你在这种情况下使用int类型已经确定了一点奇怪,顺便说一句。
如果你的"惩罚"单位实际上是某种货币,在大多数用例中,推荐的数据类型是十进制。
'希望这会有所帮助。