如何从C#中的Datetime变量中仅获取日期格式 [英] how to get only date format from Datetime variable in C#
问题描述
DateTime fromDate = DateTime.Parse(HttpContext.Current.Session [a]。ToString());
DateTime toDate = DateTime.Parse(HttpContext .Current.Session [b]。ToString());
我只想在两个变量中都有日期格式,而不是时间。
我的会话变量中的
分别是1/2/2012和5/2/2012的值格式
如果我这样做,
fromDate = fromDate.Date;
它仍然是给出日期和时间格式。
fromDate = fromDate.Date;
这段代码是正确的,因为DateTime类总是有时间。如果使用.Date函数,则仅通过将时间设置为00:00:00来返回日期。这就够了。仅输出您可能想要使用.ToString方法的不同模式的日期:
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm [ ^ ]
看看DateTime.Date [ ^ ] property:
< pre lang =c#> DateTime dt = DateTime.Now;
DateTime dateOnly = dt.Date;
或者,您可以通过多种方式格式化DateTime:格式化显示的日期时间 - 格式字符串描述 [ ^ ]
.NET日期,时间和日期时间没有区别。这是一个使用问题。
String .Format( < span class =code-string> {0:d / M / yyyy},fromDate);
或
fromDate.toString( d / M / yyyy);
DateTime fromDate = DateTime.Parse(HttpContext.Current.Session["a"].ToString());
DateTime toDate = DateTime.Parse(HttpContext.Current.Session["b"].ToString());
I only want date format in both the variables, not time.
in my session variable there is value format like 1/2/2012 and 5/2/2012 respectively
if i do as,
fromDate = fromDate.Date;
it still gives both date and time format.
fromDate = fromDate.Date;
This code is correct, since the DateTime class always has a time with it. If you use the .Date function it returns only the date by setting the time to 00:00:00. This is enough. For outputting only the date you may want to use the different patterns for the .ToString method:
http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm[^]
Look at the DateTime.Date[^] property:
DateTime dt = DateTime.Now; DateTime dateOnly = dt.Date;
Alternatively, you can format a DateTime in many, many ways for display: Formatting a DateTime for display - format string description[^]
.NET is not making difference between Date, Time and Datetime. It is a matter of usage.
String.Format("{0:d/M/yyyy}", fromDate);
or
fromDate.toString("d/M/yyyy");
这篇关于如何从C#中的Datetime变量中仅获取日期格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!