C # Getting only dates from a timestamp

If I have a timestamp in the form: yyyy-mm-dd hh: mm: ss: mmm

How can I just extract a date from a timestamp?

For example, if the time stamp reads: "2010-05-18 08: 36: 52: 236", which is the best way to get it from 2010-05-18.

What I'm trying to do is to highlight a part of the timestamp date, determine the time when it will create a new timestamp. Is there a more efficient way to determine the timestamp time without first selecting a date and then adding a new time?

+4
source share
7 answers

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

+9
source

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 need to call ParseExact instead of Parse :

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

You can 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"); 
+2
source
 DateTime date; if (DateTime.TryParse(dateString, out date)) { date = date.Date; // Get the date-only component. // Do something cool. } else { // Flip out because you didn't get a real date. } 
+2
source

Get .Date member in DateTime

 DateTime date = DateTime.Now; DateTime midnightDate = date.Date; 
+1
source

use it as follows:

 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. 
0
source

The best (and fastest) way to do this is to convert the date to an integer, since the temporary part is stored in decimal.

Try the following:

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

So, you convert it to an integer, and then back to the data and voila, part of the time is gone.

Of course, subtracting this result from the original value will give you only a fraction of the time.

0
source

Source: https://habr.com/ru/post/1310115/


All Articles