Happy Happy - 6 months ago 71
C# Question

How to store convert date time in int?

I need to store DateTime in int. So I tried below codes

Int64 n = Int64.Parse(DateTime.Today.ToString("dd-MM-yyyy"));


Int64 twoday_date=Convert.ToInt64(System.DateTime.Today.ToString("dd-MM-yyyy"));

but its showing error:

Input string was not in a correct format.

Where is the error?

Answer Source

Just use DateTime.Ticks instead - there's absolutely no reason to start converting to and from strings here.

long ticks = DateTime.Today.Ticks;

// Later in the code when you need a DateTime again
DateTime dateTime = new DateTime(ticks);

Note that this will use the local date - if you're trying to retain a global timestamp, you should use DateTime.UtcNow instead of DateTime.Today.

If you really need int instead of long, you probably ought to translate and scale, e.g. to seconds since the Unix epoch.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download