Saving current time without millisecond component

I have a timepan object that should only contain time, no date. I would use

DateTime.Now.TimeOfDay 

but the problem is that it gives time in format

 15:51:51.7368329 

I don't need the millisecond component. How can i crop it?

+7
source share
7 answers

You can use the DateTime.Now.Hour/Minute/Second properties or use DateTime.Now.ToString("HH:mm:ss") .

See more information: http://msdn.microsoft.com/en-us/library/zdtaw1bw.aspx

+10
source

I believe that this is what you can after:

 TimeSpan timeNow = DateTime.Now.TimeOfDay; TimeSpan trimmedTimeNow = new TimeSpan(timeNow.Hours, timeNow.Minutes, timeNow.Seconds); 
+8
source

Just subtract the millisecond part:

 DateTime myTime = DateTime.Now.TimeOfDay; myTime = myTime.AddMilliseconds(-myTime.Millisecond); 

This can be done in less code without first assigning myTime :

 DateTime myTime = DateTime.Now.TimeOfDay.AddMilliseconds( -DateTime.Now.TimeOfDay.Millisecond); 

Although somewhat elegant, this is a bad idea. When accessing TimeOfDay twice, there is a chance that it will at some point pass another millisecond before the second access. In this case, the result will not be zero milliseconds.

+6
source

If the problem is displayed, you can do this:

 DateTime.Now.ToString("HH:mm:ss") 
+4
source
  • When displayed to the user, you can specify the desired format. Here is a good tutorial:

http://www.geekzilla.co.uk/View00FF7904-B510-468C-A2C8-F859AA20581F.htm

  • You can create a new DateTime object that is passed to the constructor only for an hour, minute, second (to save.)
+1
source

You can use this function to check which format suits you:

 DateTime.Now.GetDateTimeFormats(); 

This will give you all formats, for example:

  • "14/05/2011"
  • "14/05/11"
  • "14.05.11"
  • "14-05-11"
  • "2011-05-14"
  • and etc.
+1
source

You can do it -

 DateTime.Parse( DateTime.Now.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"), System.Globalization.CultureInfo.CurrentCulture ); 

Worked for me :).

0
source

All Articles