Javascript 添加前导零至今

发布于 2024-09-17 12:51:47 字数 518 浏览 17 评论 0原文

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

有人可以告诉我在脚本中的何处插入这些内容,我将非常感激。

I've created this script to calculate the date for 10 days in advance in the format of dd/mm/yyyy:

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

I need to have the date appear with leading zeroes on the day and month component by way of adding these rules to the script. I can't seem to get it to work.

if (MyDate.getMonth < 10)getMonth = '0' + getMonth;

and

if (MyDate.getDate <10)get.Date = '0' + getDate;

If someone could show me where to insert these into the script I would be really appreciative.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

再见回来 2024-09-24 12:51:48

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

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

You can define a "str_pad" function (as in php):

function str_pad(n) {
    return String("00" + n).slice(-2);
}
哆啦不做梦 2024-09-24 12:51:48

我找到了最短的方法来做到这一点:

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

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

I found the shorterst way to do this:

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

will add leading zeros to all lonely, single digits

猫九 2024-09-24 12:51:48
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
*/
Number.prototype.padZero= function(len){
 var s= String(this), c= '0';
 len= len || 2;
 while(s.length < len) s= c + s;
 return s;
}

//in use:

(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
*/
雨后彩虹 2024-09-24 12:51:48

现在您还可以使用 String.prototype.padStart< /a> 以快速、简单的方式实现目标

String(new Date().getMonth() + 1).padStart(2, '0')

可用性可以在 caniuse 进行评估

var date = new Date()

var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')

console.log('%s/%s/%s', month, day, year)

检查

var date = new Date('7/4/2021')
    
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
    
/**
 * Expected output: 07/04/2021
 */
console.log('%s/%s/%s', month, day, year)

适用于旧浏览器的 Polyfill

String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
    configurable : true,
    writable : true,
    value : function (targetLength, padString) {
        'use strict'
        /**
         * String.prototype.padStart polyfill
         * https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
         */
        targetLength = targetLength | 0
        padString = arguments.length > 1 ? String(padString) : ' '

        if (this.length < targetLength && padString.length) {
            targetLength = targetLength - this.length

            while (padString.length < targetLength) {
                padString += padString
            }

            return padString.slice(0, targetLength) + this
        } else {
            return this
        }
    }
})

Nowadays you can also utilize String.prototype.padStart to reach the goal in quick and easy way

String(new Date().getMonth() + 1).padStart(2, '0')

The availability can be assessed at caniuse

var date = new Date()

var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')

console.log('%s/%s/%s', month, day, year)

Check

var date = new Date('7/4/2021')
    
var year = date.getFullYear()
var month = String(date.getMonth() + 1).padStart(2, '0')
var day = String(date.getDate()).padStart(2, '0')
    
/**
 * Expected output: 07/04/2021
 */
console.log('%s/%s/%s', month, day, year)

Polyfill for old browsers

String.prototype.padStart || Object.defineProperty(String.prototype, 'padStart', {
    configurable : true,
    writable : true,
    value : function (targetLength, padString) {
        'use strict'
        /**
         * String.prototype.padStart polyfill
         * https://stackoverflow.com/questions/3605214/javascript-add-leading-zeroes-to-date
         */
        targetLength = targetLength | 0
        padString = arguments.length > 1 ? String(padString) : ' '

        if (this.length < targetLength && padString.length) {
            targetLength = targetLength - this.length

            while (padString.length < targetLength) {
                padString += padString
            }

            return padString.slice(0, targetLength) + this
        } else {
            return this
        }
    }
})
雅心素梦 2024-09-24 12:51:48
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();
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();
醉南桥 2024-09-24 12:51:48

还有另一种方法可以解决这个问题,那就是在 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

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

溺深海 2024-09-24 12:51:48

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

So

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

类似于 if 语句,如果 getDate() 返回一个小于 10 的值,则返回 '0' + Date,否则返回大于 10 的日期(因为我们不需要添加前导 0)。这个月也一样。

编辑:
忘记了 getMonth 是从 0 开始的,所以添加了 +1 来解释它。当然你也可以直接说 d.getMonth() < 9 :但我认为使用 +1 有助于使其更容易理解。

You could use ternary operator to format the date like an "if" statement.

For example:

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

So

(MyDate.getDate() < 10 ? '0' + MyDate.getDate() : MyDate.getDate())

would be similar to an if statement, where if the getDate() returns a value less than 10, then return a '0' + the Date, or else return the date if greater than 10 (since we do not need to add the leading 0). Same for the month.

