Ivan-Mark Debono
Ivan-Mark Debono

Reputation: 16340

How to convert an int to a datetime?

I have a date that is converted to int using the following formula:

var i = date.Year * 65536 + date.Month * 256 + date.Day;

How do I convert the int back to the date?

Upvotes: 0

Views: 785

Answers (2)

Sweeper
Sweeper

Reputation: 274470

That seems like you are using different bits of an int to store the date. The most significant 16 bits are the year. The 8 bits after that is the month, and the least significant 8 bits are the day.

You can therefore use bitwise operations to get the year, month and day:

uint unsigned = (uint)i; // cast to uint because we don't want to do an arithmetic shift
uint year = unsigned >> 16;
uint month = (unsigned >> 8) & 0xff;
uint day = unsigned & 0xff;

In fact, i can also be calculated using bitwise operations:

var i = date.Year << 16 | date.Month << 8 | date.Day;

Upvotes: 5

Alex Netkachov
Alex Netkachov

Reputation: 13562

This formula writes day, month and year in first, second and third bytes of int. So you basically just need to take these bytes and create DateTime from them:

var date = DateTime.Now;
var i = date.Year * 65536 + date.Month * 256 + date.Day;
var dt = new DateTime(i >> 16, i >> 8 & 0xFF, i & 0xFF);

Upvotes: 2

Related Questions