格式化DateTime没有字符串转换

Pau*_*hra 1 c# datetime datetime-format

我正在修改一些遗留代码,有这个......

DateTime dateTime = DateTime.Now;

DateTime from = DateTime.Parse(dateTime.ToString("dd/MM/yyyy 00:00:00"));
DateTime to = DateTime.Parse(dateTime.AddDays(8).ToString("dd/MM/yyyy 23:59:59"));
Run Code Online (Sandbox Code Playgroud)

然后,在Linq/Lambda比较中使用from和to变量,因此必须是DateTime.

我似乎无法找到一种方法来格式化DateTime变量而不将其转换为字符串,然后再返回到DateTime,这似乎至少可以说是愚蠢的.

当然必须有一种方法来格式化DateTime而不将其转换为字符串,然后再转换回DateTime?

Hab*_*bib 5

没有必要将您转换DateTime为字符串,然后将其解析回来DateTime,而不是使用DateTime.Date:

DateTime from = dateTime.Date;
DateTime to = dateTime.Date.AddDays(9).AddTicks(-1); //or .AddSeconds(-1) if you want 
                                                     // accuracy to a second. 
Run Code Online (Sandbox Code Playgroud)