我已经创建了这个脚本,以dd/mm/yyyy的格式提前计算10天的日期:

var MyDate = new Date();
var MyDateString = new Date();
MyDate.setDate(MyDate.getDate()+10);
MyDateString = MyDate.getDate() + '/' + (MyDate.getMonth()+1) + '/' + MyDate.getFullYear();

我需要通过将这些规则添加到脚本中,使日期在日期和月份组件上以前导零出现。我好像不能让它工作。

if (MyDate.getMonth < 10)getMonth = '0' + getMonth;

and

if (MyDate.getDate <10)get.Date = '0' + getDate;

如果有人能告诉我在哪里插入这些脚本,我会非常感激。


当前回答

function formatDate(jsDate){
  // add leading zeroes to jsDate when days or months are < 10.. 
  // i.e.
  //     formatDate(new Date("1/3/2013")); 
  // returns
  //    "01/03/2103"
  ////////////////////
  return (jsDate.getDate()<10?("0"+jsDate.getDate()):jsDate.getDate()) + "/" + 
      ((jsDate.getMonth()+1)<10?("0"+(jsDate.getMonth()+1)):(jsDate.getMonth()+1)) + "/" + 
      jsDate.getFullYear();
}

其他回答

这里有一个非常简单的例子,你可以如何处理这种情况。

var mydate = new Date(); var month = (mydate.getMonth(). tostring()。长度< 2 ?“0”+ mydate.getMonth () .toString (): mydate.getMonth ()); var date = (mydate.getDate(). tostring()。长度< 2 ?“0”+ mydate.getDate () .toString (): mydate.getDate ()); var year = mydate.getFullYear(); console.log(“格式Y-m-d:”+“-”+月+“-”+日期); Y / m / d: console.log(“格式”,年+ " +月+ " +日期);

var MyDate = new Date();
var MyDateString = '';
MyDate.setDate(MyDate.getDate());
var tempoMonth = (MyDate.getMonth()+1);
var tempoDate = (MyDate.getDate());
if (tempoMonth < 10) tempoMonth = '0' + tempoMonth;
if (tempoDate < 10) tempoDate = '0' + tempoDate;
MyDateString = tempoDate + '/' + tempoMonth + '/' + MyDate.getFullYear();

你可以简单地使用:

const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

所以可以这样创建一个函数:

AddZero(val){
    // adding 0 if the value is a single digit
    return `0${val}`.slice(-2);
}

你的新代码:

var MyDate = new Date();
var MyDateString = new Date();

MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
function pad(value) {
    return value.tostring().padstart(2, 0);
}

let d = new date();
console.log(d);
console.log(`${d.getfullyear()}-${pad(d.getmonth() + 1)}-${pad(d.getdate())}t${pad(d.gethours())}:${pad(d.getminutes())}:${pad(d.getseconds())}`);

toISOString可以得到前导0

const currentdate = new Date(); const date = new date (date. utc (currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds())); //你可以传递YY, MM, DD //op: 2018-03-01 //i have passed YY, MM, DD, HH, Min, Sec // op: 2021-06-09T12:14:27.000Z console.log (date.toISOString ());

输出将类似于此:2021-06-09T12:14:27.000Z