JavaScript How to format time in JavaScript, without a framework [duplicate] format time javascript moment,format time javascript,format time javascript

This is a common problem but I'm not sure how to solve it. The code below works fine.

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?

Thanks

Answer:1

Another fancy solution:

function fancyTimeFormat(time)
{   
    // Hours, minutes and seconds
    var hrs = ~~(time / 3600);
    var mins = ~~((time % 3600) / 60);
    var secs = ~~time % 60;

    // Output like "1:01" or "4:03:59" or "123:03:59"
    var ret = "";

    if (hrs > 0) {
        ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
    }

    ret += "" + mins + ":" + (secs < 10 ? "0" : "");
    ret += "" + secs;
    return ret;
}

~~ is a shorthand for Math.floor, see this link for more info

Try online

Answer:2

You can also use native Date object:

var date = new Date(null);
date.setSeconds(timeInSeconds);

// retrieve time ignoring the browser timezone - returns hh:mm:ss
var utc = date.toUTCString();
// negative start index in substr does not work in IE 8 and earlier
var time = utc.substr(utc.indexOf(':') - 2, 8)

// retrieve each value individually - returns h:m:s
var time = date.getUTCHours() + ':' + date.getUTCMinutes() + ':' +  date.getUTCSeconds();

// does not work in IE8 and below - returns hh:mm:ss
var time = date.toISOString().substr(11, 8);

// not recommended - only if seconds number includes timezone difference
var time = date.toTimeString().substr(0, 8);

Of course this solution works only for timeInSeconds less than 24 hours ;)

Answer:3

To add leading zeros, I would just do:

var minutes = "0" + Math.floor(time / 60);
var seconds = "0" + (time - minutes * 60);
return minutes.substr(-2) + ":" + seconds.substr(-2);

Nice and short

Answer:4

Clean one liner using ES6


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

Answer:5

A one liner (doesnt work with hours):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }
Answer:6

Seconds to h:mm:ss

var hours = Math.floor(time / 3600);
time -= hours * 3600;

var minutes = Math.floor(time / 60);
time -= minutes * 60;

var seconds = parseInt(time % 60, 10);

console.log(hours + ':' + (minutes < 10 ? '0' + minutes : minutes) + ':' + (seconds < 10 ? '0' + seconds : seconds));
Answer:7

After all this, yet another simple solution:

const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());
Answer:8

The Following function will help you to get Days , Hours , Minutes , seconds

toDDHHMMSS(inputSeconds){
        const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
        const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
        const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
        const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
        let ddhhmmss  = '';
        if (Days > 0){
            ddhhmmss += Days + ' Day ';
        }
        if (Hour > 0){
            ddhhmmss += Hour + ' Hour ';
        }

        if (Minutes > 0){
            ddhhmmss += Minutes + ' Minutes ';
        }

        if (Seconds > 0){
            ddhhmmss += Seconds + ' Seconds ';
        }
        return ddhhmmss;
    }
alert( toDDHHMMSS(2000));
Answer:9

For adding zeros I really don't see the need to have a full other function where you can simply use for example

var mins=Math.floor(StrTime/60);
var secs=StrTime-mins * 60;
var hrs=Math.floor(StrTime / 3600);
RoundTime.innerHTML=(hrs>9?hrs:"0"+hrs) + ":" + (mins>9?mins:"0"+mins) + ":" + (secs>9?secs:"0"+secs);

Its why we have conditional statements in the first place.

(condition?if true:if false) so if example seconds is more than 9 than just show seconds else add a string 0 before it.

Answer:10

try this : Converting Second to HOURS, MIN and SEC.

function convertTime(sec) {
    var hours = Math.floor(sec/3600);
    (hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
    var min = Math.floor(sec/60);
    (min >= 1) ? sec = sec - (min*60) : min = '00';
    (sec < 1) ? sec='00' : void 0;

    (min.toString().length == 1) ? min = '0'+min : void 0;    
    (sec.toString().length == 1) ? sec = '0'+sec : void 0;    

    return hours+':'+min+':'+sec;
}
Answer:11

var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
  <label for="course" class="col-md-4">Time</label>
  <div class="col-md-8">
    <input type="text" class="form-control" id="id1" name="field">Min
  </div>
</div>
Answer:12

You've done enough code to track minutes and seconds portions of time.

What you could do is add the hours factor in:

var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);

var mind = hrd % 60;
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

var moreminutes = minutes + hours * 60

This would give you what you need also.

Answer:13

I was thinking of a faster way to get this done and this is what i came up with

var sec = parseInt(time);
var min=0;
while(sec>59){ sec-=60; min++;}

If we want to convert "time" to minutes and seconds, for example:

