I have hopefully a very simple question. What I want to do is convert the date object I create to match the format of a regular expression. The problem is is that the value I keep getting in my console is null. Any suggestions on how I can modify my code to have the date's format that of the regular expression I created?
function getDate() {
var newdate = new Date();
var results = newdate.toDateString();
var exp = new RegExp("[0-9]{4}\\.\[0-9]{2}\\.\[0-9]{2}");
var newresults = results.match(exp);
console.log(newresults);
}
Instead of using toDateString
, use the date methods to build up your string piece by piece:
var results = newdate.getFullYear() + '.' +
newdate.getMonth() + '.' + newdate.getDate();
It's impossible to tell if you wanted month then day or day then month, so flip them if you need to.
Edit: you need to pad zeros on the month and day to fit the regex:
String.prototype.padZero = function () {
if (this.length === 1) {
return '0' + this;
} else {
return this;
}
};
var year = newdate.getFullYear();
var month = newdate.getMonth().toString();
var day = newdate.getDate().toString();
var results = year + '.' + month.padZero() + '.' + day.padZero();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.