简体   繁体   English

从 C# 中的日期中删除时间戳?

[英]Remove timestamp from date in C#?

I have a date like this: 2011-03-29 00:00:00.000我有一个这样的日期:2011-03-29 00:00:00.000

I want to remove the timestamp from that, is that possible?我想从中删除时间戳,这可能吗?

Thanks :-)谢谢 :-)

DateTime 类的实例具有仅显示日期的 ToShortDateString 方法

也许:

date.ToString("yyyy-MM-dd");

Probably the easiest way to do this is to use the parse function within the DateTime class which takes a string in the format you've described:可能最简单的方法是使用 DateTime 类中的 parse 函数,它采用您所描述的格式的字符串:

http://msdn.microsoft.com/en-us/library/1k1skd40%28v=VS.90%29.aspx http://msdn.microsoft.com/en-us/library/1k1skd40%28v=VS.90%29.aspx

You can then use the 'Date' property within the class to get the date without the time stamp.然后,您可以使用类中的“日期”属性来获取不带时间戳的日期。

Hope this helps.希望这可以帮助。

try尝试

DateTime d ="2011-03-29  00:00:00';
string strDate = d.ToShortDateString();

Or或者

string strDate = d.ToString("dd/MM/yyyy");

There are a few ways to do this, however some depend on assumptions.有几种方法可以做到这一点,但有些方法取决于假设。

a) convert it date/time and then output just the date, the time is still there if you had wanted it b) copy the string upto the first space c) copy the first 11 characters (eg the date) d) regex the output to confirm its a date/time format and then pull out the date a) 转换它的日期/时间,然后只输出日期,如果你想要它,时间仍然存在 b) 将字符串复制到第一个空格 c) 复制前 11 个字符(例如日期) d) 正则表达式输出确认其日期/时间格式,然后拉出日期

It depends a little I guess on what you want to do with it after and assuming it is a string in the first place.我猜这取决于你想用它做什么,并假设它首先是一个字符串。 if not myDateTime.tostring('YM-D') would work.如果不是myDateTime.tostring('YM-D')将起作用。

                DataColumn date = new DataColumn("date");
                date.DataType = System.Type.GetType("System.String");
                SomeDataTable.Columns.Add(date);
                date.SetOrdinal(n); //placing it in the n+1th position
                //n is where the actual column you want to replace is
                foreach (DataRow dr in SomeDataTable.Rows)
                {
                    DateTime date;
                    if (DateTime.TryParse(dr["date"].ToString(), out date))
                    {
                        dr["date"] = convert.ToDateTime(dr["date"]).ToString("MM/dd/yyyy");
                    }
                }
                SomeDataTable.Columns.RemoveAt(n-1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM