简体   繁体   English

C#从时间戳获取日期

[英]C# Getting Just Date From Timestamp

If I have a timestamp in the form: yyyy-mm-dd hh:mm:ss:mmm 如果我有一个时间戳形式:yyyy-mm-dd hh:mm:ss:mmm

How can I just extract the date from the timestamp? 如何从时间戳中提取日期?

For instance, if a timestamp reads: "2010-05-18 08:36:52:236" what is the best way to just get 2010-05-18 from it. 例如,如果时间戳显示为:“2010-05-18 08:36:52:236”,从中获取2010-05-18的最佳方法是什么。

What I'm trying to do is isolate the date portion of the timestamp, define a custom time for it to create a new time stamp. 我要做的是隔离时间戳的日期部分,定义它创建新时间戳的自定义时间。 Is there a more efficient way to define the time of the timestamp without first taking out the date, and then adding a new time? 是否有更有效的方法来定义时间戳的时间而不先取出日期,然后添加新的时间?

DateTime.Parse(“2010-05-18 08:36:52:236”)。ToString(“yyyy-MM-dd”);

You should use the DateTime type: 您应该使用DateTime类型:

DateTime original = DateTime.Parse(str);
DateTime modified = original.Date + new TimeSpan(13, 15, 00);
string str = modified.ToString("yyyy-MM-dd HH:mm:ss:fff");

Your format is non-standard, so you'll need to call ParseExact instead of Parse : 您的格式是非标准格式,因此您需要调用ParseExact而不是Parse

DateTime original = DateTime.ParseExact(str, "yyyy-MM-dd HH:mm:ss:fff", CultureInfo.InvariantCulture);

You could use substring : 你可以使用substring

"2010-05-18 08:36:52:236".Substring(0, 10);

Or use ParseExact : 或者使用ParseExact

DateTime.ParseExact("2010-05-18 08:36:52:236", 
                    "yyyy-MM-dd HH:mm:ss:fff", 
                    CultureInfo.InvariantCulture)
        .ToString("yyyy-MM-dd");
DateTime date;
if (DateTime.TryParse(dateString, out date))
{
   date = date.Date; // Get's the date-only component.
   // Do something cool.
}
else
{
   // Flip out because you didn't get a real date.
}

Get the .Date member on the DateTime 获取DateTime上的.Date成员

DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;

use it like this: 像这样用它:

var x = DateTime.Now.Date; //will give you midnight today

x.AddDays(1).AddTicks(-1); //use these method calls to modify the date to whats needed.

The best (and fastest) way to do this is to convert the date to an integer as the time part is stored in the decimal part. 最好(也是最快)的方法是将日期转换为整数,因为时间部分存储在小数部分中。

Try this: 尝试这个:

select convert(datetime,convert(int, @yourdate))

So you convert it to an integer and then back to a data and voila, time part is gone. 所以你把它转换成一个整数,然后再回到数据,瞧,时间部分消失了。

Of course subtracting this result from the original value will give you the time part only. 当然,从原始值中减去这个结果只会给你时间部分。

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

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