如何将值 overdueDate 从 DateTime 变量转换为格式为 dd / mm / yyyy 00:00:00 的字符串
DateTime overdueDate;
DateTime today = DateTime.Now;
if (today.DayOfWeek == DayOfWeek.Monday)
{
overdueDate = today.AddDays(-12);
}
else if (today.DayOfWeek == DayOfWeek.Tuesday)
{
overdueDate = today.AddDays(-13);
}
else if (today.DayOfWeek == DayOfWeek.Wednesday)
{
overdueDate = today.AddDays(-7);
}
else if (today.DayOfWeek == DayOfWeek.Thursday)
{
overdueDate = today.AddDays(-8);
}
else if (today.DayOfWeek == DayOfWeek.Friday)
{
overdueDate = today.AddDays(-9);
}
else if (today.DayOfWeek == DayOfWeek.Saturday)
{
overdueDate = today.AddDays(-10);
}
else if (today.DayOfWeek == DayOfWeek.Sunday)
{
overdueDate = today.AddDays(-11);
}
答案 0 :(得分:3)
由于您只需Date
部分时间设置为00:00:00
,因此您可以使用DateTime.Date
属性并将其格式化为:
string str = overdueDate.Date.ToString("dd/MM/yyy HH:mm:ss");
请参阅:Custom Date and Time Format Strings
您在声明时尚未初始化overdueDate
,虽然您在条件中为其分配了一些值,但编译器无法确定是否会为其分配任何值。因此,您会收到错误“使用未分配的局部变量”。只需声明它:
DateTime overdueDate = default(DateTime);
答案 1 :(得分:1)
var dateString = overdueDate.ToString("dd/MM/yyyy HH:mm:ss");
为了向您提供更详细的信息,请参考custom date time format strings的文档。
这里需要注意的一点是,ToString
可以根据文档列出您可以设想的任何日期。
答案 2 :(得分:1)
我不是100%肯定你想要达到的目标,但我相信以下是一种更有效的方法。
DateTime overdueDate = DateTime.Now.AddDays(-7);
while (overdueDate.DayOfWeek != DayOfWeek.Wednesday)
overdueDate = overdueDate.AddDays(-1);