Javascript添加前导零到目前为止

问题描述 投票:363回答:20

我已经创建了这个脚本,以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;

如果有人能告诉我将这些插入脚本的位置,我会非常感激。

javascript date date-format time-format leading-zero
20个回答
1210
投票

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

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

3
投票

我找到了最简单的方法:

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

将为所有孤独的单个数字添加前导零


2
投票

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

2
投票

您可以提供选项作为格式化日期的参数。第一个参数是您可能不需要的区域设置,第二个参数是选项。欲了解更多信息,请访问https://developer.mozilla.org/en-US/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));

1
投票

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

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'

但请注意,人们会在开始时和结束时显示年份。


0
投票

以下目的是提取配置,挂钩到Date.protoype并应用配置。

我用Array存储时间块,当我push() this作为Date对象时,它返回我的迭代长度。当我完成后,我可以在join值上使用return

这看起来非常快: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();

但是:ぁzxswい


0
投票

我会做的是创建我自己的自定义日期助手,如下所示:

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


0
投票

添加一些填充以允许前导零 - 在需要的地方 - 并使用您选择的分隔符作为字符串连接。

this Fiddle

0
投票

正如@John Henckel所说,开始使用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('/'); 方法会让事情变得更容易


0
投票

加上@modiX答案,这是有效的......不要把它当成空的

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

95
投票

以下是使用自定义“pad”功能的Mozilla开发者网络上的Date object docs的示例,无需扩展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

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

41
投票

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

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

21
投票

新的现代方法是使用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参数。


17
投票

For you people from the future (ECMAScript 2017 and beyond)

"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])padString目标中添加尽可能多的String.prototype,以便目标的新长度为targetLength

Example

"use strict"

let month = "9"

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

let byte = "00000100"

byte = byte.padStart(8, 0) // "00000100"

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

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

3
投票

您可以使用三元运算符来格式化日期,就像“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会有助于理解它。


3
投票

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

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

// Now will print 30-06-2015 17:55
console.log(beginDateTime);
© www.soinside.com 2019 - 2024. All rights reserved.