284

How can I exactly construct a time stamp of actual time with milliseconds precision?

I need something like 16.4.2013 9:48:00:123. Is this possible? I have an application, where I sample values 10 times per second, and I need to show them in a graph.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LuckyHK
  • 2,851
  • 2
  • 13
  • 6
  • Related http://msdn.microsoft.com/en-us/library/bb882581.aspx – Soner Gönül Apr 16 '13 at 08:47
  • Be aware that a number of the answers are using `hh` for hours (standard time). In the case of a timestamp (and in many other cases) this should probably be paired with `tt` (am/pm) or replaced by `HH` (military time). – wentz Mar 07 '19 at 19:27

12 Answers12

371

How can I exactly construct a time stamp of actual time with milliseconds precision?

I suspect you mean millisecond accuracy. DateTime has a lot of precision, but is fairly coarse in terms of accuracy. Generally speaking, you can't. Usually the system clock (which is where DateTime.Now gets its data from) has a resolution of around 10-15 ms. See Eric Lippert's blog post about precision and accuracy for more details.

If you need more accurate timing than this, you may want to look into using an NTP client.

However, it's not clear that you really need millisecond accuracy here. If you don't care about the exact timing - you just want to show the samples in the right order, with "pretty good" accuracy, then the system clock should be fine. I'd advise you to use DateTime.UtcNow rather than DateTime.Now though, to avoid time zone issues around daylight saving transitions, etc.

If your question is actually just around converting a DateTime to a string with millisecond precision, I'd suggest using:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff",
                                            CultureInfo.InvariantCulture);

(Note that unlike your sample, this is sortable and less likely to cause confusion around whether it's meant to be "month/day/year" or "day/month/year".)

Callum Watkins
  • 2,844
  • 4
  • 29
  • 49
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • 5
    @antonio: With no more information than "don't works" I can't provide any more help. – Jon Skeet Feb 01 '18 at 06:57
  • Yes, I can provide more info: "{0:yyyyMMdd HH:mm:ss.fff}", DateTime.UtcNow -> 20180502 11:07:20.000 Win32.GetSystemTime(ref stime) -> 2018,2,5,11,7,20,0 (y m d h mm ss ms) I can create a instance of date time with milliseconds: var dt = new DateTime(2018, 5, 2, 19, 34, 55, 200); "{0:yyyyMMdd HH:mm:ss.fff}", dt -> 20180502 19:34:55.200 .Net compact framework, Windows Embedded Compact 7, on ARM Cortex-A8 – antonio Feb 05 '18 at 11:23
  • @antonio: So it sounds like the version of .NET you're using on the hardware you're using simply doesn't provide subsecond accuracy - or you happened to call it on a second boundary. (If you keep hitting `DateTime.UtcNow` repeatedly, does it only ever increment once per second? You haven't shown that.) – Jon Skeet Feb 05 '18 at 11:25
  • When I retrieve Ticks from DateTime.Now, the value come truncated: Ticks 636534596580000000 DateTime from Ticks 20180205 20:34:18.000. the limitation is in the hard/software, i think. I have using Stopwatch class, instead Thanks Jon – antonio Feb 05 '18 at 11:41
  • @antonio: It's probably worth creating a new question with full details of the device involved at this point. – Jon Skeet Feb 05 '18 at 11:41
  • @JonSkeet I am struggling to understand 2020-09-04T14:29:40.101935+02:00 the miliseconds part here, why is it like 101395 ? I mean i expecte 1 second to have like 1000 ms , and this number looks bigger than that ? What does the last 101395 actually represents in a UTC format ? – kuldeep Sep 04 '20 at 13:07
  • @kuldeep: That's not milliseconds, that's microseconds. But I've no idea where that came from - I suspect you should ask a new question. – Jon Skeet Sep 04 '20 at 14:10
  • @JonSkeet .. somehow i am unable to ask a new question on SO. This was saved in postgres DB as timestamptz from datetime.UtcNow field from .net core app ! – kuldeep Sep 05 '20 at 06:30
  • 1
    @kuldeep: I'm afraid if you've asked sufficiently bad questions to be question-banned, I'm not going to try to bypass that by getting into what *should* be another question via comments. I suggest you edit your old questions to be better, to try to remove the ban. – Jon Skeet Sep 05 '20 at 06:53
140

This should work:

DateTime.Now.ToString("hh.mm.ss.ffffff");

If you don't need it to be displayed and just need to know the time difference, well don't convert it to a String. Just leave it as, DateTime.Now();

And use TimeSpan to know the difference between time intervals:

Example

DateTime start;
TimeSpan time;

start = DateTime.Now;

//Do something here

