Get DateTime.Now with milliseconds precision - Stack Overflow
文章推薦指數: 80 %
I have an application, where I sample values 10 times per second, and I need to show them in a graph. c# datetime precision milliseconds · Share.
Home
Public
Questions
Tags
Users
Collectives
ExploreCollectives
FindaJob
Jobs
Companies
Teams
StackOverflowforTeams
–Collaborateandshareknowledgewithaprivategroup.
CreateafreeTeam
WhatisTeams?
Teams
CreatefreeTeam
CollectivesonStackOverflow
Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost.
Learnmore
Teams
Q&Aforwork
Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch.
Learnmore
GetDateTime.Nowwithmillisecondsprecision
AskQuestion
Asked
8years,11monthsago
Modified
11monthsago
Viewed
470ktimes
265
43
HowcanIexactlyconstructatimestampofactualtimewithmillisecondsprecision?
Ineedsomethinglike16.4.20139:48:00:123.Isthispossible?Ihaveanapplication,whereIsamplevalues10timespersecond,andIneedtoshowtheminagraph.
c#datetimeprecisionmilliseconds
Share
Improvethisquestion
Follow
editedJul16,2015at8:15
PeterMortensen
29.8k2121goldbadges9898silverbadges124124bronzebadges
askedApr16,2013at8:41
LuckyHKLuckyHK
2,66122goldbadges1111silverbadges66bronzebadges
2
Relatedmsdn.microsoft.com/en-us/library/bb882581.aspx
– SonerGönül
Apr16,2013at8:47
Beawarethatanumberoftheanswersareusinghhforhours(standardtime).Inthecaseofatimestamp(andinmanyothercases)thisshouldprobablybepairedwithtt(am/pm)orreplacedbyHH(militarytime).
– wentz
Mar7,2019at19:27
Addacomment
|
12Answers
12
Sortedby:
Resettodefault
Highestscore(default)
Datemodified(newestfirst)
Datecreated(oldestfirst)
346
HowcanIexactlyconstructatimestampofactualtimewithmillisecondsprecision?
Isuspectyoumeanmillisecondaccuracy.DateTimehasalotofprecision,butisfairlycoarseintermsofaccuracy.Generallyspeaking,youcan't.Usuallythesystemclock(whichiswhereDateTime.Nowgetsitsdatafrom)hasaresolutionofaround10-15ms.SeeEricLippert'sblogpostaboutprecisionandaccuracyformoredetails.
Ifyouneedmoreaccuratetimingthanthis,youmaywanttolookintousinganNTPclient.
However,it'snotclearthatyoureallyneedmillisecondaccuracyhere.Ifyoudon'tcareabouttheexacttiming-youjustwanttoshowthesamplesintherightorder,with"prettygood"accuracy,thenthesystemclockshouldbefine.I'dadviseyoutouseDateTime.UtcNowratherthanDateTime.Nowthough,toavoidtimezoneissuesarounddaylightsavingtransitions,etc.
IfyourquestionisactuallyjustaroundconvertingaDateTimetoastringwithmillisecondprecision,I'dsuggestusing:
stringtimestamp=DateTime.UtcNow.ToString("yyyy-MM-ddHH:mm:ss.fff",
CultureInfo.InvariantCulture);
(Notethatunlikeyoursample,thisissortableandlesslikelytocauseconfusionaroundwhetherit'smeanttobe"month/day/year"or"day/month/year".)
Share
Improvethisanswer
Follow
editedFeb23,2020at3:49
CallumWatkins
2,56522goldbadges3131silverbadges4545bronzebadges
answeredApr16,2013at8:45
JonSkeetJonSkeet
1.3m817817goldbadges88958895silverbadges90319031bronzebadges
9
5
@antonio:Withnomoreinformationthan"don'tworks"Ican'tprovideanymorehelp.
– JonSkeet
Feb1,2018at6:57
Yes,Icanprovidemoreinfo:"{0:yyyyMMddHH:mm:ss.fff}",DateTime.UtcNow->2018050211:07:20.000Win32.GetSystemTime(refstime)->2018,2,5,11,7,20,0(ymdhmmssms)Icancreateainstanceofdatetimewithmilliseconds:vardt=newDateTime(2018,5,2,19,34,55,200);"{0:yyyyMMddHH:mm:ss.fff}",dt->2018050219:34:55.200.Netcompactframework,WindowsEmbeddedCompact7,onARMCortex-A8
– antonio
Feb5,2018at11:23
@antonio:Soitsoundsliketheversionof.NETyou'reusingonthehardwareyou'reusingsimplydoesn'tprovidesubsecondaccuracy-oryouhappenedtocallitonasecondboundary.(IfyoukeephittingDateTime.UtcNowrepeatedly,doesitonlyeverincrementoncepersecond?Youhaven'tshownthat.)
– JonSkeet
Feb5,2018at11:25
WhenIretrieveTicksfromDateTime.Now,thevaluecometruncated:Ticks636534596580000000DateTimefromTicks2018020520:34:18.000.thelimitationisinthehard/software,ithink.IhaveusingStopwatchclass,insteadThanksJon
– antonio
Feb5,2018at11:41
1
@kuldeep:I'mafraidifyou'veaskedsufficientlybadquestionstobequestion-banned,I'mnotgoingtotrytobypassthatbygettingintowhatshouldbeanotherquestionviacomments.Isuggestyouedityouroldquestionstobebetter,totrytoremovetheban.
– JonSkeet
Sep5,2020at6:53
|
Show4morecomments
131
Thisshouldwork:
DateTime.Now.ToString("hh.mm.ss.ffffff");
Ifyoudon'tneedittobedisplayedandjustneedtoknowthetimedifference,welldon'tconvertittoaString.Justleaveitas,DateTime.Now();
AnduseTimeSpantoknowthedifferencebetweentimeintervals:
Example
DateTimestart;
TimeSpantime;
start=DateTime.Now;
//Dosomethinghere
time=DateTime.Now-start;
label1.Text=String.Format("{0}.{1}",time.Seconds,time.Milliseconds.ToString().PadLeft(3,'0'));
Share
Improvethisanswer
Follow
editedJul16,2015at8:17
PeterMortensen
29.8k2121goldbadges9898silverbadges124124bronzebadges
answeredApr16,2013at8:45
PyromancerPyromancer
2,32355goldbadges1818silverbadges2828bronzebadges
2
Ineedcomputewithit,soIcan'tconvertittostring.
– LuckyHK
Apr16,2013at8:50
Notethatthemostprecisionforsub-secondsisapparently7,asin"hh.mm.ss.fffffff".
– Nae
Jun29,2021at21:17
Addacomment
|
28
Iwaslookingforasimilarsolution,baseonwhatwassuggestedonthisthread,Iusethefollowing
DateTime.Now.ToString("MM/dd/yyyyhh:mm:ss.fff")
,anditworklikecharm.Note:that.fffaretheprecisionnumbersthatyouwishtocapture.
Share
Improvethisanswer
Follow
editedJun25,2017at23:42
Luis
5,58688goldbadges4141silverbadges6161bronzebadges
answeredJan5,2017at17:22
JozcarJozcar
91699silverbadges1111bronzebadges
1
1
Ifthedateisinafternoon(4PM)willshowsasinthemorning.FIX:UseHH(militarytime)oraddtt(PMorAM).Asshowninthisexample:repl.it/KGr3/1
– Jaider
Aug11,2017at22:12
Addacomment
|
22
UseDateTimeStructurewithmillisecondsandformatlikethis:
stringtimestamp=DateTime.UtcNow.ToString("yyyy-MM-ddHH:mm:ss.fff",
CultureInfo.InvariantCulture);
timestamp=timestamp.Replace("-",".");
Share
Improvethisanswer
Follow
answeredJan31,2018at19:23
JacmanJacman
1,34033goldbadges1818silverbadges3030bronzebadges
Addacomment
|
16
Pyromancer'sanswerseemsprettygoodtome,butmaybeyouwanted:
DateTime.Now.Millisecond
Butifyouarecomparingdates,TimeSpanisthewaytogo.
Share
Improvethisanswer
Follow
editedMay23,2017at10:31
CommunityBot
111silverbadge
answeredNov29,2013at0:15
RenaeRenae
42266silverbadges1515bronzebadges
1
16
Note:Ifyou'recomparingthedifferencebetweentwoDateTimesasaTimeSpan,youneedTotalMilliseconds.MillisecondsholdsthecurrentMillisecondscounter,whichisnevergreaterthan1000,whereasTotalMillisecondsholdsthetotalmillisecondselapsedsincetheepoch.
– Contango
Sep12,2014at11:48
Addacomment
|
4
Ifyoustillwantadateinsteadofastringliketheotheranswers,justaddthisextensionmethod.
publicstaticDateTimeToMillisecondPrecision(thisDateTimed){
returnnewDateTime(d.Year,d.Month,d.Day,d.Hour,d.Minute,
d.Second,d.Millisecond,d.Kind);
}
Share
Improvethisanswer
Follow
editedFeb16,2018at20:34
pirho
10.3k1212goldbadges4141silverbadges6060bronzebadges
answeredFeb16,2018at20:16
birchbirch
4122bronzebadges
Addacomment
|
3
AsfarasIunderstandthequestion,youcangofor:
DateTimedateTime=DateTime.Now;
DateTimedateTimeInMilliseconds=dateTime.AddTicks(-1*dateTime.Ticks%10000);
Thiswillcutofftickssmallerthan1millisecond.
Share
Improvethisanswer
Follow
editedDec14,2016at20:08
PeterMortensen
29.8k2121goldbadges9898silverbadges124124bronzebadges
answeredJul25,2016at16:39
RolandDietzRolandDietz
4933bronzebadges
1
Yes,buttheactualresolutionofDateTime.Nowmaynotbemorethanabout16ms.
– PeterMortensen
Dec14,2016at20:09
Addacomment
|
2
ThetroublewithDateTime.UtcNowandDateTime.Nowisthat,dependingonthecomputerandoperatingsystem,itmayonlybeaccuratetobetween10and15milliseconds.However,onwindowscomputersonecanusebyusingthelowlevelfunctionGetSystemTimePreciseAsFileTimetogetmicrosecondaccuracy,seethefunctionGetTimeStamp()below.
[System.Security.SuppressUnmanagedCodeSecurity,System.Runtime.InteropServices.DllImport("kernel32.dll")]
staticexternvoidGetSystemTimePreciseAsFileTime(outFileTimepFileTime);
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
publicstructFileTime{
publicconstlongFILETIME_TO_DATETIMETICKS=504911232000000000;//146097=daysin400yearGregoriancalendarcycle.504911232000000000=4*146097*86400*1E7
publicuintTimeLow;//leastsignificantdigits
publicuintTimeHigh;//mostsifnificantdigits
publiclongTimeStamp_FileTimeTicks{get{returnTimeHigh*4294967296+TimeLow;}}//tickssince1-Jan-1601(1tick=100nanosecs).4294967296=2^32
publicDateTimedateTime{get{returnnewDateTime(TimeStamp_FileTimeTicks+FILETIME_TO_DATETIMETICKS);}}
}
publicstaticDateTimeGetTimeStamp(){
FileTimeft;GetSystemTimePreciseAsFileTime(outft);
returnft.dateTime;
}
Share
Improvethisanswer
Follow
answeredApr30,2018at16:25
StochasticallyStochastically
7,41655goldbadges2929silverbadges5858bronzebadges
1
Thankyousomuch.I'vebeensearchingthissolong.Isitcauseanyperformanceissuesandisitsafetouseproductioncode?
– MuhammetGöktürkAyan
Aug28,2018at7:48
Addacomment
|
0
tryusingdatetime.now.ticks.thisprovidesnanosecondprecision.takingthedeltaoftwoticks(stoptick-starttick)/10,000isthemillisecondofspecifiedinterval.
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.ticks?view=netframework-4.7.2
Share
Improvethisanswer
Follow
answeredDec3,2018at15:42
darkstardarkstar
1111bronzebadge
Addacomment
|
0
AnotheroptionistoconstructanewDateTimeinstancefromthesourceDateTimevalue:
//currentdateandtime
varnow=DateTime.Now;
//modifieddateandtimewithmillisecondaccuracy
varmsec=newDateTime(now.Year,now.Month,now.Day,now.Hour,now.Minute,now.Second,now.Millisecond,now.Kind);
There'snoneedtodoanyto-stringandfrom-stringconversions,andit'salsoverywellunderstandableandreadablecode.
Share
Improvethisanswer
Follow
answeredApr8,2021at13:51
OndrejTucnyOndrejTucny
26.6k66goldbadges6666silverbadges8888bronzebadges
Addacomment
|
-2
publiclongmillis(){
return(long.MaxValue+DateTime.Now.ToBinary())/10000;
}
Ifyouwantmicroseconds,justchange10000to10,andifyouwantthe10thofmicro,delete/10000.
Share
Improvethisanswer
Follow
editedAug4,2017at15:40
TamásSengel
51.2k2727goldbadges152152silverbadges192192bronzebadges
answeredAug4,2017at13:00
distikingdistiking
733bronzebadges
Addacomment
|
-3
DateTime.Now.ToString("ddMMyyyyhhmmssffff")
Share
Improvethisanswer
Follow
answeredApr1,2014at8:38
amoljadhaoamoljadhao
11866bronzebadges
Addacomment
|
YourAnswer
ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers.
Draftsaved
Draftdiscarded
Signuporlogin
SignupusingGoogle
SignupusingFacebook
SignupusingEmailandPassword
Submit
Postasaguest
Name
Email
Required,butnevershown
PostYourAnswer
Discard
Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy
Nottheansweryou'relookingfor?Browseotherquestionstaggedc#datetimeprecisionmillisecondsoraskyourownquestion.
TheOverflowBlog
AIandnanotechnologyareworkingtogethertosolvereal-worldproblems
FeaturedonMeta
WhatgoesintositesponsorshipsonSE?
StackExchangeQ&AaccesswillnotberestrictedinRussia
Shouldweburninatethe[term]tag?
NewUserExperience:DeepDiveintoourResearchontheStagingGround–How...
AskWizardforNewUsersFeatureTestisnowLive
Visitchat
Linked
9
Any()methodonList
延伸文章資訊
- 1c# - How to format a string as a date with milliseconds - 1400+ ...
DateTime now = DateTime.Now; Label1.Text = "now: " + now.ToString(); //format date time with mill...
- 2C#的Datetime進DB少一毫秒之問題解決方式 ... - Coding Girl - Mia
C#的Datetime進DB少一毫秒之問題解決方式(C# Datetime into MSSQL DB lose one millisecond). 前言&解決方法: 將資料存進DB時發現毫秒數...
- 3C# DateTime Millisecond - Java2s.com
C# Tutorial - C# DateTime Millisecond. ... Description. DateTime Millisecond gets the millisecond...
- 4DateTime.AddMilliseconds() Method in C# - Tutorialspoint
- 5c# get datetime in milliseconds Code Example
c# get total milliseconds from datetime. csharp by Poor Pollan on Apr 27 2021 Comment ... C# answ...