Marcelo Camargo
Marcelo Camargo

Reputation: 2298

Convert seconds to Day, Hour, Minute and Second

I'm trying to convert a certain value of seconds to the following format, using F#:

00d 00h 00m 00s

And I'm sure I'm doing the correct calc but it also gives me wrong minutes. My code is the following:

let sum = 266521
let day = sum / 86400
let leftover = sum % 86400

let hour = leftover / 3600
leftover = leftover % 3600

let minute = leftover / 60
leftover = leftover % 60

86400 -> Seconds in a day
3600 -> Seconds in an hour
60 -> Seconds in a minute.

I'm trying to do this greedy calc, but it gives me the values: 3d 2h 122m 7321s

But it can't be 122m, it should be in hour. I don't understand where is my error. Can you help me? Thanks in advance

Upvotes: 2

Views: 415

Answers (3)

Mark Seemann
Mark Seemann

Reputation: 233197

How about just leveraging the built-in functionality?

> open System;;
> let secs = 266521;;

val secs : int = 266521

> let s = (TimeSpan.FromSeconds (float secs)).ToString "d\d\ hh\h\ mm\m\ ss\s";;

val s : string = "3d 02h 02m 01s"

Upvotes: 9

John Reynolds
John Reynolds

Reputation: 5057

The line

leftover = leftover % 3600

is a boolean expression that compares leftover to leftover % 3600 (which probably evaluates to false). What you need to do, is to assign a new value,

let leftover' = leftover % 3600

and then use leftover' subsequently.

Upvotes: 0

Lukos
Lukos

Reputation: 1852

It's because the values are immutable (cannot change) in F#. Your value "leftover" stays at the value 7321, its first value. This is done to help with threading and data sharing. Either create a new value when changing the value of "leftover" or otherwise make the value mutable:

let mutable leftover = sum % 86400
leftover <- leftover % 3600

Upvotes: 2

Related Questions