How to get 2 digit year w/ Javascript?
本问题已经有最佳答案,请猛点这里访问。
我正在尝试找到一些javascript代码,这些代码将以以下格式写入当前日期:mmddyy
我发现的所有东西都是4位数的年份,我需要2位数。
这个问题的具体答案可以在下面的这一行中找到:
1 2 3 4 5 6 7 | //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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | //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 | date.getFullYear().toString().substr(2,2); |
它以字符串形式返回数字。如果希望它是整数,只需将其包装在parseInt()函数中:
1 | var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10); |
以当前年份为一行的示例:
1 | var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2)); |
1 2 | var d = new Date(); var n = d.getFullYear(); |
是的,n会给你4位数的年份,但是你可以使用子字符串或类似的方法来拆分年份,因此只给你两位数:
1 | var final = n.toString().substring(2); |
这将给您一年中最后两位数字(2013年将变为13等)。
如果有更好的方法,希望有人发布!这是我唯一能想到的方法。如果可行,请通知我们!
1 2 3 4 5 6 7 8 9 10 | var currentYear = (new Date()).getFullYear(); var twoLastDigits = currentYear%100; var formatedTwoLastDigits =""; if (twoLastDigits <10 ) { formatedTwoLastDigits ="0" + twoLastDigits; } else { formatedTwoLastDigits ="" + twoLastDigits; } |
其他版本:
1 | var yy = (new Date().getFullYear()+'').slice(-2); |