我正在尝试找到一些以这种格式写出当前日期的JavaScript代码:mmddyy
我发现的所有内容都使用4位数年份,我需要2位数。
答案 0 :(得分:98)
//pull the last two digits of the year
//logs to console
//creates a new date object (has the current date and time by default)
//gets the full year from the date object (currently 2017)
//converts the variable to a string
//gets the substring backwards by 2 characters (last two characters)
console.log(new Date().getFullYear().toString().substr(-2));
<强> JavaScript的:强>
//A function for formatting a date to MMddyy
function formatDate(d)
{
//get the month
var month = d.getMonth();
//get the day
//convert day to string
var day = d.getDate().toString();
//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
//converts month to a string
month = (month + 1).toString();
//if month is 1-9 pad right with a 0 for two digits
if (month.length === 1)
{
month = "0" + month;
}
//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));
答案 1 :(得分:47)
给定日期对象:
date.getFullYear().toString().substr(2,2);
它将数字作为字符串返回。如果你想把它作为整数,只需将它包装在 parseInt()函数中:
var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);
当前年份在一行中的示例:
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));
答案 2 :(得分:12)
var d = new Date();
var n = d.getFullYear();
是的,n会给你4位数的年份,但你总是可以使用子串或类似的东西来分割年份,因此只给你两位数:
var final = n.toString().substring(2);
这将为您提供当年的最后两位数字(2013年将变为13,等等......)
如果有更好的方法,希望有人发布它!这是我能想到的唯一方法。如果有效,请告诉我们!
答案 3 :(得分:7)
var currentYear = (new Date()).getFullYear();
var twoLastDigits = currentYear%100;
var formatedTwoLastDigits = "";
if (twoLastDigits <10 ) {
formatedTwoLastDigits = "0" + twoLastDigits;
} else {
formatedTwoLastDigits = "" + twoLastDigits;
}
答案 4 :(得分:6)
另一个版本:
var yy = (new Date().getFullYear()+'').slice(-2);