time = DateTime.Now - start;
label1.Text = String.Format("{0}.{1}", time.Seconds, time.Milliseconds.ToString().PadLeft(3, '0'));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Pyromancer
  • 2,429
  • 5
  • 19
  • 28
29

I was looking for a similar solution, base on what was suggested on this thread, I use the following DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff") , and it work like charm. Note: that .fff are the precision numbers that you wish to capture.

Luis
  • 5,786
  • 8
  • 43
  • 62
Jozcar
  • 976
  • 9
  • 11
  • 1
    If the date is in afternoon (4PM) will shows as in the morning. **FIX:** Use `HH` (military time) or add `tt` (PM or AM). As shown in this example: https://repl.it/KGr3/1 – Jaider Aug 11 '17 at 22:12
22

Use DateTime Structure with milliseconds and format like this:

string timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.fff", 
CultureInfo.InvariantCulture);
timestamp = timestamp.Replace("-", ".");
Jacman
  • 1,486
  • 3
  • 20
  • 32
17

Pyromancer's answer seems pretty good to me, but maybe you wanted:

DateTime.Now.Millisecond

But if you are comparing dates, TimeSpan is the way to go.

Community
  • 1
  • 1
Renae
  • 432
  • 1
  • 6
  • 16
  • 19
    Note: If you're comparing the difference between two DateTimes as a TimeSpan, you need `TotalMilliseconds`. Milliseconds holds the current Milliseconds counter, which is never greater than 1000, whereas TotalMilliseconds holds the total milliseconds elapsed since the epoch. – Contango Sep 12 '14 at 11:48
5

If you still want a date instead of a string like the other answers, just add this extension method.

public static DateTime ToMillisecondPrecision(this DateTime d) {
    return new DateTime(d.Year, d.Month, d.Day, d.Hour, d.Minute,
                        d.Second, d.Millisecond, d.Kind);
}
pirho
  • 11,565
  • 12
  • 43
  • 70
birch
  • 51
  • 1
  • 2
3

As far as I understand the question, you can go for:

DateTime dateTime = DateTime.Now;
DateTime dateTimeInMilliseconds = dateTime.AddTicks(-1 * dateTime.Ticks % 10000); 

This will cut off ticks smaller than 1 millisecond.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
3

Another option is to construct a new DateTime instance from the source DateTime value:

// current date and time
var now = DateTime.Now;

// modified date and time with millisecond accuracy
var msec = new DateTime(now.Year, now.Month, now.Day, now.Hour, now.Minute, now.Second, now.Millisecond, now.Kind);

There's no need to do any to-string and from-string conversions, and it's also very well understandable and readable code.

Ondrej Tucny
  • 27,626
  • 6
  • 70
  • 90
2

The trouble with DateTime.UtcNow and DateTime.Now is that, depending on the computer and operating system, it may only be accurate to between 10 and 15 milliseconds. However, on windows computers one can use by using the low level function GetSystemTimePreciseAsFileTime to get microsecond accuracy, see the function GetTimeStamp() below.

    [System.Security.SuppressUnmanagedCodeSecurity, System.Runtime.InteropServices.DllImport("kernel32.dll")]
    static extern void GetSystemTimePreciseAsFileTime(out FileTime pFileTime);

    [System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
    public struct FileTime  {
        public const long FILETIME_TO_DATETIMETICKS = 504911232000000000;   // 146097 = days in 400 year Gregorian calendar cycle. 504911232000000000 = 4 * 146097 * 86400 * 1E7
        public uint TimeLow;    // least significant digits
        public uint TimeHigh;   // most sifnificant digits
        public long TimeStamp_FileTimeTicks { get { return TimeHigh * 4294967296 + TimeLow; } }     // ticks since 1-Jan-1601 (1 tick = 100 nanosecs). 4294967296 = 2^32
        public DateTime dateTime { get { return new DateTime(TimeStamp_FileTimeTicks + FILETIME_TO_DATETIMETICKS); } }
    }

    public static DateTime GetTimeStamp() { 
        FileTime ft; GetSystemTimePreciseAsFileTime(out ft);
        return ft.dateTime;
    }
Stochastically
  • 7,616
  • 5
  • 30
  • 58
0

try using datetime.now.ticks. this provides nanosecond precision. taking the delta of two ticks (stoptick - starttick)/10,000 is the millisecond of specified interval.

https://learn.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2

darkstar
  • 11
  • 1
-2
public long millis() {
  return (long.MaxValue + DateTime.Now.ToBinary()) / 10000;
}

If you want microseconds, just change 10000 to 10, and if you want the 10th of micro, delete / 10000.

Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
distiking
  • 7
  • 3
-3

DateTime.Now.ToString("ddMMyyyyhhmmssffff")

amol jadhao
  • 118
  • 6