Get the local time in javascript with zeros?

Asked

Viewed 3,314 times

4

I’m trying to get local time and minute in javascript.

The first way I tried was this:

date = new Date;
date.getHours() + ':' + date.getMinutes() // 10:5

But for the time of 10 hours and 05 minutes, he returned 10:5 instead of 10:05.

Then I left for second try:

(new Date).toLocaleString().substr(11, 5) // 10:06

Only my concern is whether the size of this string returned by toLocaleString will vary according to region!

The way I’m getting hours minutes, in the format hh:mm, is fine?

Or is there some more effective way, in javascript, to get them in this format (with zeros filled) ?

6 answers

4


I usually use a simple function to join the 0:

function pad(s) {
    return (s < 10) ? '0' + s : s;
}

That way you don’t have to use the toLocaleString() which is still poorly supported.

So I’d do something like:

function novaHora() {
    function pad(s) {
        return (s < 10) ? '0' + s : s;
    }
    var date = new Date();
    return [date.getHours(), date.getMinutes()].map(pad).join(':');
}

and then calling the function gives the hour and minutes in the format hh:mm.

novaHora()
// "15:20"

jsFiddle: http://jsfiddle.net/jtr6062n/

  • 1

    Valid and organized. I liked the solution

1

Determining the output object (output) of the function

<div id="hora"></div>

Javascript to display the time

<script>
function pad(s) { /* Completa com zeros numeros com 1 digito */
    return (s < 10) ? '0' + s : s;
}

function newData(){ /* Obter a hora e aplica ao objeto*/
 var date = new Date();
 hora.innerHTML=[date.getHours(), date.getMinutes(),date.getSeconds()].map(pad).join(':');
}

setInterval(function(){ /* Atualizar a hora em tempo real */
newData();
},500);

/* Caso não queria exibir sendo atualizando no lugar do metodo setInterval apenas instancie  a função newData();*/
</script>

See the example here http://jsfiddle.net/405c7u63/

  • The exit will look like this HH:MM:SS.

  • Although the exit was not as expected, I found a cool solution!

1

Using this plugin is very simple:

