简体   繁体   中英

Convert DateTime to String value?

How do I convert DateTime to an Integer value?

Edit: How do I convert DateTime to a String value?

Example

String return value of 20100626144707 (for 26th of June 2010, at 14:47:07)

That could not be represented as an integer, it would overflow. It can be a long, however.

DateTime dateTime = new DateTime(2010, 6, 26, 14, 44, 07);
long time = long.Parse(dateTime.ToString("yyyyMMddHHmmss"));

However, it would be more intuitive to simply express it as a string, but I don't know what you intend to do with the information.

Edit:

Since you've updated the question, the answer is simpler.

string time = dateTime.ToString("yyyyMMddHHmmss");

A 32-bit integer is not large enough to hold a DateTime value to a very precise resolution. The Ticks property is a long (Int64). If you don't need precision down to the tick level, you could get something like seconds since the epoch:

TimeSpan t = (DateTime.UtcNow - new DateTime(1970, 1, 1));
int dateAsInteger  = (int)t.TotalSeconds;

It's generally a bad idea to use a numeric datatype to store a number you can't do arithmetic on. Eg the number in your example has no numeric meaning or value, adding it or subtracting it is pointless. However, the number of seconds since a certain date is useful as a numeric data type.

Note: this was posted before the question was changed to "string value" rather than "integer value".

Essentially, you want to shift the number along by the number of places needed for each part and then add it:

var x = new DateTime(2010,06,26,14,47,07);

long i = x.Year;
i = i * 100 + x.Month;
i = i * 100 + x.Day;
i = i * 100 + x.Hour;
i = i * 100 + x.Minute;
i = i * 100 + x.Second;

Console.WriteLine(i); // 20100626144707

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM