用Javascript格式化日期时间
我应该将javascript中的datetime值格式化为yyyy-MM-dd hh:MM:ss格式 我试过这个用Javascript格式化日期时间,javascript,asp.net-mvc,Javascript,Asp.net Mvc,我应该将javascript中的datetime值格式化为yyyy-MM-dd hh:MM:ss格式 我试过这个 var btf = new Date(value.createDate); var billingTimeFormatted = btf.getFullYear() + "-" + btf.getMonth() + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf
var btf = new Date(value.createDate);
var billingTimeFormatted = btf.getFullYear() + "-" + btf.getMonth() + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();
但结果是这样的
2017-8-31 02:00:00
*输入分钟数已编辑您的代码没有问题。Javascript仅以一位数返回小于10的整数。使用函数将其格式化为2的字符串
function formatWithZero(val)
{
// as per comment by @RobG below, return ('0'+val).slice(-2) will also
// do the same thing in lesser lines of code. It works and can be used.
var value = val.toString();
if(value.length > 1)
return value;
var str = "00"+value;
return str.slice(str.length-2,str.length); ;
}
//I am using Date.now(), you can use your value.
var btf = new Date(Date.now());
var billingTimeFormatted = btf.getFullYear() + "-" + formatWithZero(btf.getMonth()) + "-" + formatWithZero(btf.getDate()) + " " + formatWithZero(btf.getHours()) + ":" + formatWithZero(btf.getMinutes()) + ":" + formatWithZero(btf.getSeconds());
alert(billingTimeFormatted);
您忘记了()
的getMinutes()
有两位数字:
var btf = new Date();
var currentMonth = btf.getMonth();
if (currentMonth < 10) { currentMonth = '0' + currentMonth; }
var billingTimeFormatted = btf.getFullYear() + "-" + currentMonth + "-" + btf.getDate() + " " + btf.getHours() + ":" + btf.getMinutes() + ":" + btf.getSeconds();
var btf=新日期();
var currentMonth=btf.getMonth();
如果(currentMonth<10){currentMonth='0'+currentMonth;}
var billingTimeFormatted=btf.getFullYear()+“-”+currentMonth+“-”+btf.getDate()+“+btf.getHours()+”:“+btf.getMinutes()+”:“+btf.getSeconds();
您忘记了getMinutes
后面的括号。如果您不介意添加另一个库,请考虑使用Time.js.<代码> BTF.GETMIX <代码> > >代码> BTF.GETMIUTESH()/代码>投票结束。是的,它只是输入错误,将对其进行编辑。我猜这也将在小时分钟和秒内工作。是的。它应该是包含这些值的有效日期。整个函数体可以是return('0'+val)。slice(-2)
。是的,但我不想检查它的长度是否合适。我也把你的建议作为评论放在函数中。