我正在使用 Datjs从用户那里获取日期并将其转换为适合存储在我的数据库中的格式。当我提供包含月、日和年的日期时,我得到了我想要的,日期格式为年-月-日:
var d1 = Date.parse('02/22/1984');
console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-02-22'
但是,当我只给出一年时,我会返回同一年,然后是今天的月份和日期:
var d1 = Date.parse('1984');
console.log(d1.toString('yyyy-MM-dd')); //Prints '1984-12-19'
我该怎么做才能确保当用户仅输入年份时,仅以下列格式返回该年份
1984-00-00
同样,如果只给出月份和年份,我希望它的格式如下:
1984-02-00
最佳答案
Datejs 返回一个 JavaScript Date
对象。该对象旨在表示一个时间点,而一个时间点必然包括月和日。如果未提供,Datejs 会将这些值默认为当前月份和日期。如果您不想显示该信息,请更改您的格式设置模式:
var d1 = Date.parse('1984');
console.log(d1.toString('yyyy')); // prints 1984
如果您需要根据用户最初输入的内容更改模式,则需要保存该信息,以便您知道以后要打印什么。
一个简单的例子如下:
function DatePrinter(input) {
var s = input.split("/").length;
this.fmt = ["dd", "MM", "yyyy"].slice(3 - s).reverse().join("-");
this.date = Date.parse(input);
}
DatePrinter.prototype.toString = function() {
return (this.date.toString(this.fmt) + "-00-00").slice(0, 10);
}
一些测试:
new DatePrinter("02/22/1984").toString() // "1984-02-22"
new DatePrinter("02/1984").toString() // "1984-02-00"
new DatePrinter("1984").toString() // "1984-00-00"
关于javascript - 当只给出年份时,如何让 Datejs 只返回年份?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8566801/