/*! jquery-dateFormat 05-10-2014 */
var DateFormat={};!function(a){var b=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],c=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],e=["January","February","March","April","May","June","July","August","September","October","November","December"],f={Jan:"01",Feb:"02",Mar:"03",Apr:"04",May:"05",Jun:"06",Jul:"07",Aug:"08",Sep:"09",Oct:"10",Nov:"11",Dec:"12"},g=/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.?\d{0,3}[Z\-+]?(\d{2}:?\d{2})?/;a.format=function(){function a(a){return b[parseInt(a,10)]||a}function h(a){return c[parseInt(a,10)]||a}function i(a){var b=parseInt(a,10)-1;return d[b]||a}function j(a){var b=parseInt(a,10)-1;return e[b]||a}function k(a){return f[a]||a}function l(a){var b,c,d,e,f,g=a,h="";return-1!==g.indexOf(".")&&(e=g.split("."),g=e[0],h=e[1]),f=g.split(":"),3===f.length?(b=f[0],c=f[1],d=f[2].replace(/\s.+/,"").replace(/[a-z]/gi,""),g=g.replace(/\s.+/,"").replace(/[a-z]/gi,""),{time:g,hour:b,minute:c,second:d,millis:h}):{time:"",hour:"",minute:"",second:"",millis:""}}function m(a,b){for(var c=b-String(a).length,d=0;c>d;d++)a="0"+a;return a}return{parseDate:function(a){var b={date:null,year:null,month:null,dayOfMonth:null,dayOfWeek:null,time:null};if("number"==typeof a)return this.parseDate(new Date(a));if("function"==typeof a.getFullYear)b.year=String(a.getFullYear()),b.month=String(a.getMonth()+1),b.dayOfMonth=String(a.getDate()),b.time=l(a.toTimeString()+"."+a.getMilliseconds());else if(-1!=a.search(g))values=a.split(/[T\+-]/),b.year=values[0],b.month=values[1],b.dayOfMonth=values[2],b.time=l(values[3].split(".")[0]);else switch(values=a.split(" "),6===values.length&&isNaN(values[5])&&(values[values.length]="()"),values.length){case 6:b.year=values[5],b.month=k(values[1]),b.dayOfMonth=values[2],b.time=l(values[3]);break;case 2:subValues=values[0].split("-"),b.year=subValues[0],b.month=subValues[1],b.dayOfMonth=subValues[2],b.time=l(values[1]);break;case 7:case 9:case 10:b.year=values[3],b.month=k(values[1]),b.dayOfMonth=values[2],b.time=l(values[4]);break;case 1:subValues=values[0].split(""),b.year=subValues[0]+subValues[1]+subValues[2]+subValues[3],b.month=subValues[5]+subValues[6],b.dayOfMonth=subValues[8]+subValues[9],b.time=l(subValues[13]+subValues[14]+subValues[15]+subValues[16]+subValues[17]+subValues[18]+subValues[19]+subValues[20]);break;default:return null}return b.date=new Date(b.year,b.month-1,b.dayOfMonth),b.dayOfWeek=String(b.date.getDay()),b},date:function(b,c){try{var d=this.parseDate(b);if(null===d)return b;for(var e=(d.date,d.year),f=d.month,g=d.dayOfMonth,k=d.dayOfWeek,l=d.time,n="",o="",p="",q=!1,r=0;r<c.length;r++){var s=c.charAt(r),t=c.charAt(r+1);if(q)"'"==s?(o+=""===n?"'":n,n="",q=!1):n+=s;else switch(n+=s,p="",n){case"ddd":o+=a(k),n="";break;case"dd":if("d"===t)break;o+=m(g,2),n="";break;case"d":if("d"===t)break;o+=parseInt(g,10),n="";break;case"D":g=1==g||21==g||31==g?parseInt(g,10)+"st":2==g||22==g?parseInt(g,10)+"nd":3==g||23==g?parseInt(g,10)+"rd":parseInt(g,10)+"th",o+=g,n="";break;case"MMMM":o+=j(f),n="";break;case"MMM":if("M"===t)break;o+=i(f),n="";break;case"MM":if("M"===t)break;o+=m(f,2),n="";break;case"M":if("M"===t)break;o+=parseInt(f,10),n="";break;case"y":case"yyy":if("y"===t)break;o+=n,n="";break;case"yy":if("y"===t)break;o+=String(e).slice(-2),n="";break;case"yyyy":o+=e,n="";break;case"HH":o+=m(l.hour,2),n="";break;case"H":if("H"===t)break;o+=parseInt(l.hour,10),n="";break;case"hh":hour=0===parseInt(l.hour,10)?12:l.hour<13?l.hour:l.hour-12,o+=m(hour,2),n="";break;case"h":if("h"===t)break;hour=0===parseInt(l.hour,10)?12:l.hour<13?l.hour:l.hour-12,o+=parseInt(hour,10),n="";break;case"mm":o+=m(l.minute,2),n="";break;case"m":if("m"===t)break;o+=l.minute,n="";break;case"ss":o+=m(l.second.substring(0,2),2),n="";break;case"s":if("s"===t)break;o+=l.second,n="";break;case"S":case"SS":if("S"===t)break;o+=n,n="";break;case"SSS":o+=l.millis.substring(0,3),n="";break;case"a":o+=l.hour>=12?"PM":"AM",n="";break;case"p":o+=l.hour>=12?"p.m.":"a.m.",n="";break;case"E":o+=h(k),n="";break;case"'":n="",q=!0;break;default:o+=s,n=""}}return o+=p}catch(u){return console&&console.log&&console.log(u),b}},prettyDate:function(a){var b,c,d;return("string"==typeof a||"number"==typeof a)&&(b=new Date(a)),"object"==typeof a&&(b=new Date(a.toString())),c=((new Date).getTime()-b.getTime())/1e3,d=Math.floor(c/86400),isNaN(d)||0>d?void 0:60>c?"just now":120>c?"1 minute ago":3600>c?Math.floor(c/60)+" minutes ago":7200>c?"1 hour ago":86400>c?Math.floor(c/3600)+" hours ago":1===d?"Yesterday":7>d?d+" days ago":31>d?Math.ceil(d/7)+" weeks ago":d>=31?"more than 5 weeks ago":void 0},toBrowserTimeZone:function(a,b){return this.date(new Date(a),b||"MM/dd/yyyy HH:mm:ss")}}}()}(DateFormat),function(a){a.format=DateFormat.format}(jQuery);

Utilizing:

ObtenhaDataHoraAtual : function() {
    var currentdate = new Date();
    return $.format.date(currentdate, "dd/MM/yyyy HH:mm:ss");
},

