如何获得2位数的年份w / Javascript? [英] How to get 2 digit year w/ Javascript?
本文介绍了如何获得2位数的年份w / Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试找到一些JavaScript代码,将以以下格式写入当前日期:mmddyy
我发现的一切使用4位数字,我需要2位数
解决方案
这个问题的具体答案见下面两行:
//拉出yearconsole.log的最后两位数(new Date()。getFullYear()。toString() .substr(-2));
格式化全日期时间示例(MMddyy): jsFiddle
JavaScript:
//将日期格式化为MMddyyfunction的函数formatDate(d){//获取月份var month = d.getMonth(); // get the day var day = d.getDate(); //获取年份var year = d.getFullYear(); //拉出年份的最后两位数= year.toString()。substr(-2); //由于月份为0,索引月份=月+ 1; //将月份转换为字符串month = month +; // if month is 1-9 pad right with a 0 for two digits if(month.length == 1){month =0+ month; } //将day转换为string day = day +; // if day is between 1-9 pad right with a 0 for two digits if(day.length == 1){day =0+ day; } //返回字符串MMddyyreturn month + day + year;} var d = new Date(); console.log(formatDate(d));
/ div>
I am trying to find some javascript code that will write the current date in this format: mmddyy
Everything I have found uses 4 digit years and I need 2 digit.
解决方案
The specific answer to this question is found in these two lines below:
//pull the last two digits of the year
console.log(new Date().getFullYear().toString().substr(-2));
Formatting Full Date Time Example (MMddyy): jsFiddle
JavaScript:
//A function for formatting a date to MMddyy
function formatDate(d)
{
//get the month
var month = d.getMonth();
//get the day
var day = d.getDate();
//get the year
var year = d.getFullYear();
//pull the last two digits of the year
year = year.toString().substr(-2);
//increment month by 1 since it is 0 indexed
month = month + 1;
//converts month to a string
month = month + "";
//if month is 1-9 pad right with a 0 for two digits
if (month.length == 1)
{
month = "0" + month;
}
//convert day to string
day = day + "";
//if day is between 1-9 pad right with a 0 for two digits
if (day.length == 1)
{
day = "0" + day;
}
//return the string "MMddyy"
return month + day + year;
}
var d = new Date();
console.log(formatDate(d));
这篇关于如何获得2位数的年份w / Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文