Javascript添加前导零到目前为止 [英] Javascript add leading zeroes to date

查看:586
本文介绍了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)给我们 last 两个字符字符串。

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) on给我们最后两个字符:

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天全站免登陆