سؤال

If I did this

// Default implementation of UNIX time of the current UTC time
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
string myResult = "";
myResult = Convert.ToInt64(ts.TotalSeconds).ToString();

What is the maximum string length of myResult and is it always the same size?

هل كانت مفيدة؟

المحلول

An Int64 is a signed 64-bit integer, which means it has a range of values from −9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

Since toString doesn't format its output with commas, the longest possible value of the string would be −9223372036854775808 which is 20 characters long.

Now, since this is representing a UNIX timestamp we need to take into consideration what would be considered a "reasonable" date to return. As I write this, a current UNIX timestamp would be something close to 1292051460, which is a 10-digit number.

Assuming a maximum length of 10 characters gives you a range of timestamps from -99999999 to 9999999999. This gives you a range of dates from "Mon, 31 Oct 1966 14:13:21 GMT" to "Sat, 20 Nov 2286 17:46:39 GMT". Note that I'm including the negation symbol as a character in the lower bound, which is why the lower bound is so much closer to the epoch than the upper bound.

If you're not expecting dates before Halloween 1966 or after late November 2286, you can reasonably assume that the length of the string won't exceed 10 characters. If you are expecting dates outside of this range (most likely pre-1966 rather than post-2286), you can expect to see an 11 character string. I wouldn't expect any more than that.

That's the maximum number of characters to expect; it could be shorter.

نصائح أخرى

Assuming the code is used far into the future it would be the maximum length of an Int64.

For example, right now that value is 1292022273 so the length would be 10.

You can find a calculator that includes the seconds here http://www.timeanddate.com/date/duration.html

If you stick with Convert.ToInt64() with no formatting, then your maximum length will be 20, because the minimum Int64 is -9223372036854775808 (the negative sign requires an extra character). In practice, however, it will not utilize the entire range afforded by Int64 due to limitations in TimeSpan and DateTime.

And, no, the length of myResult will not always be the same, but can range from 1 to 20. It just depends on the current value of Convert.ToInt64(ts.TotalSeconds).

To get max size of the TimeSpan try to use this code:

var maxValue = Convert.ToInt64(TimeSpan.MaxValue).ToString();

Hope it will help you with your question! Good luck!

Best regards, Dima.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top