peter
peter

Reputation: 69

Convert from float to TimeSpan

I need to convert a float number to datetime. For example:

float x=70;

DateTime should return 1 minute and 10 seconds. (1:30)

Upvotes: 3

Views: 8290

Answers (1)

jeanfrg
jeanfrg

Reputation: 2351

You can use TimeSpan to represent a float in time. Keep in mind TimeSpan does not accept float parameters so you'll need to cast to a double type.

float x = 70;
TimeSpan span = TimeSpan.FromSeconds((double)(new decimal(x)));

Then use a reference DateTime to "convert" TimeSpan to DateTime. In this example we're using epoch.

DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime date = epoch + span;

Date would represent the number of seconds (your float) from epoch.

Note: epoch (Unix time) can be any date (change as needed)

Demo: http://rextester.com/QCK29438

Upvotes: 10

Related Questions