gpt4 book ai didi

JavaScript 日期 : How to add a year to a string that contains mm/dd?

转载 作者:行者123 更新时间:2023-11-30 13:40:49 25 4
gpt4 key购买 nike

我有一个包含月份/日期的字符串,我需要插入年份。字符串看起来像:

Last Mark:: 2/27 6:57 PM

我想将字符串转换成如下形式:

Last Mark:: 2010/02/27 18:57

在这种情况下,不会有超过一年的条目。例如,如果日期是 10 月 12 日,则可以假设年份是 2009 年。

最好的方法是什么?

最佳答案

来自 Adam's suggestion :

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"

关于JavaScript 日期 : How to add a year to a string that contains mm/dd?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2351500/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com