【发布时间】:2010-02-28 15:28:32
【问题描述】:
我有一个包含月份/日期的字符串,我需要插入年份。字符串看起来像:
Last Mark:: 2/27 6:57 PM
我想将字符串转换为:
Last Mark:: 2010/02/27 18:57
在这种情况下,不会有任何超过一年的条目。例如,如果日期是 10 月 12 日,则可以假定年份是 2009 年。
最好的方法是什么?
【问题讨论】:
标签: javascript date
我有一个包含月份/日期的字符串,我需要插入年份。字符串看起来像:
Last Mark:: 2/27 6:57 PM
我想将字符串转换为:
Last Mark:: 2010/02/27 18:57
在这种情况下,不会有任何超过一年的条目。例如,如果日期是 10 月 12 日,则可以假定年份是 2009 年。
最好的方法是什么?
【问题讨论】:
标签: javascript date
function convertDate(yourDate) {
var today = new Date();
var newDate = new Date(today.getFullYear() + '/' + yourDate);
// If newDate is in the future, subtract 1 from year
if (newDate > today)
newDate.setFullYear(newDate.getFullYear() - 1);
// Get the month and day value from newDate
var month = newDate.getMonth() + 1;
var day = newDate.getDate();
// Add the 0 padding to months and days smaller than 10
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
// Return a string in YYYY/MM/DD HH:MM format
return newDate.getFullYear() + '/' +
month + '/' +
day + ' ' +
newDate.getHours() + ':' +
newDate.getMinutes();
}
convertDate('2/27 6:57 PM'); // Returns: "2010/02/27 18:57"
convertDate('3/27 6:57 PM'); // Returns: "2009/03/27 18:57"
【讨论】:
添加THIS年份的代码很简单
var d = Date();
var withYear = d.getFullYear() + yourDate;
但是,考虑是今年还是去年的逻辑可能更难做到
我会这样想:获取今天的日期。如果日期比今天高,是去年,所以加d.getFullYear()-1,否则加d.getFullYear()
【讨论】:
返回当前年份:
var d = new Date();
var year = d.getFullYear();
要判断是否是今年,你可以将日期和月份与当前日期和月份进行比较,如果需要,从年份中减去 1。
从 Date 对象中获取日期和月份:
d.getMonth(); // warning this is 0-indexed (0-11)
d.getDate(); // this is 1-indexed (1-31)
【讨论】: