JavaScript将日期前面加0

616

我创建了这个脚本来计算10天后的日期,格式为dd/mm/yyyy:

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;

如果有人能告诉我在脚本中应该插入这些内容的位置,我会非常感激。


7
作为一种良好的惯例,您应该将变量名的第一个字符设置为小写,并将驼峰命名保留给对象/原型。 - zykadelic
如果YYYY-MM-DD格式可接受,这将是一个非常好的答案:https://dev59.com/UXA75IYBdhLWcg3w3NBe#28431880 - Fabien Snauwaert
2
向下滚动以查看ES6+ padStart答案 - technogeek1995
33个回答

1

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


1
我会创建自己的日期助手,如下所示:

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

参见this Fiddle(也可参考此Fiddle)。

1
toISOString 可以获取前导零。

    const currentdate = new Date(); 
    const date = new Date(Date.UTC(currentdate.getFullYear(), (currentdate.getMonth()),currentdate.getDate(), currentdate.getHours(), currentdate.getMinutes(), currentdate.getSeconds()));
    //you can pass YY, MM, DD //op: 2018-03-01
    //i have passed YY, MM, DD, HH, Min, Sec // op : 2021-06-09T12:14:27.000Z
    console.log(date.toISOString());

输出结果将类似于:2021-06-09T12:14:27.000Z。

1
你可以简单地使用:
const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

因此,可以创建一个函数,例如:

AddZero(val){
    // adding 0 if the value is a single digit
    return `0${val}`.slice(-2);
}

你的新代码:

var MyDate = new Date();
var MyDateString = new Date();

MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();

1

尝试使用此基本函数,无需任何库

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

1

2023年更新

如果您正在寻找一个简单的现代解决方案,date-fns可以完美地处理这个问题。

用法

import {format} from 'date-fns';

const myDate = new Date();
const formattedDate = format(myDate, 'dd/MM/yyyy');

0
在需要的情况下添加一些填充以允许前导零,并使用您选择的分隔符将其连接为字符串。
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
一个简单的dateformat库拯救了我的生命(GitHub):
  • Node.js:var dateFormat = require("dateformat");
  • ES6:import dateFormat from "dateformat";
const now = new Date();             // consider 3rd of December 1993

const full = dateFormat(today, "yyyy-mm-dd");  // 1993-12-03
const day = dateFormat(today, "dd");           // 03
const month = dateFormat(today, "mm");         // 12
const year = dateFormat(today, "yyyy");        // 1993

值得一提的是,它支持广泛的掩码选项。

0

以下旨在提取配置,钩入Date.protoype并应用配置。

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

这似乎运行得非常快:0.016毫秒

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


0

我能想到的最短版本:

const addZero = (val: number) => (val < 10 ? "0" + val : val);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接