Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Getting Just Date From Timestamp

Tags:

c#

sql

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?

like image 506
sooprise Avatar asked Nov 29 '22 18:11

sooprise


2 Answers

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

like image 197
Run CMD Avatar answered Dec 10 '22 04:12

Run CMD


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);
like image 21
SLaks Avatar answered Dec 10 '22 04:12

SLaks