简体   繁体   English

getMinutes() 0-9 - 如何显示两位数?

[英]getMinutes() 0-9 - How to display two digit numbers?

var date = "2012-01-18T16:03";
var date = new Date(date);

console.log(date.getMinutes());
console.log(date.getMinutes().length)

This returns 3.这将返回 3。

  1. How do I make it return '03'?我如何让它返回'03'?
  2. Why does .length return undefinded?为什么.length返回未定义?

I tried this, but it did not work:我试过这个,但没有用:

If strlen == 1 then num = ('0' + num);如果strlen == 1num = ('0' + num);

var date = new Date("2012-01-18T16:03");

console.log( (date.getMinutes()<10?'0':'') + date.getMinutes() );

Yikes these answers aren't great, even the top post upticked.哎呀,这些答案都不是很好,即使是最高职位也有所上升。 Here y'go, cross-browser and cleaner int/string conversion.在这里,跨浏览器和更清晰的 int/string 转换。 Plus my advice is don't use a variable name 'date' with code like date = Date(...) where you're relying heavily on language case sensitivity (it works, but risky when you're working with server/browser code in different languages with different rules).另外我的建议是不要将变量名称“日期”与诸如date = Date(...)类的代码一起使用,在这种情况下,您严重依赖语言区分大小写(它有效,但在使用服务器/浏览器时存在风险)不同语言的代码,具有不同的规则)。 So assuming the javascript Date in a var current_date :因此,假设 var current_date的 javascript 日期:

mins = ('0'+current_date.getMinutes()).slice(-2);

The technique is take the rightmost 2 characters (slice(-2)) of "0" prepended onto the string value of getMinutes() .该技术是将“0”的最右边的 2 个字符(slice(-2))添加到getMinutes()的字符串值上。 So:所以:

"0"+"12" -> "012".slice(-2) -> "12"

and

"0"+"1" -> "01".slice(-2) -> "01"

Another short way is to fill the minutes with a leading zero using:另一种简短的方法是使用前导零填充分钟:

String(date.getMinutes()).padStart(2, "0");

Meaning: Make the string two chars long, if a char is missing then set 0 at this position.含义:使字符串长度为两个字符,如果缺少字符,则在此位置设置0

See docs at str.padStart(targetLength, padString)请参阅str.padStart(targetLength, padString)处的文档

Elegant ES6 function to format a date into hh:mm:ss :优雅的 ES6 函数将日期格式化为hh:mm:ss

const leadingZero = (num) => `0${num}`.slice(-2);

const formatTime = (date) =>
  [date.getHours(), date.getMinutes(), date.getSeconds()]
  .map(leadingZero)
  .join(':');

I would like to provide a more neat solution to the problem if I may.The accepted answer is very good.如果可以的话,我想为这个问题提供一个更简洁的解决方案。接受的答案非常好。 But I would have done it like this.但我会这样做。

Date.prototype.getFullMinutes = function () {
   if (this.getMinutes() < 10) {
       return '0' + this.getMinutes();
   }
   return this.getMinutes();
};

Now if you want to use this.现在如果你想使用这个。

console.log(date.getFullMinutes());

I suggest:我建议:

var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;

it is one function call fewer.少了一个函数调用。 It is always good to think about performance.考虑性能总是好的。 It is short as well;它也很短;

使用 ECMAScript 国际化 API, 更多信息

const twoDigitMinutes = date.toLocaleString('en-us', { minute: '2-digit' });

Another option:另外一个选择:

var dateTime = new Date();
var minutesTwoDigitsWithLeadingZero = ("0" + dateTime.getMinutes()).substr(-2);

你应该检查它是否小于 10...不是在寻找它的长度,因为这是一个数字而不是一个字符串

I dont see any ES6 answers on here so I will add one using StandardJS formatting我在这里没有看到任何 ES6 答案,所以我将使用 StandardJS 格式添加一个

// ES6 String formatting example
const time = new Date()
const tempMinutes = new Date.getMinutes()
const minutes = (tempMinutes < 10) ? `0${tempMinutes}` : tempMinutes

.length is undefined because getMinutes is returning a number, not a string. .length未定义,因为getMinutes返回的是数字,而不是字符串。 numbers don't have a length property.数字没有length属性。 You could do你可以做

var m = "" + date.getMinutes();

to make it a string, then check the length (you would want to check for length === 1 , not 0).使其成为字符串,然后检查长度(您需要检查length === 1 ,而不是 0 )。

Numbers don't have a length, but you can easily convert the number to a string, check the length and then prepend the 0 if it's necessary:数字没有长度,但您可以轻松地将数字转换为字符串,检查长度,然后在必要时添加 0:

var strMonth = '' + date.getMinutes();
if (strMonth.length == 1) {
  strMonth = '0' + strMonth;
}

I assume you would need the value as string.我假设您需要该值作为字符串。 You could use the code below.您可以使用下面的代码。 It will always return give you the two digit minutes as string.它总是会返回给你两位数的分钟作为字符串。

var date = new Date(date);
var min = date.getMinutes();

if (min < 10) {
min = '0' + min;
} else {
min = min + '';
}
console.log(min);

Hope this helps.希望这可以帮助。

I usually use this piece of code :我通常使用这段代码:

var start = new Date(timestamp),
    startMinutes = start.getMinutes() < 10 ? '0' + start.getMinutes() : start.getMinutes();

It is quite similar to the @ogur accepted answer but does not concatenate an empty string in the case that 0 is not needed.它与@ogur 接受的答案非常相似,但在不需要 0 的情况下不会连接空字符串。 Not sure it is better.不确定它更好。 Just an other way to do it !只是另一种方式来做到这一点!

how about this?这个怎么样? it works for me!这个对我有用! :) :)

var d = new Date();
var minutes = d.getMinutes().toString().replace(/^(\d)$/, '0$1');
var d = new Date(date);
var dd = d.getDate();
var MM = d.getMonth();
var mm = d.getMinutes();
var HH = d.getHours();

// Hour
var result = ("0" + HH).slice(-2);

// Minutes
var result = ("0" + mm).slice(-2);

// Month
var result = ("0" + MM).slice(-2);
$(".min").append( (date.getMinutes()<10?'0':'') + date.getMinutes() );

new to JS so this was very helpful the most ppl looking at this prob new too so this is how i got it to show in the div called "class="min" JS 新手所以这对大多数人都非常有帮助

hope it helps someone希望它可以帮助某人

Another option to get two digit minutes or hours.获得两位数分钟或小时的另一种选择。

var date = new Date("2012-01-18T16:03");

var minutes = date.toTimeString().slice(3, 5); 
var hours   = date.toTimeString().slice(0, 2); 

you can use moment js :你可以使用moment js:

moment(date).format('mm')

example : moment('2019-10-29T21:08').format('mm') ==> 08示例: moment('2019-10-29T21:08').format('mm') ==> 08

hope it helps someone希望它可以帮助某人

对于两位数分钟使用: new Date().toLocaleFormat("%M")

If you're using AngularJS in your project, just inject $filter and use it like here:如果您在项目中使用 AngularJS,只需注入 $filter 并像这样使用它:

$filter('date')(value, 'HH:mm')

You can also format the output in the template, more on filters here .您还可以在模板中格式化输出,更多关于这里的过滤器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM