sooprise
sooprise

Reputation: 23187

C# Getting Just Date From Timestamp

If I have a timestamp in the form: 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.

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?

Upvotes: 4

Views: 9158

Answers (7)

Cobusve
Cobusve

Reputation: 1570

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.

Upvotes: 0

VoodooChild
VoodooChild

Reputation: 9784

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.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

You should use the DateTime type:

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:

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

Upvotes: 7

Lance
Lance

Reputation: 5800

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.
}

Upvotes: 2

Kevin McKelvin
Kevin McKelvin

Reputation: 3547

Get the .Date member on the DateTime

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

Upvotes: 1

Andomar
Andomar

Reputation: 238086

You could use substring:

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

Or use ParseExact:

DateTime.ParseExact("2010-05-18 08:36:52:236", 
                    "yyyy-MM-dd HH:mm:ss:fff", 
                    CultureInfo.InvariantCulture)
        .ToString("yyyy-MM-dd");

Upvotes: 2

Run CMD
Run CMD

Reputation: 3035

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

Upvotes: 9

Related Questions