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;

如果有人可以告诉我将这些内容插入脚本的位置,我将非常感激。


#1楼

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();

#2楼

这是来自Mozilla开发人员网络上Date对象文档的示例,该示例使用自定义的“ pad”功能,而无需扩展Java的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

#3楼

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();
}

#4楼

下面的目的是提取配置,挂接到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/


#5楼

您可以使用三元运算符将日期格式设置为“ 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()<9:,但是我认为使用+1可以使理解变得更容易。


#6楼

我将这个问题的正确答案包装在一个函数中,该函数可以添加多个前导零,但默认情况下会添加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
  }

#7楼

您可以定义一个“ str_pad”函数(如php中一样):

function str_pad(n) {
    return String("00" + n).slice(-2);
}

#8楼

使您的生活更轻松,并使用Moment.js一些示例代码:

var beginDateTime = moment()
  .format('DD-MM-YYYY HH:mm')
  .toString();

// Now will print 30-06-2015 17:55
console.log(beginDateTime);

#9楼

我要做的是创建自己的自定义日期帮助器,如下所示:

 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)); 

(另请参阅此小提琴


#10楼

试试这个: 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"

#11楼

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
*/

#12楼

另一种选择,使用内置函数进行填充(但会导致代码很长!):

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'

但要知道,一个将显示在一年的开始结束的一天。


#13楼

我找到了最简单的方法:

 MyDateString.replace(/(^|\D)(\d)(?!\d)/g, '$10$2');

会将前导零添加到所有孤独的一位数字


#14楼

添加一些填充以允许前导零(在需要时),并使用您选择的分隔符作为字符串进行连接。

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('/');

#15楼

新的现代方法是使用toLocaleDateString ,因为它不仅允许您使用适当的本地化来格式化日期,您甚至可以传递格式选项来存档所需的结果:

 var date = new Date(2018, 2, 1); var result = date.toLocaleDateString("en-GB", { // you can skip the first argument year: "numeric", month: "2-digit", day: "2-digit", }); console.log(result); 

当您跳过第一个参数时,它将检测浏览器语言。 此外,您还可以在年份选项上使用2-digit

如果您不需要支持像IE10这样的旧浏览器,这是完成任务的最干净的方法。 IE10和更低版本不了解options参数。


#16楼

面向未来的人们(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"

#17楼

正如@John Henckel所建议的那样,开始使用toISOString()方法使事情变得更容易

 const dateString = new Date().toISOString().split('-'); const year = dateString[0]; const month = dateString[1]; const day = dateString[2].split('T')[0]; console.log(`${year}-${month}-${day}`); 


#18楼

您可以提供选项作为格式化日期的参数。 第一个参数用于您可能不需要的语言环境,第二个参数用于选项。 有关更多信息,请访问https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

var date = new Date(Date.UTC(2012, 1, 1, 3, 0, 0));
var options = { year: 'numeric', month: '2-digit', day: '2-digit' };
console.log(date.toLocaleDateString(undefined,options));

#19楼

添加到@modiX答案,这是有效的...不要留空

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})

#20楼

 let date = new Date();
 let dd = date.getDate();//day of month

 let mm = date.getMonth();// month
 let yyyy = date.getFullYear();//day of week
 if (dd < 10) {//if less then 10 add a leading zero
     dd = "0" + dd;
   }
 if (mm < 10) {
    mm = "0" + mm;//if less then 10 add a leading zero
  }

#21楼

还有另一种解决此问题的方法,即在JavaScript中使用slice

var d = new Date();
var datestring = d.getFullYear() + "-" + ("0"+(d.getMonth()+1)).slice(-2) +"-"+("0" + d.getDate()).slice(-2);

datestring返回日期,其格式与您期望的一样:2019-09-01

另一种方法是使用dateformat库: https : //github.com/felixge/node-dateformat


#22楼

尝试此基本功能,无需库

Date.prototype.CustomformatDate = function() {
 var tmp = new Date(this.valueOf());
 var mm = tmp.getMonth() + 1;
 if (mm < 10) mm = "0" + mm;
 var dd = tmp.getDate();
 if (dd < 10) dd = "0" + dd;
 return mm + "/" + dd + "/" + tmp.getFullYear();
};

#23楼

这是一个非常简单的示例,您将如何处理这种情况。

 var mydate = new Date(); var month = (mydate.getMonth().toString().length < 2 ? "0"+mydate.getMonth().toString() :mydate.getMonth()); var date = (mydate.getDate().toString().length < 2 ? "0"+mydate.getDate().toString() :mydate.getDate()); var year = mydate.getFullYear(); console.log("Format Ymd : ",year+"-"+month+"-" + date); console.log("Format Y/m/d : ",year+"/"+month+"/" + date); 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值