Javascript 添加前导零到日期 [英] Javascript add leading zeroes to date

查看:46
本文介绍了Javascript 添加前导零到日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了这个脚本来以 dd/mm/yyyy 的格式提前计算 10 天的日期:

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;

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.

推荐答案

试试这个: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) 给了我们字符串的最后两个字符.

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

所以无论如何,我们都可以在日或月添加"0",然后只要求最后两个,因为这总是我们想要的两个.

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.

所以如果 MyDate.getMonth() 返回 9,它将是:

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

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

所以添加 .slice(-2) 给我们最后两个字符,即:

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

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

但是如果 MyDate.getMonth() 返回 10,它将是:

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

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

所以添加 .slice(-2) 给我们最后两个字符,或者:

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

("0" + "10").slice(-2)
"10"

这篇关于Javascript 添加前导零到日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