Click here to Skip to main content
15,886,110 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
in javascrip

C#
var d = new Date();
var n = d.getTime();


how in c#?
Posted
Updated 16-Feb-23 15:33pm

The solution posted by OriginalGriff is good, except that the last line should use the TotalMilliseconds property, instead of Milliseconds:
C#
DateTime baseDate = new DateTime(1970, 1, 1);
TimeSpan diff = DateTime.Now - baseDate;
Console.WriteLine(diff.TotalMilliseconds);

The Milliseconds property just gives the milliseconds component of the TimeSpan (the amount left-over after totaling the number of years, days, hours, minutes and seconds), while TotalMilliseconds gives the total number of milliseconds represented by the value.
 
Share this answer
 
Comments
OriginalGriff 17-Aug-12 13:59pm    
I think you are right! 5!
Try:
C#
DateTime baseDate = new DateTime(1970, 1, 1);
TimeSpan diff = DateTime.Now - baseDate;
Console.WriteLine(diff.Milliseconds);
 
Share this answer
 
Comments
OriginalGriff 17-Aug-12 13:59pm    
See comment by BitThink in his solution
Hi, You can do like this....

var d = new Date("January 01, 1970");
var n = d.getMilliseconds();


C#

DateTime dt=Convert.ToDateTime("1970/01/01");

long k= dt.Ticks;
 
Share this answer
 
v2
var a = DateTime.Now;
var b = (DateTimeOffset)a;
va milliseconds = b.ToUnixTimeMilliseconds();
 
Share this answer
 
Comments
CHill60 17-Feb-23 5:18am    
This does not return the number of milliseconds since 1970/01/01
Richard Deeming 20-Feb-23 6:39am    
Actually it does:
DateTimeOffset.ToUnixTimeMilliseconds Method (System) | Microsoft Learn[^]
"Returns the number of milliseconds that have elapsed since 1970-01-01T00:00:00.000Z"

(Although DateTimeOffset.UtcNow would be better than (DateTimeOffset)DateTime.Now.)

It's just a shame this method wasn't supported until almost four years after the question was posted. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900