Reputation: 25
I am working on a music application. If a music file has been added then I should get the duration (which is in milliseconds) and convert the duration into minutes.
var d = new Date(ms);
var hms = d.getMinutes().toString() +':'+ d.getSeconds().toString();
If I am providing ms = 331807;
expected answer is = 11:42
but the result is = 41:02
I am unable to figure out the problem. Can anyone please help me find the solution?
Upvotes: 0
Views: 55
Reputation: 241858
The Date
object expects milliseconds since Jan 1, 1970 UTC. However, the getMinutes
and getSeconds
functions will be output relative to the time zone that the code is running in.
If you want to use the Date
object for this, you should use the getUTCMinutes
and getUTCSeconds
instead.
However, as others pointed out, this isn't the best use case for the Date
object. You can do simple math to convert milliseconds to minutes and seconds.
Upvotes: 2
Reputation: 19802
The Date
constructor instantiates a new object with an optional argument passed to it. Passing an amount of milliseconds to it gives you a new Date
object, which is a date and time since the epoch, relative to the number of milliseconds you passed to it. getMinutes
probably gave you 42, because the time you passed to the Date
constructor was at the 42nd minute of whatever date was constructed.
You can convert milliseconds to minutes with simple multiplication.
numberOfMilliseconds / (1000*60)
Upvotes: 1