Edit:
Forgot that getMonth starts with 0, so added the +1 to account for it. Of course you could also just say d.getMonth() < 9 :, but I figured using the +1 would help make it easier to understand.

把梦留给海 2024-09-24 12:51:48
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();
}
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();
}
悲念泪 2024-09-24 12:51:48

您可以提供选项作为参数来格式化日期。第一个参数用于您可能不需要的区域设置,第二个参数用于选项。
欲了解更多信息,请访问
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));

You can provide options as a parameter to format date. First parameter is for locale which you might not need and second is for options.
For more info visit
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));
何以畏孤独 2024-09-24 12:51:48

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

I wrapped the correct answer of this question in a function that can add multiple leading zero's but defaults to adding 1 zero.

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

for working with numbers only and not more than 2 digits, this is also an approach:

function zeroFill(i) {
    return (i < 10 ? '0' : '') + i
  }
神妖 2024-09-24 12:51:48

添加到 @modiX 答案,这就是有效的...不要将其保留为空

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

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"})
愛上了 2024-09-24 12:51:48

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

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'

但请注意,它会在开始时显示年份 > 以及结束的日期

Another option, using a built-in function to do the padding (but resulting in quite long code!):

myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + myDate.getFullYear();

// '12/06/2017'

And another, manipulating strings with regular expressions:

var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');

// '2017/06/12'

But be aware that one will show the year at the start and the day at the end.

自我难过 2024-09-24 12:51:48

这是如何处理这种情况的非常简单的示例。

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

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

挥剑断情 2024-09-24 12:51:48

我认为这个解决方案更容易并且容易记住:

var MyDate = new Date();


var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();

day = checkDate(day);
month = checkDate(month);


function checkDate(i){
    if(i < 10){
    i = '0' + i;
  }
  return i;
}

console.log(`${month}/${day}/${year}`);

I think this solution is easier and can be easily remembered:

var MyDate = new Date();


var day = MyDate.getDate() + 10; // 10 days in advance
var month = MyDate.getMonth() + 1; // since months start from 0 we should add 1 to it
var year = MyDate.getFullYear();

day = checkDate(day);
month = checkDate(month);


function checkDate(i){
    if(i < 10){
    i = '0' + i;
  }
  return i;
}

console.log(`${month}/${day}/${year}`);

自我难过 2024-09-24 12:51:48

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

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

(另请参阅这个小提琴

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)

满身野味 2024-09-24 12:51:48

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

As @John Henckel suggests, starting using the toISOString() method makes things easier

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

墨落画卷 2024-09-24 12:51:48

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

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

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();
};
谁的年少不轻狂 2024-09-24 12:51:48

您可以使用 String.slice() 提取字符串的一部分并将其作为新字符串返回,而不修改原始字符串:

const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16

或者您也可以使用库,例如​​ Moment.js 格式化日期:

const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16

You can use String.slice() which extracts a section of a string and returns it as a new string, without modifying the original string:

const currentDate = new Date().toISOString().slice(0, 10) // 2020-04-16

Or you can also use a lib such as Moment.js to format the date:

const moment = require("moment")
const currentDate = moment().format("YYYY-MM-DD") // 2020-04-16
骄傲 2024-09-24 12:51:48

您可以简单地使用:

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

You could simply use :

const d = new Date();
const day = `0${d.getDate()}`.slice(-2);

So a function could be created like :

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

Your new code :

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

MyDate.setDate(MyDate.getDate()+10);
MyDateString = AddZero(MyDate.getDate()) + '/' + AddZero(MyDate.getMonth() + 1) + '/' + MyDate.getFullYear();
不必你懂 2024-09-24 12:51:48

toISOString 可以获得前导 0

    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

toISOString can get leading 0

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

output will be similar to this : 2021-06-09T12:14:27.000Z

陈独秀 2024-09-24 12:51:48
const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
const month = date.toLocaleDateString('en-US', { month: '2-digit' });
const day = date.toLocaleDateString('en-US', { day: '2-digit' });
const year = date.getFullYear();
const dateString = `${month}-${day}-${year}`;
风流物 2024-09-24 12:51:48

我能想到的最短版本:

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

Shortest version I can think of:

const addZero = (val: number) => (val < 10 ? "0" + val : val);
笨死的猪 2024-09-24 12:51:48
d = new Date();
theMonth = ("0" + (d.getMonth() + 1)).substr(-2);
theDate = ("0" + d.getDate()).substr(-2);
d = new Date();
theMonth = ("0" + (d.getMonth() + 1)).substr(-2);
theDate = ("0" + d.getDate()).substr(-2);
残龙傲雪 2024-09-24 12:51:48

