tags:

views:

323

answers:

7

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?

+8  A: 

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

Run CMD
Did you get a chance to read the second part of my question? If there is a preferred way to do this, I would really like to know. Otherwise, what you have written here seems legit, Thanks.
Soo
Well what do you mean by 'more efficient' ? If you want it faster, you could compare different methods with a profiler ? I think the method Andomar suggested will be faster ? (The substring)
Run CMD
Gives a `String was not recognized as a valid DateTime.` exception on my machine
Andomar
Yeah you should use CultureInfo.InvariantCulture somewhere
Run CMD
+2  A: 

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");
Andomar
+1 for ParceExact
fishhead
+6  A: 

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);
SLaks
+1  A: 

Get the .Date member on the DateTime

DateTime date = DateTime.Now;
DateTime midnightDate = date.Date;
Kevin McKelvin
+2  A: 
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.
}
Lance May
A: 

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.
VoodooChild
DateTime is immutable. You can't modify the date - you're creating a new one, which you happen to be throwing away instead of storing in a variable.
Joel Mueller
A: 

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.

Cobusve