abc*_*123 116
//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));
Run Code Online (Sandbox Code Playgroud)
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));
Run Code Online (Sandbox Code Playgroud)
Mar*_*sch 49
Given a date object:
date.getFullYear().toString().substr(2,2);
Run Code Online (Sandbox Code Playgroud)
It returns the number as string. If you want it as integer just wrap it inside the parseInt() function:
var twoDigitsYear = parseInt(date.getFullYear().toString().substr(2,2), 10);
Run Code Online (Sandbox Code Playgroud)
Example with the current year in one line:
var twoDigitsCurrentYear = parseInt(new Date().getFullYear().toString().substr(2,2));
Run Code Online (Sandbox Code Playgroud)
Ric*_*ner 12
var d = new Date();
var n = d.getFullYear();
Run Code Online (Sandbox Code Playgroud)
Yes, n will give you the 4 digit year, but you can always use substring or something similar to split up the year, thus giving you only two digits:
var final = n.toString().substring(2);
Run Code Online (Sandbox Code Playgroud)
This will give you the last two digits of the year (2013 will become 13, etc...)
如果有更好的方法,希望有人发布它!这是我能想到的唯一方法.如果有效,请告诉我们!
var currentYear = (new Date()).getFullYear();
var twoLastDigits = currentYear%100;
var formatedTwoLastDigits = "";
if (twoLastDigits <10 ) {
formatedTwoLastDigits = "0" + twoLastDigits;
} else {
formatedTwoLastDigits = "" + twoLastDigits;
}
Run Code Online (Sandbox Code Playgroud)
another version:
var yy = (new Date().getFullYear()+'').slice(-2);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
97534 次 |
最近记录: |