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;

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

神奇番长2020/03/16 15:05:20
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())}`);
StafanEva2020/03/16 15:05: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
  }
飞云Jim2020/03/16 15:05:20

try this for a basic function, no libraries required

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();
};
さ恋旧る2020/03/16 15:05:20

What I would do, is create my own custom Date helper that looks like this :

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

(see also this Fiddle)

StafanL2020/03/16 15:05:20

Here is very simple example how you can handle this situation.

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 Y-m-d : ",year+"-"+month+"-" + date);

console.log("Format Y/m/d : ",year+"/"+month+"/" + date);

TomL2020/03/16 15:05:20

Adding on to @modiX answer, this is what works...DO NOT LEAVE THAT as empty

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
神无阳光2020/03/16 15:05:20
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();
}
老丝Tony2020/03/16 15:05:20

There is another approach to solve this problem, using slice in JavaScript.

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

the datestring return date with format as you expect: 2019-09-01

another approach is using dateformat library: https://github.com/felixge/node-dateformat

逆天Gil2020/03/16 15:05:19

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

古一斯丁猴子2020/03/16 15:05:19

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

function str_pad(n) {
    return String("00" + n).slice(-2);
}
伽罗Tony2020/03/16 15:05:19

面向未来的人们(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])增加尽可能多的padStringString.prototype目标,使得目标的新长度是targetLength

"use strict"

let month = "9"

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

let byte = "00000100"

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