我创建了这个脚本计算日期的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"

其他提示

下面是从日期对象的示例文档使用自定义的“垫”的功能,而无需扩展JavaScript的号码原型Mozilla开发者网络上的。他们给出作为一个例子的方便的功能是

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

在新的现代的方式做,这是使用的 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和较低版本将不明白选项参数。

你的人从未来(2017年的ECMAScript及以后)

解决方案

"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

实施例

"use strict"

let month = "9"

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

let byte = "00000100"

byte = byte.padStart(8, 0) // "00000100"
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 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();

我发现这样做的最短途径:

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

将前导零添加到所有孤独,个位数

您可以使用三元运算符来格式化日期就像一个“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())

将类似于如果一个语句,其中如果GETDATE()返回一个值小于10,则返回“0” +日期,否则返回日期,如果大于10(因为我们不需要加上前导0)。同为一个月。

编辑: 忘了得到月从0开始,所以增加了+1考虑到它。当然,你也可以只说d.getMonth()<9:,但我想用+1将有助于使之更易于理解

让你的生活更方便,使用 Moment.js 一些示例代码:

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

// Now will print 30-06-2015 17:55
console.log(beginDateTime);
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();
}

我包裹在一个函数这个问题,可以添加多个前导零但默认为加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
  }

可以提供选项作为参数格式日期。第一个参数是语言环境,你可能不需要和第二是选项。 欲了解更多信息请访问 https://developer.mozilla.org/ EN-US /文档/网络/的JavaScript /参考/ Global_Objects /日期/ 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));

另一种选择,使用内置函数做填充(但导致相当长的代码!):

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'

但要知道,一个将显示今年在启动的,并在月底的一天的。

还有一个办法来解决这个问题,在JavaScript中使用slice

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

datestring归期与格式如您所愿:2019年9月1日

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

以下旨在提取结构,钩入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();

<强>演示: 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('/');

作为@约翰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}`);

添加到@modiX答案,这是什么工作......,不要离开为空

today.toLocaleDateString("default", {year: "numeric", month: "2-digit", day: "2-digit"})
 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
  }

尝试这一个基本的功能,不需要库

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();
};
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top