以下目标是提取配置、挂钩到 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/主动/U4MZ3/

The following aims to extract configuration, hook into Date.protoype and apply configuration.

I've used an Array to store time chunks and when I push() this as a Date object, it returns me the length to iterate. When I'm done, I can use join on the return value.

This seems to work pretty fast: 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();

demo: http://jsfiddle.net/tive/U4MZ3/

最近可好 2024-09-24 12:51:48

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

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

Add some padding to allow a leading zero - where needed - and concatenate using your delimiter of choice as string.

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('/');
与风相奔跑 2024-09-24 12:51:48
 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
  }
 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
  }
长伴 2024-09-24 12:51:47

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

Try this: 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();

EDIT:

To explain, .slice(-2) gives us the last two characters of the string.

So no matter what, we can add "0" to the day or month, and just ask for the last two since those are always the two we want.

So if the MyDate.getMonth() returns 9, it will be:

("0" + "9") // Giving us "09"

so adding .slice(-2) on that gives us the last two characters which is:

("0" + "9").slice(-2)
"09"

But if MyDate.getMonth() returns 10, it will be:

("0" + "10") // Giving us "010"

so adding .slice(-2) gives us the last two characters, or:

("0" + "10").slice(-2)
"10"
桃气十足 2024-09-24 12:51:47

现代方法

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

const date = new Date(2018, 2, 1)
const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

或者使用 Temporal 对象(仍在提案中caniuse):

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const result = date.toLocaleString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

当您使用 undefined 作为第一个参数时,它将检测浏览器语言。或者,您也可以在年份选项上使用2 位

性能

如果您打算格式化大量日期,则应考虑使用 Intl.DateTimeFormat 改为:

const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
const date = new Date(2018, 2, 1) // can also be a Temporal object
const result = formatter.format(date)
console.log(result) // outputs “01/03/2018”

格式化程序与日期和时间对象兼容。

历史日期

与 Temporal 构造函数不同,0 到 99 之间的年份在 Date 构造函数中将被解释为 20 世纪年份。为了防止这种情况,请像这样初始化日期:

const date = new Date()
date.setFullYear(18, 2, 1) // the year is A.D. 18

这对于 Temporal 对象来说不是必需的,但低于 1000 的年份在所有情况下都不会包含前导零,因为格式化程序(为 Date 和 Temporal API 共享)不支持 4 位数字 完全格式化。在这种情况下,您必须手动格式化(见下文)。

对于 ISO 8601 格式

如果您想获取 YYYY-MM-DD 格式 (ISO 8601) 的日期,解决方案看起来会有所不同:

const date = new Date(Date.UTC(2018, 2, 1))
const result = date.toISOString().split('T')[0]
console.log(result) // outputs “2018-03-01”

您输入的日期应采用 UTC 格式,否则 toISOString() 将为您解决该问题。这是通过使用 Date.UTC 来完成的,如上所示。

ISO 8601 格式的历史日期

与 Temporal 构造函数不同,0 到 99 之间的年份在 Date 构造函数中将被解释为 20 世纪年份。为了防止这种情况,请像这样初始化日期以用于 ISO 8601 格式:

const date = new Date()
date.setUTCFullYear(18, 2, 1) // the year is A.D. 18

请注意,日期在 1000 年之前或 9999 年之后的 Temporal 对象的 ISO 格式将具有 与旧版 Date API 相比,格式不同。建议在所有情况下回退到自定义格式以强制使用 4 位数年份。

年份的自定义 4 位格式

遗憾的是,格式化程序不支持年份的前导零。没有 4 位 选项。这也适用于 Temporal 对象,因为它们确实共享相同的格式化程序。

幸运的是,Date API 的 ISO 格式将始终显示至少 4 位数字的年份,但 Temporal 对象不会。因此,至少对于 Date API,您可以使用 ISO 8601 格式方法的一部分,使用手动格式化方法来格式化 1000 年之前的带有前导零的历史日期:

const date = new Date()
date.setUTCFullYear(18, 2, 1)
const ymd = date.toISOString().split('T')[0].split('-')
const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`
console.log(result) // outputs “01/03/0018”

对于 Temporal 对象,需要不同的路由,因为 ISOYearString 对于 1000 年之前和 9999 年之后的日期,格式会有所不同,如前所述:

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const zeroPad = (n, digits) => n.toString().padStart(digits, '0');
const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`;
console.log(result) // outputs “01/03/0018”