// time = 75,3 sec
var sec = parseInt(time); //sec = 75
var min=0;
while(sec>59){ sec-=60; min++;} //sec = 15; min = 1
Answer:14

I suggest another solution:

function formatTime(nbSeconds, hasHours) {
    var time = [],
        s = 1;
    var calc = nbSeconds;

    if (hasHours) {
        s = 3600;
        calc = calc / s;
        time.push(format(Math.floor(calc)));//hour
    }

    calc = ((calc - (time[time.length-1] || 0)) * s) / 60;
    time.push(format(Math.floor(calc)));//minute

    calc = (calc - (time[time.length-1])) * 60;
    time.push(format(Math.round(calc)));//second


    function format(n) {//it makes "0X"/"00"/"XX"
        return (("" + n) / 10).toFixed(1).replace(".", "");
    }

    //if (!hasHours) time.shift();//you can set only "min: sec"

    return time.join(":");
};
console.log(formatTime(3500));//58:20
console.log(formatTime(305));//05:05
console.log(formatTime(75609, true));//21:00:09
console.log(formatTime(0, true));//00:00:00
Answer:15

I know it has been solved in many ways. I needed this function for an After Effects script, where speed or namespace pollution is not an issue. I drop it here for someone that needs something similar. I also wrote some tests and worked fine. So here's the code:

Number.prototype.asTime = function () {
    var hour = Math.floor(this / 3600),
        min = Math.floor((this - hour * 3600) / 60),
        sec = this - hour * 3600 - min * 60,
        hourStr, minStr, secStr;
    if(hour){
        hourStr = hour.toString(),
        minStr = min < 9 ? "0" + min.toString() : min.toString();
        secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
        return hourStr + ":" + minStr + ":" + secStr + "hrs";
    }
    if(min){
        minStr = min.toString();
        secStr = sec < 9 ? "0" + sec.toString() : sec.toString();
        return  minStr + ":" + secStr + "min";
    }
    return sec.toString() + "sec";
}
Answer:16

Put my two cents in :

function convertSecondsToMinutesAndSeconds(seconds){
            var minutes;
            var seconds;
            minutes = Math.floor(seconds/60);
            seconds = seconds%60;

            return [minutes, seconds];
        }

So this :

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);

Will have the following output :

[1,41];

Then you can print it like so :

console.log('TIME : ' +  minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');

//TIME : 1 minutes, 41 seconds
Answer:17

strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.

When creating a new Date, each optional argument is positional as follows:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

In one line, it would look like:

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:

# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"

# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"

And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.

var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"

Hope this helps.

Answer:18

I have data from the server to display. I receive strings such as this: 2016-05-01. I need to filter the data between two dates in that format. I have a function to parse the date as it is: $scope....

I have data from the server to display. I receive strings such as this: 2016-05-01. I need to filter the data between two dates in that format. I have a function to parse the date as it is: $scope....

  1. parse string into array
  2. parse string into int
  3. parse string into json
  4. parse string into list python
  5. parse string into int java
  6. parse string into json java
  7. parse string into array python
  8. parse string into datetime python
  9. parse string into object javascript
  10. parse string into date
  11. parse string into double java
  12. parse string into list
  13. parse string into int python
  14. parse string into array java
  15. parse string into datetime c#
  16. parse string into words c++
  17. parse string into object java
  18. parse string into int c#
  19. parse string into vector c++
  20. parse string into json python

I'm trying to add the value of the checkbox in the field the is closest to it. But I think I missed something. Please see my code below: $(document).ready(function(){ $("input:checkbox")....

I'm trying to add the value of the checkbox in the field the is closest to it. But I think I missed something. Please see my code below: $(document).ready(function(){ $("input:checkbox")....

  1. pass input checkbox value to controller

I am using a <asp:FileUpload> to upload a PDF file to my web page. But after clicking on browse the window opens, and once I select a file and click on Open i want to get the file name and ...

I am using a <asp:FileUpload> to upload a PDF file to my web page. But after clicking on browse the window opens, and once I select a file and click on Open i want to get the file name and ...

  1. file name from path
  2. file name from path python
  3. file name from path c#
  4. file name from file descriptor
  5. file name from user input java
  6. file name from path java
  7. file name from folder to excel
  8. file name from url
  9. file name from uri android
  10. file name from path bash
  11. file name from path php
  12. file name from url php
  13. file name from path vba
  14. file name from url swift
  15. file name from path ruby
  16. file name from trigger
  17. file name from path shell
  18. filename from file path
  19. file name from url python
  20. file name from file object python

I am trying to test a method using Jest... The method should return Promise.reject() . Here is the code I wrote: test('testing Invalid Response Type', () => { const client = new ...

I am trying to test a method using Jest... The method should return Promise.reject() . Here is the code I wrote: test('testing Invalid Response Type', () => { const client = new ...