System.DateTime conversion

  • Thread starter Thread starter DWW
  • Start date Start date
D

DWW

System.DateTime returns a string with the date and time. I want to convert
the time to an integer, for example, convert 10:24:45 to 102445. Much
research has turned up a myriad of variations on formatting using Parse and
DateTimeFormatInfo, but nothing that returns the time as an integer. Any
ideas?

Thanks.

DW
 
DWW,

I don't think that this is the best way to get the time portion as an
integer. The reason being that you would have to convert it back to a
string before you wanted to convert it into a time span again.

Rather, I would do this:

static int TimeSpanToInt32(TimeSpan timeSpan)
{
// Get the return value, rounded down.
return (int) Math.Floor(timeSpan.TotalSeconds);
}

To convert back, you do this.

static TimeSpan Int32ToTimeSpan(int timeSpan)
{
// Convert to a timespan.
return TimeSpan.FromSeconds(timeSpan);
}

Note that there will be some loss in the conversion here.

If you really want to just create an integer based on that string, it's
going to be a little harder, since you can't specify the format of the
timespan when calling ToString (and it expects a set format when it is
passed back as well).

Hope this helps.
 
DWW,
The framework doesn't have any functions that return an integer formatted as
102445 per se.

What I do is write a simply function to convert the Date Time. Something
like:

DateTime dt = ...;
int hms = dt.Hour * 10000 + dt.Minute * 100 + dt.Second;

--
Hope this helps
Jay [MVP - Outlook]
..NET Application Architect, Enthusiast, & Evangelist
T.S. Bradley - http://www.tsbradley.net


| System.DateTime returns a string with the date and time. I want to
convert
| the time to an integer, for example, convert 10:24:45 to 102445. Much
| research has turned up a myriad of variations on formatting using Parse
and
| DateTimeFormatInfo, but nothing that returns the time as an integer. Any
| ideas?
|
| Thanks.
|
| DW
|
|
 
Thanks, Jay. Shortly after I posted this, I figured it out and I did it the
way you present below. Unfortunately, MS's documentation is a little spare
on this issue, but it works. (My implementation multiplies the
DateTime.Hour by 100 and adds DateTime.Minute.)

Thanks.

DW
 
DWW said:
Thanks, Jay. Shortly after I posted this, I figured it out and I did it the
way you present below. Unfortunately, MS's documentation is a little spare
on this issue, but it works. (My implementation multiplies the
DateTime.Hour by 100 and adds DateTime.Minute.)

What do you want to be documented which isn't, out of interest? If you
look for custom date and time format strings, you should find enough
information - I've never found it to be a problem.
 
Back
Top