Posted by: R Manimaran | January 27, 2011

Convert DateTime to Ticks and Ticks to DateTime in .net (C#)

I have got a requirement to convert the DateTime to Ticks and Ticks to DateTime. Here is the function which may be useful to somebody In C#, the DateTime.Ticks property simply returns a long, that represents the amount of ticks (100-nanosecond interval) that have passed since january 1, 0001 12:00:00.

class Program 
{ 
  static void Main(string[] args) 
 {
     //Call func to convert DateTime to Ticks 
     long ticks = ConvertDateTimeToTicks(DateTime.Now); 
     Console.WriteLine(ticks.ToString()); 
    //Call fun to convert Ticks to DateTime 
    DateTime dt = ConvertTicksToDateTime(ticks); 
    Console.WriteLine(dt.ToString()); 
    Console.Read(); 
  } 

  public static long ConvertDateTimeToTicks( DateTime dtInput) 
  {
      long ticks = 0; 
      ticks=dtInput.Ticks; 
      return ticks; 
  } 
  public static DateTime ConvertTicksToDateTime( long lticks) 
  { 
     DateTime dtresult = new DateTime(lticks); 
     return dtresult; 
  }

 }
About these ads

Responses

  1. Got a related question which I recently faced. I got a Java Date object (an expiry time actually) on the server side which is converted to ticks and given to client and vc++ client has to convert the tick to a date/time and check for the current time and do action based on that.

    But java epoch is on 1970 and ticks are in terms of milli seconds (that can be converted to nano-sec) but windows epoch is 1600 or 0001. I couldn’t get over this. Got any idea?

    I did solved in a round about way, along with time I sent ttl (TimeToLive) so that all the time calculation is done in server itself. Though this solves the problem, IMO this is not clean.

  2. Thnx,its works for me,actually i was concantenating ticks with filenames & it works.

    Nice !!!

  3. Wow, this piece of writing is good, my younger sister is analyzing such things, so I am going
    to convey her.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

Follow

Get every new post delivered to your Inbox.

Join 25 other followers

%d bloggers like this: