[英]displaying a date format, using a regular expression
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.
问题是我一直在控制台中获取的值为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: 代替使用
toDateString
,使用date方法来逐步构建字符串:
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.