其他

对于日期和时间 API,还有 toLocaleTimeString,它允许您本地化和格式化日期的时间。

The modern way

The new modern way to do this is to use toLocaleDateString, because it allows you not only to format a date with proper localization, but even to pass format options to achieve the desired result:

const date = new Date(2018, 2, 1)
const result = date.toLocaleDateString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

Or using a Temporal object (still in proposal, caniuse):

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const result = date.toLocaleString("en-GB", { // you can use undefined as first argument
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
console.log(result) // outputs “01/03/2018”

When you use undefined as the first argument it will detect the browser language, instead. Alternatively, you can use 2-digit on the year option, too.

Performance

If you plan to format a lot of dates, you should consider using Intl.DateTimeFormat instead:

const formatter = new Intl.DateTimeFormat("en-GB", { // <- re-use me
  year: "numeric",
  month: "2-digit",
  day: "2-digit",
})
const date = new Date(2018, 2, 1) // can also be a Temporal object
const result = formatter.format(date)
console.log(result) // outputs “01/03/2018”

The formatter is compatible with Date and Temporal objects.

Historical dates

Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so:

const date = new Date()
date.setFullYear(18, 2, 1) // the year is A.D. 18

This is not required for Temporal objects, but years below 1000 will not contain leading zeros in all cases, because the formatter (that is shared for the Date and Temporal API) does not support 4-digit formatting at all. In this case you have to do manual formatting (see below).

For the ISO 8601 format

If you want to get your date in the YYYY-MM-DD format (ISO 8601), the solution looks different:

const date = new Date(Date.UTC(2018, 2, 1))
const result = date.toISOString().split('T')[0]
console.log(result) // outputs “2018-03-01”

Your input date should be in the UTC format or toISOString() will fix that for you. This is done by using Date.UTC as shown above.

Historical dates for the ISO 8601 format

Unlike in the Temporal constructor years between 0 and 99 will be interpreted as 20th century years on the Date constructor. To prevent this, initialize the date like so to be used for the ISO 8601 format:

const date = new Date()
date.setUTCFullYear(18, 2, 1) // the year is A.D. 18

Note that the ISO format for Temporal objects with dates before the year 1000 or after the year 9999 will have a different formatting compared to the legacy Date API. It is recommend to fallback to custom formatting to enforce 4 digit years in all circumstances.

Custom 4-digit formatting on the year

Sadly, the formatter doesn't support leading zeros on the year. There is no 4-digit option. This will remain for Temporal objects as well, because they do share the same formatter.

Fortunately, the ISO format of the Date API will always display at least 4 digits on the year, although Temporal objects do not. So at least for the Date API you can format historical dates before the year 1000 with leading zeros by falling back to a manual formatting approach using part of the ISO 8601 format method:

const date = new Date()
date.setUTCFullYear(18, 2, 1)
const ymd = date.toISOString().split('T')[0].split('-')
const result = `${ymd[2]}/${ymd[1]}/${ymd[0]}`
console.log(result) // outputs “01/03/0018”

For a Temporal object a different route is necessary, since the ISOYearString will be formatted differently for dates before the year 1000 and after the year 9999 as mentioned before:

const date = new Temporal.PlainDate(2018, 3, 1) // also works with zoned date
const zeroPad = (n, digits) => n.toString().padStart(digits, '0');
const result = `${zeroPad(date.day, 2)}/${zeroPad(date.month, 2)}/${zeroPad(date.year, 4)}`;
console.log(result) // outputs “01/03/0018”

Miscellaneous

For the Date and Temporal API there is also toLocaleTimeString, that allows you to localize and format the time of a date.

调妓 2024-09-24 12:51:47

以下是日期对象文档 在 Mozilla 开发者网络上使用自定义“pad”函数,而无需扩展 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

Here is an example from the Date object docs on the Mozilla Developer Network using a custom "pad" function, without having to extend Javascript's Number prototype. The handy function they give as an example is

function pad(n){return n<10 ? '0'+n : n}

And below is it being used in context.

/* 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
甜味拾荒者 2024-09-24 12:51:47

对于来自未来的人们(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.prototypepadString code> target,以便目标的新长度为 targetLength

例子

"use strict"

let month = "9"

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

let byte = "00000100"

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

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

Solution

"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

Explaination

the String.prototype.padStart(targetLength[, padString]) adds as many as possible padString in the String.prototype target so that the new length of the target is targetLength.

Example

"use strict"

let month = "9"

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

let byte = "00000100"

byte = byte.padStart(8, "0") // "00000100"
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文