Mystogan
Mystogan

Reputation: 21

How to get Date (yyyy/mm/dd) from ticks without using an instance/helper of/from Datetime C#

I'm trying to extract date from ticks.

Am I right that, a millisecond is 10000 ticks. and a day is 864000000000 ticks and a month is 26784000000000 and a year is 316224000000000.

but when I use these in computations, I get wrong date :(.

It could have been easy using Datetime parse but, for some reasons they say that I shouldn't rely on it as it is rather slower.

Would appreciate your help. Thank you.

UPDATE:

//assume this for now 
    DateTime time = DateTime.Now;
char[] ashigakaricom= new char[] { 'yyyy','-','mm','-','dd','-','H','H',':','M','M',':','S','S',':','m','m','m' }; 
long ticks = time.Ticks;
 int n1 = (int)(ticks >> 32);
 int n2 = (int)ticks;
 if (n2 < 0) 
n1++; 

ticks = (((Math.BigMul(429497, n2) - (int)(Math.BigMul(1161359156, n2) >> 32) - Math.BigMul(1161359156, n1)) >> 32)) + Math.BigMul(n1, 429497); n1 = (int)(ticks >> 32); 
n2 = (int)ticks; 


if (n2 < 0) 
n1++; 

int q = n1 * 50 + ((50 * (n2 >> 16)) >> 16) - (int)(System.Math.BigMul(1244382467, n1) >> 32) - 1; 

int r = (int)(ticks - System.Math.BigMul(q, 86400000)); 

if (r > 86400000) 
r -= 86400000; 



//so on

Upvotes: 1

Views: 641

Answers (4)

TomTom
TomTom

Reputation: 62101

and a month is 26784000000

Ah - sorry, what planet do you live oh? On mine (called "Earth") months have between 28 and 31 days, so they can not be standardized to a specific number of ticks.

The best you can come up with is IIRC

There is NO Way around a working calendar for what you try to achieve, which means a lot of mainteannce and overhead..5 hours average per month. Just use what .NET provides - this is a lot of work to duplicate with zero gain.

Upvotes: 1

shytikov
shytikov

Reputation: 9548

I have several ideas on this:

  • If you're missing correct year -- probably incorrect starting point for this ticks calculation was assumed. For C# it's not beginning of Unix epoch (1st January 1970), but "beginning of days" (1st January 0001);
  • Incorrect date, hour or minute -- this may something to do with leap year.

Upvotes: 0

OSH
OSH

Reputation: 2937

A millisecond may be any number of ticks (depending on what you use). regardless, even if you have the number of days since epoch (lets assume 1-1-1970), you will still have a hard time calculating the amount of days in each month (e.g. February).

Upvotes: 0

ductran
ductran

Reputation: 10203

Try this:

     TimeSpan elapsedSpan = new TimeSpan(10000);
 or: TimeSpan elapsedSpan = TimeSpan.FromTicks(10000);
 then use: elapsedSpan.Milliseconds, elapsedSpan.Days

Ref: http://msdn.microsoft.com/en-us/library/system.datetime.ticks.aspx

P/S: 316224000000000 ticks equal 366 days.

Upvotes: 0

Related Questions