Javascript添加前导零到目前为止

我已经创建了这个脚本,以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;
if (MyDate.getDate <10)get.Date = '0' + getDate;
如果有人能告诉我将这些插入脚本的位置,我会非常感激。     
已邀请:
试试这个:http://jsfiddle.net/xA5B7/
var MyDate = new Date();
var MyDateString;

MyDate.setDate(MyDate.getDate() + 20);

MyDateString = ('0' + MyDate.getDate()).slice(-2) + '/'
             + ('0' + (MyDate.getMonth()+1)).slice(-2) + '/'
             + MyDate.getFullYear();
编辑: 为了解释,
.slice(-2)
给出了字符串的最后两个字符。 所以无论如何,我们可以添加
"0"
到日或月,并且只要求最后两个,因为那些总是我们想要的两个。 所以如果
MyDate.getMonth()
返回
9
,它将是:
("0" + "9") // Giving us "09"
所以添加
.slice(-2)
给我们最后两个字符是:
("0" + "9").slice(-2)
"09"
但如果
MyDate.getMonth()
返回
10
,它将是:
("0" + "10") // Giving us "010"
所以添加
.slice(-2)
给我们最后两个字符,或者:
("0" + "10").slice(-2)
"10"
    
以下是使用自定义“pad”函数的Mozilla Developer Network上的Date对象文档的示例,无需扩展Javascript的Number原型。他们给出的便利功能是
function pad(n){return n<10 ? '0'+n : n}
以下是它在上下文中使用。
/* use a function for the exact format desired... */
function ISODateString(d){
    function pad(n){return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
    + pad(d.getUTCMonth()+1)+'-'
    + pad(d.getUTCDate())+'T'
    + pad(d.getUTCHours())+':'
    + pad(d.getUTCMinutes())+':'
    + pad(d.getUTCSeconds())+'Z'
}

var d = new Date();
console.log(ISODateString(d)); // prints something like 2009-09-28T19:03:12Z
    
你可以定义一个“str_pad”函数(如在php中):
function str_pad(n) {
    return String("00" + n).slice(-2);
}
    
Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}
//正在使用:
(function(){
 var myDate= new Date(), myDateString;
 myDate.setDate(myDate.getDate()+10);

 myDateString= [myDate.getDate().padZero(),
 (myDate.getMonth()+1).padZero(),
 myDate.getFullYear()].join('/');

 alert(myDateString);
})()

/*  value: (String)
09/09/2010
*/
    
如果要按语言本地化日期输出并需要前导零,则解决方案看起来不同:
var date = new Date(2018, 2, 1);
var result = date.toLocaleDateString("de-DE", {
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
});
console.log(result);
为您提供未来的人(ECMAScript 2017及以后) 解
"use strict"

const today = new Date()

const year = today.getFullYear()

const month = `${today.getMonth() + 1}`.padStart(2, 0)

const day = `${today.getDate()}`.padStart(2, 0)

const stringDate = [day, month, year].join("/") // 13/12/2017
String.prototype.padStart(targetLength[, padString])
String.prototype
目标中添加尽可能多的
padString
,以使目标的新长度为
targetLength
。 例
"use strict"

let month = "9"

month = month.padStart(2, 0) // "09"

let byte = "00000100"

byte = byte.padStart(8, 0) // "00000100"
    
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();
    
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();
}
    
您可以使用三元运算符来格式化日期,就像“if”语句一样。 例如:
var MyDate = new Date();
MyDate.setDate(MyDate.getDate()+10);
var MyDateString = (MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate()) + '/' + ((d.getMonth()+1) < 10 ? '0' + (d.getMonth()+1) : (d.getMonth()+1)) + '/' + MyDate.getFullYear();
所以
(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())
类似于if语句,如果getDate()返回小于10的值,则返回'0'+ Date,否则返回大于10的日期(因为我们不需要添加前导0)。月份相同。 编辑: 忘了getMonth从0开始,所以添加了+1来说明它。当然你也可以说d.getMonth()&lt; 9:但我认为使用+1将有助于使其更容易理解。     
我在一个函数中包含了这个问题的正确答案,该函数可以添加多个前导零但是默认添加1个零。
function zeroFill(nr, depth){
  depth = (depth === undefined)? 1 : depth;

  var zero = "0";
  for (var i = 0; i < depth; ++i) {
    zero += "0";
  }

  return (zero + nr).slice(-(depth + 1));
}
对于仅使用数字且不超过2位数,这也是一种方法:
function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }
    
让您的生活更轻松,并使用Moment.js一些示例代码:
var beginDateTime = moment()
  .format('DD-MM-YYYY HH:mm')
  .toString();

// Now will print 30-06-2015 17:55
console.log(beginDateTime);
    
我找到了这样做的简短方法:
 MyDateString.replace(/(^|D)(d)(?!d)/g, '$10$2');
将为所有孤独的单个数字添加前导零     
另一种选择,使用内置函数来执行填充(但导致代码很长!):
myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + myDate.getFullYear();

// '12/06/2017'
另外,用正则表达式操纵字符串:
var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');

// '2017/06/12'
但请注意,人们会在开始时和结束时显示年份。     
以下目的是提取配置,挂入
Date.protoype
并应用配置。 我使用了
Array
来存储时间块,当我
push()
this
作为
Date
对象时,它会返回迭代的长度。当我完成后,我可以在
return
值上使用
join
。 这看起来非常快:0.016ms
// Date protoype
Date.prototype.formatTime = function (options) {
    var i = 0,
        time = [],
        len = time.push(this.getHours(), this.getMinutes(), this.getSeconds());

    for (; i < len; i += 1) {
        var tick = time[i];
        time[i] = tick < 10 ? options.pad + tick : tick;
    }

    return time.join(options.separator);
};

// Setup output
var cfg = {
    fieldClock: "#fieldClock",
    options: {
        pad: "0",
        separator: ":",
        tick: 1000
    }
};

// Define functionality
function startTime() {
    var clock = $(cfg.fieldClock),
        now = new Date().formatTime(cfg.options);

    clock.val(now);
    setTimeout(startTime, cfg.options.tick);
}

// Run once
startTime();
演示:http://jsfiddle.net/tive/U4MZ3/     
我会做的是创建我自己的自定义日期助手,如下所示:
var DateHelper = {
    addDays : function(aDate, numberOfDays) {
        aDate.setDate(aDate.getDate() + numberOfDays); // Add numberOfDays
        return aDate;                                  // Return the date
    },
    format : function format(date) {
        return [
           ("0" + date.getDate()).slice(-2),           // Get day and pad it with zeroes
           ("0" + (date.getMonth()+1)).slice(-2),      // Get month and pad it with zeroes
           date.getFullYear()                          // Get full year
        ].join('/');                                   // Glue the pieces together
    }
}

// With this helper, you can now just use one line of readable code to :
// ---------------------------------------------------------------------
// 1. Get the current date
// 2. Add 20 days
// 3. Format it
// 4. Output it
// ---------------------------------------------------------------------
document.body.innerHTML = DateHelper.format(DateHelper.addDays(new Date(), 20));
添加一些填充以允许前导零 - 在需要的地方 - 并使用您选择的分隔符作为字符串连接。
Number.prototype.padLeft = function(base,chr){
        var  len = (String(base || 10).length - String(this).length)+1;
        return len > 0? new Array(len).join(chr || '0')+this : this;
    }

var d = new Date(my_date);
var dformatted = [(d.getMonth()+1).padLeft(), d.getDate().padLeft(), d.getFullYear()].join('/');
    

要回复问题请先登录注册