DateTime string format in c#

那年仲夏 提交于 2019-12-02 07:22:11

问题


I have a project that contain 3 string variables.

  1. DateFormatStr is the format string I need to use to output dates.
  2. DateFormatFrom is the start date a request will apply from
  3. FilloutDateTo is the end date the request will apply to.

The problem is that I don't want to manually specify the dates. As you can see in my example below (a working example), I need to specify the dates, but is there a way to make it that the from date has time 00:00:00 and the end date has time 23:59:59?

string DateFormatStr = "MM/dd/yy hh:mm:ss tt";
string DateFormatFrom = "12/04/14 00:00:00";
string FilloutDateTo = "12/04/14 23:59:59";

So I would like to the system time to recognize the from date and the start date respecting the formatStr variable.

Thanks


回答1:


If I understand correctly, you can use DateTime.Today property like;

var dt1 = DateTime.Today;
var dt2 = DateTime.Today.AddDays(1).AddSeconds(-1);

and use DateTime.ToString() to format them like;

var DateFormatFrom = dt1.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);
var FilloutDateTo = dt2.ToString("MM/dd/yyyy HH:mm:ss", CultureInfo.InvariantCulture);

Results will be;

12/04/2014 00:00:00
12/04/2014 23:59:59

You used hh format specifier but it is for 12-hour clock. Use HH format specifier instead which is for 24-hour clock. And since your result strings doesn't have any AM/PM designator, you don't need to use tt format specifier.




回答2:


string idate = "01/11/2019 19:00:00";
DateTime odate = Convert.ToDateTime(idate);
DateTime sdate1 = DateTime.Parse(idate);
string outDate1 = String.Format("{0}/{1}/{2}", sdate1.Day, sdate1.Month,sdate1.Year);
Console.WriteLine(outDate1);


来源:https://stackoverflow.com/questions/27303110/datetime-string-format-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!