FormateDataParaDiaMesAno: function(date) {
    return $.format.date(date, "dd/MM/yyyy");
},

ObtenhaDataHoraAtualSemSegundos: function () {

    var currentdate = new Date();
    return $.format.date(currentdate, "dd/MM/yyyy HH:mm");
},

 ObtenhaDataHoraMinutoSegundoAtual: function () {

    var currentdate = new Date();
    return $.format.date(currentdate, "dd/MM/yyyy HH:mm:ss");
}
  • +1 Although it is a lot of code, I understand that this serves to format the date anyway (and not only what I need)

  • Thanks, I wanted to exemplify that with the use of the plugin any situation with dates becomes simple to solve. I am editing to remove the validations (it is out of the context of the question).

1

One option is to use method String.prototype.padStart to handle from scratch to left (but for that you need to turn the values into string first):

function format(val) {
    return val.toString().padStart(2, '0');
}

let date = new Date('2021-04-07T01:10:30');
// 01:10
console.log(`${format(date.getHours())}:${format(date.getMinutes())}`);


Another option is to use the method Date.prototype.toLocaleTimeString. About your concern:

string returned by toLocaleString will vary by region

Just make explicit which is the locale, so it does not vary according to the region:

let date = new Date('2021-04-07T01:10:30');
// 01:10
console.log(date.toLocaleTimeString('pt-BR', { hour: '2-digit', minute: '2-digit' }));

Using the locale 'en', the locale will no longer vary (with caveats, read more below). And using the options hour: '2-digit', minute: '2-digit', it shows only the hours and minutes, already formatted with zero left if needed (so you don’t need to use substr to pick up pieces of the string).


One is that not always the locale may be available. For example, in Node < 13, only came with the locale en-US (then when using pt-BR, was made the fallback for en-US). And then just add hour12: false options, as in locale en-US it also shows the AM/PM identifier (and hour12: false disables this).

Another is that if the code runs in an environment in which the locale pt-BR is not available and the default locale is other than en-US, may need other adjustments to the options (for example, if the default locale is from Arab countries, it may be that the numbers are displayed differently).

In these cases, building the string manually may be the best option. Unless you really want a localized format instead of a fixed one - that is, in the end it’s a semantic decision: you always want to HH:MM, or want a localized format that shows only hours and minutes? (sometimes it will be the same thing, sometimes not).

1

Make it simple use native method Date.prototype.toLocaleTimeString() passing as parameter the location, in the example I used en, and an object containing the configuration options method. As options use:

  • timeStyle: "short", indicates that the result will be returned only in hours and minutes.
  • hour12: false, indicates that the location-independent result will delete suffixes AM and PM and the delivered time will be 24 hours.
  • numberingSystem: "latn" , indicates that the location-independent result will be delivered in Indo-Arabic numerals.

let date = new Date();

let time = date.toLocaleTimeString("pt-BR", {
  timeStyle: "short",       //Serão retornado apenas horas e minutos.  
  hour12: false,            //Formato de 24h, suprimindo sufixos AM e PM.
  numberingSystem: "latn"   //Resulado em algarismos indo-arábicos.
});

console.log(time);

Example 2:

let date = new Date('December 17, 1995 03:04:30');

function shortTime(locale, time){
  return time.toLocaleTimeString(locale, {
    timeStyle: "short",         
    hour12: false,            
    numberingSystem: "latn"   
  });
}

console.log(shortTime('en-US', date));
console.log(shortTime('ko-KR', date));
console.log(shortTime('ar-EG', date));

  • 1

    Only one detail: depending on the environment, not always numberingSystem: "latn" and timeStyle is enough (I suspect that in some implementations the locale ends up taking precedence), see how different implementations give different results: https://ideone.com/Y8iWv7 | https://ideone.com/hEWhIC | https://ideone.com/nOoIVA | https://replit.com/@hkotsubo/Judiciousmotionlesssales#index.js - anyway, +1 for giving an option that nobody had remembered (I also added this with another alternative in my answer :-)

-3

Rogerio is on the right track, but it’s not the way I’d do it, I prefer it this way:

function format(s) {
    return (s < 10) ? '0' + s : s;
}

function newData(){
 var date = new Date();
 return date.getHours() + ':' + format(date.getMinutes()) + ':' + format(date.getSeconds());
}

setInterval(function(){
//document.querySelector('#clock').text = newData();
$('#clock').text(newData());
},500);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="clock"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.